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