Don't use PadSectionToAlignment on windows.
[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 EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
72                                    unsigned ValueSize, unsigned MaxBytesToEmit);
73   virtual void EmitCodeAlignment(unsigned ByteAlignment,
74                                  unsigned MaxBytesToEmit);
75   virtual void EmitFileDirective(StringRef Filename);
76   virtual void EmitInstruction(const MCInst &Instruction);
77   virtual void Finish();
78
79 private:
80   virtual void EmitInstToFragment(const MCInst &Inst) {
81     llvm_unreachable("Not used by WinCOFF.");
82   }
83   virtual void EmitInstToData(const MCInst &Inst) {
84     llvm_unreachable("Not used by WinCOFF.");
85   }
86
87   void SetSection(StringRef Section,
88                   unsigned Characteristics,
89                   SectionKind Kind) {
90     SwitchSection(getContext().getCOFFSection(Section, Characteristics, Kind));
91   }
92
93   void SetSectionText() {
94     SetSection(".text",
95                COFF::IMAGE_SCN_CNT_CODE
96              | COFF::IMAGE_SCN_MEM_EXECUTE
97              | COFF::IMAGE_SCN_MEM_READ,
98                SectionKind::getText());
99     EmitCodeAlignment(4, 0);
100   }
101
102   void SetSectionData() {
103     SetSection(".data",
104                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
105              | COFF::IMAGE_SCN_MEM_READ
106              | COFF::IMAGE_SCN_MEM_WRITE,
107                SectionKind::getDataRel());
108     EmitCodeAlignment(4, 0);
109   }
110
111   void SetSectionBSS() {
112     SetSection(".bss",
113                COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
114              | COFF::IMAGE_SCN_MEM_READ
115              | COFF::IMAGE_SCN_MEM_WRITE,
116                SectionKind::getBSS());
117     EmitCodeAlignment(4, 0);
118   }
119
120 };
121 } // end anonymous namespace.
122
123 WinCOFFStreamer::WinCOFFStreamer(MCContext &Context,
124                                  TargetAsmBackend &TAB,
125                                  MCCodeEmitter &CE,
126                                  raw_ostream &OS)
127     : MCObjectStreamer(Context, TAB, OS, &CE, false)
128     , CurSymbol(NULL) {
129 }
130
131 void WinCOFFStreamer::AddCommonSymbol(MCSymbol *Symbol, uint64_t Size,
132                                       unsigned ByteAlignment, bool External) {
133   assert(!Symbol->isInSection() && "Symbol must not already have a section!");
134
135   std::string SectionName(".bss$linkonce");
136   SectionName.append(Symbol->getName().begin(), Symbol->getName().end());
137
138   MCSymbolData &SymbolData = getAssembler().getOrCreateSymbolData(*Symbol);
139
140   unsigned Characteristics =
141     COFF::IMAGE_SCN_LNK_COMDAT |
142     COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
143     COFF::IMAGE_SCN_MEM_READ |
144     COFF::IMAGE_SCN_MEM_WRITE;
145
146   int Selection = COFF::IMAGE_COMDAT_SELECT_LARGEST;
147
148   const MCSection *Section = MCStreamer::getContext().getCOFFSection(
149     SectionName, Characteristics, Selection, SectionKind::getBSS());
150
151   MCSectionData &SectionData = getAssembler().getOrCreateSectionData(*Section);
152
153   if (SectionData.getAlignment() < ByteAlignment)
154     SectionData.setAlignment(ByteAlignment);
155
156   SymbolData.setExternal(External);
157
158   Symbol->setSection(*Section);
159
160   if (ByteAlignment != 1)
161       new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectionData);
162
163   SymbolData.setFragment(new MCFillFragment(0, 0, Size, &SectionData));
164 }
165
166 // MCStreamer interface
167
168 void WinCOFFStreamer::InitSections() {
169   SetSectionText();
170   SetSectionData();
171   SetSectionBSS();
172   SetSectionText();
173 }
174
175 void WinCOFFStreamer::EmitLabel(MCSymbol *Symbol) {
176   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
177   MCObjectStreamer::EmitLabel(Symbol);
178 }
179
180 void WinCOFFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
181   llvm_unreachable("not implemented");
182 }
183
184 void WinCOFFStreamer::EmitThumbFunc(MCSymbol *Func) {
185   llvm_unreachable("not implemented");
186 }
187
188 void WinCOFFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
189   assert((Symbol->isInSection()
190          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
191          : true) && "Got non COFF section in the COFF backend!");
192   // FIXME: This is all very ugly and depressing. What needs to happen here
193   // depends on quite a few things that are all part of relaxation, which we
194   // don't really even do.
195
196   if (Value->getKind() != MCExpr::SymbolRef) {
197     // TODO: This is exactly the same as MachOStreamer. Consider merging into
198     // MCObjectStreamer.
199     getAssembler().getOrCreateSymbolData(*Symbol);
200     AddValueSymbols(Value);
201     Symbol->setVariableValue(Value);
202   } else {
203     // FIXME: This is a horrible way to do this :(. This should really be
204     // handled after we are done with the MC* objects and immediately before
205     // writing out the object file when we know exactly what the symbol should
206     // look like in the coff symbol table. I'm not doing that now because the
207     // COFF object writer doesn't have a clearly defined separation between MC
208     // data structures, the object writers data structures, and the raw, POD,
209     // data structures that get written to disk.
210
211     // Copy over the aliased data.
212     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
213     const MCSymbolData &RealSD = getAssembler().getOrCreateSymbolData(
214       dyn_cast<const MCSymbolRefExpr>(Value)->getSymbol());
215
216     // FIXME: This is particularly nasty because it breaks as soon as any data
217     // members of MCSymbolData change.
218     SD.CommonAlign     = RealSD.CommonAlign;
219     SD.CommonSize      = RealSD.CommonSize;
220     SD.Flags           = RealSD.Flags;
221     SD.Fragment        = RealSD.Fragment;
222     SD.Index           = RealSD.Index;
223     SD.IsExternal      = RealSD.IsExternal;
224     SD.IsPrivateExtern = RealSD.IsPrivateExtern;
225     SD.Offset          = RealSD.Offset;
226     SD.SymbolSize      = RealSD.SymbolSize;
227   }
228 }
229
230 void WinCOFFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
231                                           MCSymbolAttr Attribute) {
232   assert(Symbol && "Symbol must be non-null!");
233   assert((Symbol->isInSection()
234          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
235          : true) && "Got non COFF section in the COFF backend!");
236   switch (Attribute) {
237   case MCSA_WeakReference:
238   case MCSA_Weak: {
239       MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
240       SD.modifyFlags(COFF::SF_WeakExternal, COFF::SF_WeakExternal);
241       SD.setExternal(true);
242     }
243     break;
244
245   case MCSA_Global:
246     getAssembler().getOrCreateSymbolData(*Symbol).setExternal(true);
247     break;
248
249   default:
250     llvm_unreachable("unsupported attribute");
251     break;
252   }
253 }
254
255 void WinCOFFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
256   llvm_unreachable("not implemented");
257 }
258
259 void WinCOFFStreamer::BeginCOFFSymbolDef(MCSymbol const *Symbol) {
260   assert((Symbol->isInSection()
261          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
262          : true) && "Got non COFF section in the COFF backend!");
263   assert(CurSymbol == NULL && "EndCOFFSymbolDef must be called between calls "
264                               "to BeginCOFFSymbolDef!");
265   CurSymbol = Symbol;
266 }
267
268 void WinCOFFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
269   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
270   assert((StorageClass & ~0xFF) == 0 && "StorageClass must only have data in "
271                                         "the first byte!");
272
273   getAssembler().getOrCreateSymbolData(*CurSymbol).modifyFlags(
274     StorageClass << COFF::SF_ClassShift,
275     COFF::SF_ClassMask);
276 }
277
278 void WinCOFFStreamer::EmitCOFFSymbolType(int Type) {
279   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
280   assert((Type & ~0xFFFF) == 0 && "Type must only have data in the first 2 "
281                                   "bytes");
282
283   getAssembler().getOrCreateSymbolData(*CurSymbol).modifyFlags(
284     Type << COFF::SF_TypeShift,
285     COFF::SF_TypeMask);
286 }
287
288 void WinCOFFStreamer::EndCOFFSymbolDef() {
289   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
290   CurSymbol = NULL;
291 }
292
293 void WinCOFFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
294   llvm_unreachable("not implemented");
295 }
296
297 void WinCOFFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
298                                        unsigned ByteAlignment) {
299   assert((Symbol->isInSection()
300          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
301          : true) && "Got non COFF section in the COFF backend!");
302   AddCommonSymbol(Symbol, Size, ByteAlignment, true);
303 }
304
305 void WinCOFFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
306   assert((Symbol->isInSection()
307          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
308          : true) && "Got non COFF section in the COFF backend!");
309   AddCommonSymbol(Symbol, Size, 1, false);
310 }
311
312 void WinCOFFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
313                                    unsigned Size,unsigned ByteAlignment) {
314   llvm_unreachable("not implemented");
315 }
316
317 void WinCOFFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
318                                      uint64_t Size, unsigned ByteAlignment) {
319   llvm_unreachable("not implemented");
320 }
321
322 void WinCOFFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
323   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
324   // MCObjectStreamer?
325   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
326 }
327
328 void WinCOFFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
329                                            int64_t Value,
330                                            unsigned ValueSize,
331                                            unsigned MaxBytesToEmit) {
332   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
333   // MCObjectStreamer?
334   if (MaxBytesToEmit == 0)
335     MaxBytesToEmit = ByteAlignment;
336   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
337                       getCurrentSectionData());
338
339   // Update the maximum alignment on the current section if necessary.
340   if (ByteAlignment > getCurrentSectionData()->getAlignment())
341     getCurrentSectionData()->setAlignment(ByteAlignment);
342 }
343
344 void WinCOFFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
345                                         unsigned MaxBytesToEmit) {
346   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
347   // MCObjectStreamer?
348   if (MaxBytesToEmit == 0)
349     MaxBytesToEmit = ByteAlignment;
350   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
351                                            getCurrentSectionData());
352   F->setEmitNops(true);
353
354   // Update the maximum alignment on the current section if necessary.
355   if (ByteAlignment > getCurrentSectionData()->getAlignment())
356     getCurrentSectionData()->setAlignment(ByteAlignment);
357 }
358
359 void WinCOFFStreamer::EmitFileDirective(StringRef Filename) {
360   // Ignore for now, linkers don't care, and proper debug
361   // info will be a much large effort.
362 }
363
364 void WinCOFFStreamer::EmitInstruction(const MCInst &Instruction) {
365   for (unsigned i = 0, e = Instruction.getNumOperands(); i != e; ++i)
366     if (Instruction.getOperand(i).isExpr())
367       AddValueSymbols(Instruction.getOperand(i).getExpr());
368
369   getCurrentSectionData()->setHasInstructions(true);
370
371   MCInstFragment *Fragment =
372     new MCInstFragment(Instruction, getCurrentSectionData());
373
374   raw_svector_ostream VecOS(Fragment->getCode());
375
376   getAssembler().getEmitter().EncodeInstruction(Instruction, VecOS,
377                                                 Fragment->getFixups());
378 }
379
380 void WinCOFFStreamer::Finish() {
381   MCObjectStreamer::Finish();
382 }
383
384 namespace llvm
385 {
386   MCStreamer *createWinCOFFStreamer(MCContext &Context,
387                                     TargetAsmBackend &TAB,
388                                     MCCodeEmitter &CE,
389                                     raw_ostream &OS,
390                                     bool RelaxAll) {
391     WinCOFFStreamer *S = new WinCOFFStreamer(Context, TAB, CE, OS);
392     S->getAssembler().setRelaxAll(RelaxAll);
393     return S;
394   }
395 }