Aligned bundling support. Following the discussion here:
[oota-llvm.git] / lib / MC / MCObjectStreamer.cpp
1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCObjectStreamer.h"
11 #include "llvm/MC/MCAsmBackend.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCCodeEmitter.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCDwarf.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/Support/ErrorHandling.h"
21 using namespace llvm;
22
23 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
24                                    raw_ostream &OS, MCCodeEmitter *Emitter_)
25   : MCStreamer(Context),
26     Assembler(new MCAssembler(Context, TAB,
27                               *Emitter_, *TAB.createObjectWriter(OS),
28                               OS)),
29     CurSectionData(0)
30 {
31 }
32
33 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
34                                    raw_ostream &OS, MCCodeEmitter *Emitter_,
35                                    MCAssembler *_Assembler)
36   : MCStreamer(Context), Assembler(_Assembler), CurSectionData(0)
37 {
38 }
39
40 MCObjectStreamer::~MCObjectStreamer() {
41   delete &Assembler->getBackend();
42   delete &Assembler->getEmitter();
43   delete &Assembler->getWriter();
44   delete Assembler;
45 }
46
47 void MCObjectStreamer::reset() {
48   if (Assembler)
49     Assembler->reset();
50   MCStreamer::reset();
51 }
52
53 MCFragment *MCObjectStreamer::getCurrentFragment() const {
54   assert(getCurrentSectionData() && "No current section!");
55
56   if (!getCurrentSectionData()->empty())
57     return &getCurrentSectionData()->getFragmentList().back();
58
59   return 0;
60 }
61
62 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
63   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
64   if (!F)
65     F = new MCDataFragment(getCurrentSectionData());
66   return F;
67 }
68
69 const MCExpr *MCObjectStreamer::AddValueSymbols(const MCExpr *Value) {
70   switch (Value->getKind()) {
71   case MCExpr::Target:
72     cast<MCTargetExpr>(Value)->AddValueSymbols(Assembler);
73     break;
74
75   case MCExpr::Constant:
76     break;
77
78   case MCExpr::Binary: {
79     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
80     AddValueSymbols(BE->getLHS());
81     AddValueSymbols(BE->getRHS());
82     break;
83   }
84
85   case MCExpr::SymbolRef:
86     Assembler->getOrCreateSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
87     break;
88
89   case MCExpr::Unary:
90     AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
91     break;
92   }
93
94   return Value;
95 }
96
97 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
98                                      unsigned AddrSpace) {
99   assert(AddrSpace == 0 && "Address space must be 0!");
100   MCDataFragment *DF = getOrCreateDataFragment();
101
102   // Avoid fixups when possible.
103   int64_t AbsValue;
104   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue, getAssembler())) {
105     EmitIntValue(AbsValue, Size, AddrSpace);
106     return;
107   }
108   DF->getFixups().push_back(
109       MCFixup::Create(DF->getContents().size(), Value,
110                       MCFixup::getKindForSize(Size, false)));
111   DF->getContents().resize(DF->getContents().size() + Size, 0);
112 }
113
114 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
115   RecordProcStart(Frame);
116 }
117
118 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
119   RecordProcEnd(Frame);
120 }
121
122 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
123   MCStreamer::EmitLabel(Symbol);
124
125   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
126
127   // FIXME: This is wasteful, we don't necessarily need to create a data
128   // fragment. Instead, we should mark the symbol as pointing into the data
129   // fragment if it exists, otherwise we should just queue the label and set its
130   // fragment pointer when we emit the next fragment.
131   MCDataFragment *F = getOrCreateDataFragment();
132   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
133   SD.setFragment(F);
134   SD.setOffset(F->getContents().size());
135 }
136
137 void MCObjectStreamer::EmitDebugLabel(MCSymbol *Symbol) {
138   EmitLabel(Symbol);
139 }
140
141 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
142   int64_t IntValue;
143   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
144     EmitULEB128IntValue(IntValue);
145     return;
146   }
147   Value = ForceExpAbs(Value);
148   new MCLEBFragment(*Value, false, getCurrentSectionData());
149 }
150
151 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
152   int64_t IntValue;
153   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
154     EmitSLEB128IntValue(IntValue);
155     return;
156   }
157   Value = ForceExpAbs(Value);
158   new MCLEBFragment(*Value, true, getCurrentSectionData());
159 }
160
161 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
162                                          const MCSymbol *Symbol) {
163   report_fatal_error("This file format doesn't support weak aliases.");
164 }
165
166 void MCObjectStreamer::ChangeSection(const MCSection *Section) {
167   assert(Section && "Cannot switch to a null section!");
168
169   CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
170 }
171
172 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
173   getAssembler().getOrCreateSymbolData(*Symbol);
174   Symbol->setVariableValue(AddValueSymbols(Value));
175 }
176
177 void MCObjectStreamer::EmitInstruction(const MCInst &Inst) {
178   // Scan for values.
179   for (unsigned i = Inst.getNumOperands(); i--; )
180     if (Inst.getOperand(i).isExpr())
181       AddValueSymbols(Inst.getOperand(i).getExpr());
182
183   MCSectionData *SD = getCurrentSectionData();
184   SD->setHasInstructions(true);
185
186   // Now that a machine instruction has been assembled into this section, make
187   // a line entry for any .loc directive that has been seen.
188   MCLineEntry::Make(this, getCurrentSection());
189
190   // If this instruction doesn't need relaxation, just emit it as data.
191   MCAssembler &Assembler = getAssembler();
192   if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
193     EmitInstToData(Inst);
194     return;
195   }
196
197   // Otherwise, relax and emit it as data if either:
198   // - The RelaxAll flag was passed
199   // - Bundling is enabled and this instruction is inside a bundle-locked
200   //   group. We want to emit all such instructions into the same data
201   //   fragment.
202   if (Assembler.getRelaxAll() ||
203       (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
204     MCInst Relaxed;
205     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
206     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
207       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
208     EmitInstToData(Relaxed);
209     return;
210   }
211
212   // Otherwise emit to a separate fragment.
213   EmitInstToFragment(Inst);
214 }
215
216 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst) {
217   // Always create a new, separate fragment here, because its size can change
218   // during relaxation.
219   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
220
221   SmallString<128> Code;
222   raw_svector_ostream VecOS(Code);
223   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups());
224   VecOS.flush();
225   IF->getContents().append(Code.begin(), Code.end());
226 }
227
228 const char *BundlingNotImplementedMsg =
229   "Aligned bundling is not implemented for this object format";
230
231 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
232   llvm_unreachable(BundlingNotImplementedMsg);
233 }
234
235 void MCObjectStreamer::EmitBundleLock() {
236   llvm_unreachable(BundlingNotImplementedMsg);
237 }
238
239 void MCObjectStreamer::EmitBundleUnlock() {
240   llvm_unreachable(BundlingNotImplementedMsg);
241 }
242
243 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
244                                                 const MCSymbol *LastLabel,
245                                                 const MCSymbol *Label,
246                                                 unsigned PointerSize) {
247   if (!LastLabel) {
248     EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
249     return;
250   }
251   const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
252   int64_t Res;
253   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
254     MCDwarfLineAddr::Emit(this, LineDelta, Res);
255     return;
256   }
257   AddrDelta = ForceExpAbs(AddrDelta);
258   new MCDwarfLineAddrFragment(LineDelta, *AddrDelta, getCurrentSectionData());
259 }
260
261 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
262                                                  const MCSymbol *Label) {
263   const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
264   int64_t Res;
265   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
266     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
267     return;
268   }
269   AddrDelta = ForceExpAbs(AddrDelta);
270   new MCDwarfCallFrameFragment(*AddrDelta, getCurrentSectionData());
271 }
272
273 void MCObjectStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
274   assert(AddrSpace == 0 && "Address space must be 0!");
275   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
276 }
277
278 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
279                                             int64_t Value,
280                                             unsigned ValueSize,
281                                             unsigned MaxBytesToEmit) {
282   if (MaxBytesToEmit == 0)
283     MaxBytesToEmit = ByteAlignment;
284   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
285                       getCurrentSectionData());
286
287   // Update the maximum alignment on the current section if necessary.
288   if (ByteAlignment > getCurrentSectionData()->getAlignment())
289     getCurrentSectionData()->setAlignment(ByteAlignment);
290 }
291
292 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
293                                          unsigned MaxBytesToEmit) {
294   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
295   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
296 }
297
298 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
299                                          unsigned char Value) {
300   int64_t Res;
301   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
302     new MCOrgFragment(*Offset, Value, getCurrentSectionData());
303     return false;
304   }
305
306   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
307   EmitLabel(CurrentPos);
308   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
309   const MCExpr *Ref =
310     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
311   const MCExpr *Delta =
312     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
313
314   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
315     return true;
316   EmitFill(Res, Value, 0);
317   return false;
318 }
319
320 // Associate GPRel32 fixup with data and resize data area
321 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
322   MCDataFragment *DF = getOrCreateDataFragment();
323
324   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
325                                             Value, FK_GPRel_4));
326   DF->getContents().resize(DF->getContents().size() + 4, 0);
327 }
328
329 // Associate GPRel32 fixup with data and resize data area
330 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
331   MCDataFragment *DF = getOrCreateDataFragment();
332
333   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
334                                             Value, FK_GPRel_4));
335   DF->getContents().resize(DF->getContents().size() + 8, 0);
336 }
337
338 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
339                                 unsigned AddrSpace) {
340   assert(AddrSpace == 0 && "Address space must be 0!");
341   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
342   //        problems evaluating expressions across multiple fragments.
343   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
344 }
345
346 void MCObjectStreamer::FinishImpl() {
347   // Dump out the dwarf file & directory tables and line tables.
348   const MCSymbol *LineSectionSymbol = NULL;
349   if (getContext().hasDwarfFiles())
350     LineSectionSymbol = MCDwarfFileTable::Emit(this);
351
352   // If we are generating dwarf for assembly source files dump out the sections.
353   if (getContext().getGenDwarfForAssembly())
354     MCGenDwarfInfo::Emit(this, LineSectionSymbol);
355
356   getAssembler().Finish();
357 }