LLVM  8.0.0svn
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/MCObjectWriter.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSymbolCOFF.h"
32 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/SMLoc.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstdint>
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "WinCOFFStreamer"
44 
46  std::unique_ptr<MCAsmBackend> MAB,
47  std::unique_ptr<MCCodeEmitter> CE,
48  std::unique_ptr<MCObjectWriter> OW)
49  : MCObjectStreamer(Context, std::move(MAB), std::move(OW), std::move(CE)),
50  CurSymbol(nullptr) {}
51 
53  const MCSubtargetInfo &STI) {
55 
57  SmallString<256> Code;
58  raw_svector_ostream VecOS(Code);
59  getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
60 
61  // Add the fixups and data.
62  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
63  Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
64  DF->getFixups().push_back(Fixups[i]);
65  }
66  DF->setHasInstructions(STI);
67  DF->getContents().append(Code.begin(), Code.end());
68 }
69 
70 void MCWinCOFFStreamer::InitSections(bool NoExecStack) {
71  // FIXME: this is identical to the ELF one.
72  // This emulates the same behavior of GNU as. This makes it easier
73  // to compare the output as the major sections are in the same order.
74  SwitchSection(getContext().getObjectFileInfo()->getTextSection());
76 
77  SwitchSection(getContext().getObjectFileInfo()->getDataSection());
79 
80  SwitchSection(getContext().getObjectFileInfo()->getBSSSection());
82 
83  SwitchSection(getContext().getObjectFileInfo()->getTextSection());
84 }
85 
87  auto *Symbol = cast<MCSymbolCOFF>(S);
89 }
90 
92  llvm_unreachable("not implemented");
93 }
94 
96  llvm_unreachable("not implemented");
97 }
98 
101  auto *Symbol = cast<MCSymbolCOFF>(S);
103 
104  switch (Attribute) {
105  default: return false;
106  case MCSA_WeakReference:
107  case MCSA_Weak:
108  Symbol->setIsWeakExternal();
109  Symbol->setExternal(true);
110  break;
111  case MCSA_Global:
112  Symbol->setExternal(true);
113  break;
114  case MCSA_AltEntry:
115  llvm_unreachable("COFF doesn't support the .alt_entry attribute");
116  }
117 
118  return true;
119 }
120 
122  llvm_unreachable("not implemented");
123 }
124 
126  auto *Symbol = cast<MCSymbolCOFF>(S);
127  if (CurSymbol)
128  Error("starting a new symbol definition without completing the "
129  "previous one");
130  CurSymbol = Symbol;
131 }
132 
134  if (!CurSymbol) {
135  Error("storage class specified outside of symbol definition");
136  return;
137  }
138 
139  if (StorageClass & ~COFF::SSC_Invalid) {
140  Error("storage class value '" + Twine(StorageClass) +
141  "' out of range");
142  return;
143  }
144 
146  cast<MCSymbolCOFF>(CurSymbol)->setClass((uint16_t)StorageClass);
147 }
148 
150  if (!CurSymbol) {
151  Error("symbol type specified outside of a symbol definition");
152  return;
153  }
154 
155  if (Type & ~0xffff) {
156  Error("type value '" + Twine(Type) + "' out of range");
157  return;
158  }
159 
161  cast<MCSymbolCOFF>(CurSymbol)->setType((uint16_t)Type);
162 }
163 
165  if (!CurSymbol)
166  Error("ending symbol definition without starting one");
167  CurSymbol = nullptr;
168 }
169 
171  // SafeSEH is a feature specific to 32-bit x86. It does not exist (and is
172  // unnecessary) on all platforms which use table-based exception dispatch.
173  if (getContext().getObjectFileInfo()->getTargetTriple().getArch() !=
174  Triple::x86)
175  return;
176 
177  const MCSymbolCOFF *CSymbol = cast<MCSymbolCOFF>(Symbol);
178  if (CSymbol->isSafeSEH())
179  return;
180 
182  getAssembler().registerSection(*SXData);
183  if (SXData->getAlignment() < 4)
184  SXData->setAlignment(4);
185 
186  new MCSymbolIdFragment(Symbol, SXData);
187 
188  getAssembler().registerSymbol(*Symbol);
189  CSymbol->setIsSafeSEH();
190 
191  // The Microsoft linker requires that the symbol type of a handler be
192  // function. Go ahead and oblige it here.
195 }
196 
200  if (Sec->getAlignment() < 4)
201  Sec->setAlignment(4);
202 
204 
205  getAssembler().registerSymbol(*Symbol);
206 }
207 
209  visitUsedSymbol(*Symbol);
211  const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol, getContext());
213  DF->getFixups().push_back(Fixup);
214  DF->getContents().resize(DF->getContents().size() + 2, 0);
215 }
216 
218  uint64_t Offset) {
219  visitUsedSymbol(*Symbol);
221  // Create Symbol A for the relocation relative reference.
222  const MCExpr *MCE = MCSymbolRefExpr::create(Symbol, getContext());
223  // Add the constant offset, if given.
224  if (Offset)
226  MCE, MCConstantExpr::create(Offset, getContext()), getContext());
227  // Build the secrel32 relocation.
229  // Record the relocation.
230  DF->getFixups().push_back(Fixup);
231  // Emit 4 bytes (zeros) to the object file.
232  DF->getContents().resize(DF->getContents().size() + 4, 0);
233 }
234 
236  int64_t Offset) {
237  visitUsedSymbol(*Symbol);
239  // Create Symbol A for the relocation relative reference.
240  const MCExpr *MCE = MCSymbolRefExpr::create(
242  // Add the constant offset, if given.
243  if (Offset)
245  MCE, MCConstantExpr::create(Offset, getContext()), getContext());
246  // Build the imgrel relocation.
248  // Record the relocation.
249  DF->getFixups().push_back(Fixup);
250  // Emit 4 bytes (zeros) to the object file.
251  DF->getContents().resize(DF->getContents().size() + 4, 0);
252 }
253 
255  unsigned ByteAlignment) {
256  auto *Symbol = cast<MCSymbolCOFF>(S);
257 
259  if (T.isKnownWindowsMSVCEnvironment()) {
260  if (ByteAlignment > 32)
261  report_fatal_error("alignment is limited to 32-bytes");
262 
263  // Round size up to alignment so that we will honor the alignment request.
264  Size = std::max(Size, static_cast<uint64_t>(ByteAlignment));
265  }
266 
268  Symbol->setExternal(true);
269  Symbol->setCommon(Size, ByteAlignment);
270 
271  if (!T.isKnownWindowsMSVCEnvironment() && ByteAlignment > 1) {
272  SmallString<128> Directive;
273  raw_svector_ostream OS(Directive);
275 
276  OS << " -aligncomm:\"" << Symbol->getName() << "\","
277  << Log2_32_Ceil(ByteAlignment);
278 
279  PushSection();
281  EmitBytes(Directive);
282  PopSection();
283  }
284 }
285 
287  unsigned ByteAlignment) {
288  auto *Symbol = cast<MCSymbolCOFF>(S);
289 
291  PushSection();
292  SwitchSection(Section);
293  EmitValueToAlignment(ByteAlignment, 0, 1, 0);
294  EmitLabel(Symbol);
295  Symbol->setExternal(false);
296  EmitZeros(Size);
297  PopSection();
298 }
299 
301  uint64_t Size, unsigned ByteAlignment,
302  SMLoc Loc) {
303  llvm_unreachable("not implemented");
304 }
305 
307  uint64_t Size, unsigned ByteAlignment) {
308  llvm_unreachable("not implemented");
309 }
310 
311 // TODO: Implement this if you want to emit .comment section in COFF obj files.
313  llvm_unreachable("not implemented");
314 }
315 
317  llvm_unreachable("not implemented");
318 }
319 
322 }
323 
324 void MCWinCOFFStreamer::Error(const Twine &Msg) const {
325  getContext().reportError(SMLoc(), Msg);
326 }
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:552
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
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:323
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:139
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
MCWinCOFFStreamer(MCContext &Context, std::unique_ptr< MCAsmBackend > MAB, std::unique_ptr< MCCodeEmitter > CE, std::unique_ptr< MCObjectWriter > OW)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
void setAlignment(unsigned Value)
Definition: MCSection.h:122
const MCSymbol * CurSymbol
void InitSections(bool NoExecStack) override
Create the default sections and set the initial one.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:510
void registerSymbol(const MCSymbol &Symbol, bool *Created=nullptr)
void PushSection()
Save the current and previous section on the section stack.
Definition: MCStreamer.h:367
void EmitAssemblerFlag(MCAssemblerFlag Flag) override
Note in the output the specified Flag.
COFF::SymbolStorageClass StorageClass
Definition: COFFYAML.cpp:354
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:74
unsigned getAlignment() const
Definition: MCSection.h:121
MCContext & getContext() const
Definition: MCStreamer.h:250
Definition: BitVector.h:938
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
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:288
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.
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:166
MCSection * getBSSSection() const
A four-byte section relative fixup.
Definition: MCFixup.h:42
void EmitWinEHHandlerData(SMLoc Loc) override
void BeginCOFFSymbolDef(MCSymbol const *Symbol) override
Start emitting COFF symbol definition.
A four-byte fixup.
Definition: MCFixup.h:26
Context object for machine code objects.
Definition: MCContext.h:63
MCSection * getSXDataSection() 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)
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition: COFF.h:266
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:461
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:198
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:161
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:118
void EndCOFFSymbolDef() override
Marks the end of the symbol definition.
void EmitZeros(uint64_t NumBytes)
Emit NumBytes worth of zeros.
Definition: MCStreamer.cpp:201
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
MCAssembler & getAssembler()
void setHasInstructions(const MCSubtargetInfo &STI)
Record that the fragment contains instructions with the MCSubtargetInfo in effect when the instructio...
Definition: MCFragment.h:178
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:224
void EmitCOFFSymbolStorageClass(int StorageClass) override
Emit the storage class of the symbol.
void EmitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment, SMLoc Loc=SMLoc()) override
Emit the zerofill section and an optional symbol.
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:297
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:612
.weak_reference (MachO)
Definition: MCDirectives.h:44
void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override
Emits a COFF image relative relocation.
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:90
size_t size() const
Definition: SmallVector.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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 * getDrectveSection() const
void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0) override
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
PowerPC TLS Dynamic Call Fixup
void EmitCOFFSafeSEH(MCSymbol const *Symbol) override
void setIsSafeSEH() const
Definition: MCSymbolCOFF.h:58
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
void setType(uint16_t Ty) const
Definition: MCSymbolCOFF.h:37
Represents a symbol table index fragment.
Definition: MCFragment.h:576
const Triple & getTargetTriple() const
MCSymbolAttr
Definition: MCDirectives.h:19
MCSection * getCurrentSectionOnly() const
Definition: MCStreamer.h:345
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:394
bool isSafeSEH() const
Definition: MCSymbolCOFF.h:55
MCDataFragment * getOrCreateDataFragment(const MCSubtargetInfo *STI=nullptr)
Get a data fragment to write into, creating a new one if the current fragment is not a data fragment...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
void EmitCOFFSymbolIndex(MCSymbol const *Symbol) override
Emits the symbol table index of a Symbol into the current section.
.type _foo,
Definition: MCDirectives.h:30
void FinishImpl() override
Streamer specific finalization.
MCAssemblerFlag
Definition: MCDirectives.h:48
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.
uint32_t Size
Definition: Profile.cpp:47
Fragment for data and encoded instructions.
Definition: MCFragment.h:242
bool PopSection()
Restore the current and previous section from the section stack.
Definition: MCStreamer.h:376
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
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:164
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:351
A function that returns a base type.
Definition: COFF.h:262