3c5a3beb379fa144f17682be372fa7abfc99da06
[oota-llvm.git] / lib / MC / WinCOFFStreamer.cpp
1 //===-- llvm/MC/WinCOFFStreamer.cpp -----------------------------*- C++ -*-===//
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 // This file contains an implementation of a Win32 COFF object file streamer.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "WinCOFFStreamer"
15
16 #include "llvm/MC/MCObjectStreamer.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/Target/TargetRegistry.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/ADT/StringMap.h"
29
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35
36 namespace {
37 class WinCOFFStreamer : public MCObjectStreamer {
38 public:
39   MCSymbol const *CurSymbol;
40
41   WinCOFFStreamer(MCContext &Context,
42                   TargetAsmBackend &TAB,
43                   MCCodeEmitter &CE,
44                   raw_ostream &OS);
45
46   void AddCommonSymbol(MCSymbol *Symbol, uint64_t Size,
47                        unsigned ByteAlignment, bool External);
48
49   // MCStreamer interface
50
51   virtual void InitSections();
52   virtual void EmitLabel(MCSymbol *Symbol);
53   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
54   virtual void EmitThumbFunc(MCSymbol *Func);
55   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
56   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
57   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
58   virtual void BeginCOFFSymbolDef(MCSymbol const *Symbol);
59   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
60   virtual void EmitCOFFSymbolType(int Type);
61   virtual void EndCOFFSymbolDef();
62   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
63   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
64                                 unsigned ByteAlignment);
65   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
66   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
67                             unsigned Size,unsigned ByteAlignment);
68   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
69                               uint64_t Size, unsigned ByteAlignment);
70   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
71   virtual void EmitValue(const MCExpr *Value, unsigned Size,
72                          unsigned AddrSpace);
73   virtual void EmitGPRel32Value(const MCExpr *Value);
74   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
75                                    unsigned ValueSize, unsigned MaxBytesToEmit);
76   virtual void EmitCodeAlignment(unsigned ByteAlignment,
77                                  unsigned MaxBytesToEmit);
78   virtual void EmitValueToOffset(const MCExpr *Offset, unsigned char Value);
79   virtual void EmitFileDirective(StringRef Filename);
80   virtual void EmitDwarfFileDirective(unsigned FileNo,StringRef Filename);
81   virtual void EmitInstruction(const MCInst &Instruction);
82   virtual void Finish();
83
84 private:
85   virtual void EmitInstToFragment(const MCInst &Inst) {
86     llvm_unreachable("Not used by WinCOFF.");
87   }
88   virtual void EmitInstToData(const MCInst &Inst) {
89     llvm_unreachable("Not used by WinCOFF.");
90   }
91
92   void SetSection(StringRef Section,
93                   unsigned Characteristics,
94                   SectionKind Kind) {
95     SwitchSection(getContext().getCOFFSection(Section, Characteristics, Kind));
96   }
97
98   void SetSectionText() {
99     SetSection(".text",
100                COFF::IMAGE_SCN_CNT_CODE
101              | COFF::IMAGE_SCN_MEM_EXECUTE
102              | COFF::IMAGE_SCN_MEM_READ,
103                SectionKind::getText());
104     EmitCodeAlignment(4, 0);
105   }
106
107   void SetSectionData() {
108     SetSection(".data",
109                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
110              | COFF::IMAGE_SCN_MEM_READ
111              | COFF::IMAGE_SCN_MEM_WRITE,
112                SectionKind::getDataRel());
113     EmitCodeAlignment(4, 0);
114   }
115
116   void SetSectionBSS() {
117     SetSection(".bss",
118                COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
119              | COFF::IMAGE_SCN_MEM_READ
120              | COFF::IMAGE_SCN_MEM_WRITE,
121                SectionKind::getBSS());
122     EmitCodeAlignment(4, 0);
123   }
124
125 };
126 } // end anonymous namespace.
127
128 WinCOFFStreamer::WinCOFFStreamer(MCContext &Context,
129                                  TargetAsmBackend &TAB,
130                                  MCCodeEmitter &CE,
131                                  raw_ostream &OS)
132     : MCObjectStreamer(Context, TAB, OS, &CE, true)
133     , CurSymbol(NULL) {
134 }
135
136 void WinCOFFStreamer::AddCommonSymbol(MCSymbol *Symbol, uint64_t Size,
137                                       unsigned ByteAlignment, bool External) {
138   assert(!Symbol->isInSection() && "Symbol must not already have a section!");
139
140   std::string SectionName(".bss$linkonce");
141   SectionName.append(Symbol->getName().begin(), Symbol->getName().end());
142
143   MCSymbolData &SymbolData = getAssembler().getOrCreateSymbolData(*Symbol);
144
145   unsigned Characteristics =
146     COFF::IMAGE_SCN_LNK_COMDAT |
147     COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
148     COFF::IMAGE_SCN_MEM_READ |
149     COFF::IMAGE_SCN_MEM_WRITE;
150
151   int Selection = COFF::IMAGE_COMDAT_SELECT_LARGEST;
152
153   const MCSection *Section = MCStreamer::getContext().getCOFFSection(
154     SectionName, Characteristics, Selection, SectionKind::getBSS());
155
156   MCSectionData &SectionData = getAssembler().getOrCreateSectionData(*Section);
157
158   if (SectionData.getAlignment() < ByteAlignment)
159     SectionData.setAlignment(ByteAlignment);
160
161   SymbolData.setExternal(External);
162
163   Symbol->setSection(*Section);
164
165   if (ByteAlignment != 1)
166       new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectionData);
167
168   SymbolData.setFragment(new MCFillFragment(0, 0, Size, &SectionData));
169 }
170
171 // MCStreamer interface
172
173 void WinCOFFStreamer::InitSections() {
174   SetSectionText();
175   SetSectionData();
176   SetSectionBSS();
177   SetSectionText();
178 }
179
180 void WinCOFFStreamer::EmitLabel(MCSymbol *Symbol) {
181   // TODO: This is copied almost exactly from the MachOStreamer. Consider
182   // merging into MCObjectStreamer?
183   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
184   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
185   assert(CurSection && "Cannot emit before setting section!");
186
187   Symbol->setSection(*CurSection);
188
189   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
190
191   // FIXME: This is wasteful, we don't necessarily need to create a data
192   // fragment. Instead, we should mark the symbol as pointing into the data
193   // fragment if it exists, otherwise we should just queue the label and set its
194   // fragment pointer when we emit the next fragment.
195   MCDataFragment *DF = getOrCreateDataFragment();
196
197   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
198   SD.setFragment(DF);
199   SD.setOffset(DF->getContents().size());
200 }
201
202 void WinCOFFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
203   llvm_unreachable("not implemented");
204 }
205
206 void WinCOFFStreamer::EmitThumbFunc(MCSymbol *Func) {
207   llvm_unreachable("not implemented");
208 }
209
210 void WinCOFFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
211   assert((Symbol->isInSection()
212          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
213          : true) && "Got non COFF section in the COFF backend!");
214   // FIXME: This is all very ugly and depressing. What needs to happen here
215   // depends on quite a few things that are all part of relaxation, which we
216   // don't really even do.
217
218   if (Value->getKind() != MCExpr::SymbolRef) {
219     // TODO: This is exactly the same as MachOStreamer. Consider merging into
220     // MCObjectStreamer.
221     getAssembler().getOrCreateSymbolData(*Symbol);
222     AddValueSymbols(Value);
223     Symbol->setVariableValue(Value);
224   } else {
225     // FIXME: This is a horrible way to do this :(. This should really be
226     // handled after we are done with the MC* objects and immediately before
227     // writing out the object file when we know exactly what the symbol should
228     // look like in the coff symbol table. I'm not doing that now because the
229     // COFF object writer doesn't have a clearly defined separation between MC
230     // data structures, the object writers data structures, and the raw, POD,
231     // data structures that get written to disk.
232
233     // Copy over the aliased data.
234     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
235     const MCSymbolData &RealSD = getAssembler().getOrCreateSymbolData(
236       dyn_cast<const MCSymbolRefExpr>(Value)->getSymbol());
237
238     // FIXME: This is particularly nasty because it breaks as soon as any data
239     // members of MCSymbolData change.
240     SD.CommonAlign     = RealSD.CommonAlign;
241     SD.CommonSize      = RealSD.CommonSize;
242     SD.Flags           = RealSD.Flags;
243     SD.Fragment        = RealSD.Fragment;
244     SD.Index           = RealSD.Index;
245     SD.IsExternal      = RealSD.IsExternal;
246     SD.IsPrivateExtern = RealSD.IsPrivateExtern;
247     SD.Offset          = RealSD.Offset;
248     SD.SymbolSize      = RealSD.SymbolSize;
249   }
250 }
251
252 void WinCOFFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
253                                           MCSymbolAttr Attribute) {
254   assert(Symbol && "Symbol must be non-null!");
255   assert((Symbol->isInSection()
256          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
257          : true) && "Got non COFF section in the COFF backend!");
258   switch (Attribute) {
259   case MCSA_WeakReference:
260   case MCSA_Weak: {
261       MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
262       SD.modifyFlags(COFF::SF_WeakExternal, COFF::SF_WeakExternal);
263       SD.setExternal(true);
264     }
265     break;
266
267   case MCSA_Global:
268     getAssembler().getOrCreateSymbolData(*Symbol).setExternal(true);
269     break;
270
271   default:
272     llvm_unreachable("unsupported attribute");
273     break;
274   }
275 }
276
277 void WinCOFFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
278   llvm_unreachable("not implemented");
279 }
280
281 void WinCOFFStreamer::BeginCOFFSymbolDef(MCSymbol const *Symbol) {
282   assert((Symbol->isInSection()
283          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
284          : true) && "Got non COFF section in the COFF backend!");
285   assert(CurSymbol == NULL && "EndCOFFSymbolDef must be called between calls "
286                               "to BeginCOFFSymbolDef!");
287   CurSymbol = Symbol;
288 }
289
290 void WinCOFFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
291   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
292   assert((StorageClass & ~0xFF) == 0 && "StorageClass must only have data in "
293                                         "the first byte!");
294
295   getAssembler().getOrCreateSymbolData(*CurSymbol).modifyFlags(
296     StorageClass << COFF::SF_ClassShift,
297     COFF::SF_ClassMask);
298 }
299
300 void WinCOFFStreamer::EmitCOFFSymbolType(int Type) {
301   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
302   assert((Type & ~0xFFFF) == 0 && "Type must only have data in the first 2 "
303                                   "bytes");
304
305   getAssembler().getOrCreateSymbolData(*CurSymbol).modifyFlags(
306     Type << COFF::SF_TypeShift,
307     COFF::SF_TypeMask);
308 }
309
310 void WinCOFFStreamer::EndCOFFSymbolDef() {
311   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
312   CurSymbol = NULL;
313 }
314
315 void WinCOFFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
316   llvm_unreachable("not implemented");
317 }
318
319 void WinCOFFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
320                                        unsigned ByteAlignment) {
321   assert((Symbol->isInSection()
322          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
323          : true) && "Got non COFF section in the COFF backend!");
324   AddCommonSymbol(Symbol, Size, ByteAlignment, true);
325 }
326
327 void WinCOFFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
328   assert((Symbol->isInSection()
329          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
330          : true) && "Got non COFF section in the COFF backend!");
331   AddCommonSymbol(Symbol, Size, 1, false);
332 }
333
334 void WinCOFFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
335                                    unsigned Size,unsigned ByteAlignment) {
336   llvm_unreachable("not implemented");
337 }
338
339 void WinCOFFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
340                                      uint64_t Size, unsigned ByteAlignment) {
341   llvm_unreachable("not implemented");
342 }
343
344 void WinCOFFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
345   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
346   // MCObjectStreamer?
347   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
348 }
349
350 void WinCOFFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
351                                 unsigned AddrSpace) {
352   assert(AddrSpace == 0 && "Address space must be 0!");
353
354   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
355   // MCObjectStreamer?
356   MCDataFragment *DF = getOrCreateDataFragment();
357
358   // Avoid fixups when possible.
359   int64_t AbsValue;
360   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
361     // FIXME: Endianness assumption.
362     for (unsigned i = 0; i != Size; ++i)
363       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
364   } else {
365     DF->addFixup(MCFixup::Create(DF->getContents().size(),
366                                  AddValueSymbols(Value),
367                                  MCFixup::getKindForSize(Size)));
368     DF->getContents().resize(DF->getContents().size() + Size, 0);
369   }
370 }
371
372 void WinCOFFStreamer::EmitGPRel32Value(const MCExpr *Value) {
373   llvm_unreachable("not implemented");
374 }
375
376 void WinCOFFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
377                                            int64_t Value,
378                                            unsigned ValueSize,
379                                            unsigned MaxBytesToEmit) {
380   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
381   // MCObjectStreamer?
382   if (MaxBytesToEmit == 0)
383     MaxBytesToEmit = ByteAlignment;
384   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
385                       getCurrentSectionData());
386
387   // Update the maximum alignment on the current section if necessary.
388   if (ByteAlignment > getCurrentSectionData()->getAlignment())
389     getCurrentSectionData()->setAlignment(ByteAlignment);
390 }
391
392 void WinCOFFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
393                                         unsigned MaxBytesToEmit) {
394   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
395   // MCObjectStreamer?
396   if (MaxBytesToEmit == 0)
397     MaxBytesToEmit = ByteAlignment;
398   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
399                                            getCurrentSectionData());
400   F->setEmitNops(true);
401
402   // Update the maximum alignment on the current section if necessary.
403   if (ByteAlignment > getCurrentSectionData()->getAlignment())
404     getCurrentSectionData()->setAlignment(ByteAlignment);
405 }
406
407 void WinCOFFStreamer::EmitValueToOffset(const MCExpr *Offset,
408                                         unsigned char Value) {
409   llvm_unreachable("not implemented");
410 }
411
412 void WinCOFFStreamer::EmitFileDirective(StringRef Filename) {
413   // Ignore for now, linkers don't care, and proper debug
414   // info will be a much large effort.
415 }
416
417 void WinCOFFStreamer::EmitDwarfFileDirective(unsigned FileNo,
418                                              StringRef Filename) {
419   llvm_unreachable("not implemented");
420 }
421
422 void WinCOFFStreamer::EmitInstruction(const MCInst &Instruction) {
423   for (unsigned i = 0, e = Instruction.getNumOperands(); i != e; ++i)
424     if (Instruction.getOperand(i).isExpr())
425       AddValueSymbols(Instruction.getOperand(i).getExpr());
426
427   getCurrentSectionData()->setHasInstructions(true);
428
429   MCInstFragment *Fragment =
430     new MCInstFragment(Instruction, getCurrentSectionData());
431
432   raw_svector_ostream VecOS(Fragment->getCode());
433
434   getAssembler().getEmitter().EncodeInstruction(Instruction, VecOS,
435                                                 Fragment->getFixups());
436 }
437
438 void WinCOFFStreamer::Finish() {
439   MCObjectStreamer::Finish();
440 }
441
442 namespace llvm
443 {
444   MCStreamer *createWinCOFFStreamer(MCContext &Context,
445                                     TargetAsmBackend &TAB,
446                                     MCCodeEmitter &CE,
447                                     raw_ostream &OS,
448                                     bool RelaxAll) {
449     WinCOFFStreamer *S = new WinCOFFStreamer(Context, TAB, CE, OS);
450     S->getAssembler().setRelaxAll(RelaxAll);
451     return S;
452   }
453 }