LLVM  4.0.0
WinCOFFStreamer.cpp
Go to the documentation of this file.
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 Windows COFF object file streamer.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCSectionCOFF.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSymbolCOFF.h"
26 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/COFF.h"
29 #include "llvm/Support/Debug.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "WinCOFFStreamer"
38 
39 namespace llvm {
42  : MCObjectStreamer(Context, MAB, OS, &CE), CurSymbol(nullptr) {}
43 
45  const MCSubtargetInfo &STI) {
47 
49  SmallString<256> Code;
50  raw_svector_ostream VecOS(Code);
51  getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
52 
53  // Add the fixups and data.
54  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
55  Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
56  DF->getFixups().push_back(Fixups[i]);
57  }
58 
59  DF->getContents().append(Code.begin(), Code.end());
60 }
61 
62 void MCWinCOFFStreamer::InitSections(bool NoExecStack) {
63  // FIXME: this is identical to the ELF one.
64  // This emulates the same behavior of GNU as. This makes it easier
65  // to compare the output as the major sections are in the same order.
66  SwitchSection(getContext().getObjectFileInfo()->getTextSection());
68 
69  SwitchSection(getContext().getObjectFileInfo()->getDataSection());
71 
72  SwitchSection(getContext().getObjectFileInfo()->getBSSSection());
74 
75  SwitchSection(getContext().getObjectFileInfo()->getTextSection());
76 }
77 
79  auto *Symbol = cast<MCSymbolCOFF>(S);
80  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
82 }
83 
85  llvm_unreachable("not implemented");
86 }
87 
89  llvm_unreachable("not implemented");
90 }
91 
94  auto *Symbol = cast<MCSymbolCOFF>(S);
96 
97  switch (Attribute) {
98  default: return false;
99  case MCSA_WeakReference:
100  case MCSA_Weak:
101  Symbol->setIsWeakExternal();
102  Symbol->setExternal(true);
103  break;
104  case MCSA_Global:
105  Symbol->setExternal(true);
106  break;
107  case MCSA_AltEntry:
108  llvm_unreachable("COFF doesn't support the .alt_entry attribute");
109  }
110 
111  return true;
112 }
113 
115  llvm_unreachable("not implemented");
116 }
117 
119  auto *Symbol = cast<MCSymbolCOFF>(S);
120  if (CurSymbol)
121  Error("starting a new symbol definition without completing the "
122  "previous one");
123  CurSymbol = Symbol;
124 }
125 
127  if (!CurSymbol) {
128  Error("storage class specified outside of symbol definition");
129  return;
130  }
131 
132  if (StorageClass & ~COFF::SSC_Invalid) {
133  Error("storage class value '" + Twine(StorageClass) +
134  "' out of range");
135  return;
136  }
137 
139  cast<MCSymbolCOFF>(CurSymbol)->setClass((uint16_t)StorageClass);
140 }
141 
143  if (!CurSymbol) {
144  Error("symbol type specified outside of a symbol definition");
145  return;
146  }
147 
148  if (Type & ~0xffff) {
149  Error("type value '" + Twine(Type) + "' out of range");
150  return;
151  }
152 
154  cast<MCSymbolCOFF>(CurSymbol)->setType((uint16_t)Type);
155 }
156 
158  if (!CurSymbol)
159  Error("ending symbol definition without starting one");
160  CurSymbol = nullptr;
161 }
162 
164  // SafeSEH is a feature specific to 32-bit x86. It does not exist (and is
165  // unnecessary) on all platforms which use table-based exception dispatch.
166  if (getContext().getObjectFileInfo()->getTargetTriple().getArch() !=
167  Triple::x86)
168  return;
169 
170  const MCSymbolCOFF *CSymbol = cast<MCSymbolCOFF>(Symbol);
171  if (CSymbol->isSafeSEH())
172  return;
173 
175  getAssembler().registerSection(*SXData);
176  if (SXData->getAlignment() < 4)
177  SXData->setAlignment(4);
178 
179  new MCSafeSEHFragment(Symbol, SXData);
180 
181  getAssembler().registerSymbol(*Symbol);
182  CSymbol->setIsSafeSEH();
183 
184  // The Microsoft linker requires that the symbol type of a handler be
185  // function. Go ahead and oblige it here.
188 }
189 
192  const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol, getContext());
194  DF->getFixups().push_back(Fixup);
195  DF->getContents().resize(DF->getContents().size() + 2, 0);
196 }
197 
199  uint64_t Offset) {
201  // Create Symbol A for the relocation relative reference.
202  const MCExpr *MCE = MCSymbolRefExpr::create(Symbol, getContext());
203  // Add the constant offset, if given.
204  if (Offset)
206  MCE, MCConstantExpr::create(Offset, getContext()), getContext());
207  // Build the secrel32 relocation.
209  // Record the relocation.
210  DF->getFixups().push_back(Fixup);
211  // Emit 4 bytes (zeros) to the object file.
212  DF->getContents().resize(DF->getContents().size() + 4, 0);
213 }
214 
216  unsigned ByteAlignment) {
217  auto *Symbol = cast<MCSymbolCOFF>(S);
218 
220  if (T.isKnownWindowsMSVCEnvironment()) {
221  if (ByteAlignment > 32)
222  report_fatal_error("alignment is limited to 32-bytes");
223 
224  // Round size up to alignment so that we will honor the alignment request.
225  Size = std::max(Size, static_cast<uint64_t>(ByteAlignment));
226  }
227 
229  Symbol->setExternal(true);
230  Symbol->setCommon(Size, ByteAlignment);
231 
232  if (!T.isKnownWindowsMSVCEnvironment() && ByteAlignment > 1) {
233  SmallString<128> Directive;
234  raw_svector_ostream OS(Directive);
236 
237  OS << " -aligncomm:\"" << Symbol->getName() << "\","
238  << Log2_32_Ceil(ByteAlignment);
239 
240  PushSection();
242  EmitBytes(Directive);
243  PopSection();
244  }
245 }
246 
248  unsigned ByteAlignment) {
249  auto *Symbol = cast<MCSymbolCOFF>(S);
250 
252  getAssembler().registerSection(*Section);
253  if (Section->getAlignment() < ByteAlignment)
254  Section->setAlignment(ByteAlignment);
255 
257  Symbol->setExternal(false);
258 
259  if (ByteAlignment != 1)
260  new MCAlignFragment(ByteAlignment, /*Value=*/0, /*ValueSize=*/0,
261  ByteAlignment, Section);
262 
263  MCFillFragment *Fragment = new MCFillFragment(
264  /*Value=*/0, Size, Section);
265  Symbol->setFragment(Fragment);
266 }
267 
269  uint64_t Size, unsigned ByteAlignment) {
270  llvm_unreachable("not implemented");
271 }
272 
274  uint64_t Size, unsigned ByteAlignment) {
275  llvm_unreachable("not implemented");
276 }
277 
279  getAssembler().addFileName(Filename);
280 }
281 
282 // TODO: Implement this if you want to emit .comment section in COFF obj files.
284  llvm_unreachable("not implemented");
285 }
286 
288  llvm_unreachable("not implemented");
289 }
290 
293 }
294 
295 void MCWinCOFFStreamer::Error(const Twine &Msg) const {
296  getContext().reportError(SMLoc(), Msg);
297 }
298 }
299 
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:40
unsigned Log2_32_Ceil(uint32_t Value)
Log2_32_Ceil - This function returns the ceil log base 2 of the specified value, 32 if the value is z...
Definition: MathExtras.h:526
void InitSections(bool NoExecStack) override
Create the default sections and set the initial one.
void EmitThumbFunc(MCSymbol *Func) override
Note in the output that the specified Func is a Thumb mode function (ARM target only).
void EmitBytes(StringRef Data) override
Emit the bytes in Data into the output.
LLVMContext & Context
void setType(uint16_t Ty) const
Definition: MCSymbolCOFF.h:35
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:298
void EmitCOFFSectionIndex(MCSymbol const *Symbol) override
Emits a COFF section index.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
size_t i
void EmitLabel(MCSymbol *Symbol) override
Emit a label for Symbol into the current section.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
void EmitWinEHHandlerData() override
void setAlignment(unsigned Value)
Definition: MCSection.h:118
const MCSymbol * CurSymbol
void EmitAssemblerFlag(MCAssemblerFlag Flag) override
Note in the output the specified Flag.
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:262
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
void registerSymbol(const MCSymbol &Symbol, bool *Created=nullptr)
void PushSection()
Save the current and previous section on the section stack.
Definition: MCStreamer.h:324
void EmitCOFFSymbolStorageClass(int StorageClass) override
Emit the storage class of the symbol.
unsigned getAlignment() const
Definition: MCSection.h:117
COFF::SymbolStorageClass StorageClass
Definition: COFFYAML.cpp:296
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:66
bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override
Add the given Attribute to Symbol.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
void EmitFileDirective(StringRef Filename) override
Switch to a new logical file.
virtual void encodeInstruction(const MCInst &Inst, raw_ostream &OS, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
EncodeInstruction - Encode the given Inst to bytes on the output stream OS.
bool isSafeSEH() const
Definition: MCSymbolCOFF.h:53
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
bool registerSection(MCSection &Section)
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:161
A four-byte section relative fixup.
Definition: MCFixup.h:42
MCContext & getContext() const
Definition: MCStreamer.h:221
Context object for machine code objects.
Definition: MCContext.h:51
MCSection * getBSSSection() const
A two-byte section relative fixup.
Definition: MCFixup.h:41
Streaming object file generation interface.
.alt_entry (MachO)
Definition: MCDirectives.h:38
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:429
void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override
Emits a COFF section relative relocation.
void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override
Set the DescValue for the Symbol.
const Triple & getTargetTriple() const
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:175
void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override
Emit a local common (.lcomm) symbol.
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:150
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:121
void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override
Emit a common symbol.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit=0) override
Emit nops until the byte alignment ByteAlignment is reached.
virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
Definition: MCStreamer.cpp:829
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
MCAssembler & getAssembler()
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition: Support/COFF.h:233
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:23
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:200
uint32_t Offset
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:510
A function that returns a base type.
Definition: Support/COFF.h:229
MCSection * getDrectveSection() const
.weak_reference (MachO)
Definition: MCDirectives.h:44
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:392
void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override
Emit a thread local bss (.tbss) symbol.
void EmitCOFFSymbolType(int Type) override
Emit the type of the symbol.
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:82
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
MCSection * getSXDataSection() const
PowerPC TLS Dynamic Call Fixup
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
MCSymbolAttr
Definition: MCDirectives.h:19
void addFileName(StringRef FileName)
Definition: MCAssembler.h:405
void EndCOFFSymbolDef() override
Marks the end of the symbol definition.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
.type _foo,
Definition: MCDirectives.h:30
void FinishImpl() override
Streamer specific finalization.
MCAssemblerFlag
Definition: MCDirectives.h:48
void setIsSafeSEH() const
Definition: MCSymbolCOFF.h:56
MCWinCOFFStreamer(MCContext &Context, MCAsmBackend &MAB, MCCodeEmitter &CE, raw_pwrite_stream &OS)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
void EmitLabel(MCSymbol *Symbol) override
Emit a label for Symbol into the current section.
MCSubtargetInfo - Generic base class for all target subtargets.
void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override
void BeginCOFFSymbolDef(MCSymbol const *Symbol) override
Start emitting COFF symbol definition.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:333
void EmitIdent(StringRef IdentString) override
Emit the "identifiers" directive.
Fragment for data and encoded instructions.
Definition: MCFragment.h:218
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void EmitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override
Emit the zerofill section and an optional symbol.
bool PopSection()
Restore the current and previous section from the section stack.
Definition: MCStreamer.h:333
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:36
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:247
Lightweight error class with error context and mandatory checking.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
void EmitCOFFSafeSEH(MCSymbol const *Symbol) override
Represents a location in source code.
Definition: SMLoc.h:24
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:149
MCDataFragment * getOrCreateDataFragment()
Get a data fragment to write into, creating a new one if the current fragment is not a data fragment...
void FinishImpl() override
Streamer specific finalization.
void resize(size_type N)
Definition: SmallVector.h:352