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