LLVM 19.0.0git
MCAssembler.h
Go to the documentation of this file.
1//===- MCAssembler.h - Object File Generation -------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_MC_MCASSEMBLER_H
10#define LLVM_MC_MCASSEMBLER_H
11
12#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/iterator.h"
20#include "llvm/MC/MCDwarf.h"
22#include "llvm/MC/MCSymbol.h"
23#include "llvm/Support/SMLoc.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <memory>
30#include <string>
31#include <tuple>
32#include <utility>
33#include <vector>
34
35namespace llvm {
36
37class MCBoundaryAlignFragment;
38class MCCVDefRangeFragment;
39class MCCVInlineLineTableFragment;
40class MCDwarfCallFrameFragment;
41class MCDwarfLineAddrFragment;
42class MCEncodedFragment;
43class MCFixup;
44class MCLEBFragment;
45class MCPseudoProbeAddrFragment;
46class MCRelaxableFragment;
47class MCSymbolRefExpr;
48class raw_ostream;
49class MCAsmBackend;
50class MCContext;
51class MCCodeEmitter;
52class MCFragment;
53class MCObjectWriter;
54class MCSection;
55class MCValue;
56
58public:
61
62 /// MachO specific deployment target version info.
63 // A Major version of 0 indicates that no version information was supplied
64 // and so the corresponding load command should not be emitted.
65 using VersionInfoType = struct {
66 bool EmitBuildVersion;
67 union {
68 MCVersionMinType Type; ///< Used when EmitBuildVersion==false.
69 MachO::PlatformType Platform; ///< Used when EmitBuildVersion==true.
71 unsigned Major;
72 unsigned Minor;
73 unsigned Update;
74 /// An optional version of the SDK that was used to build the source.
76 };
77
78private:
79 MCContext &Context;
80
81 std::unique_ptr<MCAsmBackend> Backend;
82 std::unique_ptr<MCCodeEmitter> Emitter;
83 std::unique_ptr<MCObjectWriter> Writer;
84
85 bool HasLayout = false;
86 bool RelaxAll = false;
87 bool SubsectionsViaSymbols = false;
88 bool IncrementalLinkerCompatible = false;
89
90 SectionListType Sections;
91
93
94 /// The list of linker options to propagate into the object file.
95 std::vector<std::vector<std::string>> LinkerOptions;
96
97 /// List of declared file names
98 std::vector<std::pair<std::string, size_t>> FileNames;
99 // Optional compiler version.
100 std::string CompilerVersion;
101
102 MCDwarfLineTableParams LTParams;
103
104 /// The set of function symbols for which a .thumb_func directive has
105 /// been seen.
106 //
107 // FIXME: We really would like this in target specific code rather than
108 // here. Maybe when the relocation stuff moves to target specific,
109 // this can go with it? The streamer would need some target specific
110 // refactoring too.
111 mutable SmallPtrSet<const MCSymbol *, 32> ThumbFuncs;
112
113 /// The bundle alignment size currently set in the assembler.
114 ///
115 /// By default it's 0, which means bundling is disabled.
116 unsigned BundleAlignSize = 0;
117
118 /// ELF specific e_header flags
119 // It would be good if there were an MCELFAssembler class to hold this.
120 // ELF header flags are used both by the integrated and standalone assemblers.
121 // Access to the flags is necessary in cases where assembler directives affect
122 // which flags to be set.
123 unsigned ELFHeaderEFlags = 0;
124
125 /// Used to communicate Linker Optimization Hint information between
126 /// the Streamer and the .o writer
127 MCLOHContainer LOHContainer;
128
129 VersionInfoType VersionInfo;
130 VersionInfoType DarwinTargetVariantVersionInfo;
131
132 /// Evaluate a fixup to a relocatable expression and the value which should be
133 /// placed into the fixup.
134 ///
135 /// \param Fixup The fixup to evaluate.
136 /// \param DF The fragment the fixup is inside.
137 /// \param Target [out] On return, the relocatable expression the fixup
138 /// evaluates to.
139 /// \param Value [out] On return, the value of the fixup as currently laid
140 /// out.
141 /// \param WasForced [out] On return, the value in the fixup is set to the
142 /// correct value if WasForced is true, even if evaluateFixup returns false.
143 /// \return Whether the fixup value was fully resolved. This is true if the
144 /// \p Value result is fixed, otherwise the value may change due to
145 /// relocation.
146 bool evaluateFixup(const MCFixup &Fixup, const MCFragment *DF,
147 MCValue &Target, const MCSubtargetInfo *STI,
148 uint64_t &Value, bool &WasForced) const;
149
150 /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
151 /// (increased in size, in order to hold its value correctly).
152 bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF) const;
153
154 /// Check whether the given fragment needs relaxation.
155 bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF) const;
156
157 /// Perform one layout iteration and return true if any offsets
158 /// were adjusted.
159 bool layoutOnce();
160
161 /// Perform relaxation on a single fragment - returns true if the fragment
162 /// changes as a result of relaxation.
163 bool relaxFragment(MCFragment &F);
164 bool relaxInstruction(MCRelaxableFragment &IF);
165 bool relaxLEB(MCLEBFragment &IF);
166 bool relaxBoundaryAlign(MCBoundaryAlignFragment &BF);
167 bool relaxDwarfLineAddr(MCDwarfLineAddrFragment &DF);
168 bool relaxDwarfCallFrameFragment(MCDwarfCallFrameFragment &DF);
169 bool relaxCVInlineLineTable(MCCVInlineLineTableFragment &DF);
170 bool relaxCVDefRange(MCCVDefRangeFragment &DF);
171 bool relaxPseudoProbeAddr(MCPseudoProbeAddrFragment &DF);
172
173 std::tuple<MCValue, uint64_t, bool>
174 handleFixup(MCFragment &F, const MCFixup &Fixup, const MCSubtargetInfo *STI);
175
176public:
177 struct Symver {
179 const MCSymbol *Sym;
181 // True if .symver *, *@@@* or .symver *, *, remove.
183 };
184 std::vector<Symver> Symvers;
185
186 /// Construct a new assembler instance.
187 //
188 // FIXME: How are we going to parameterize this? Two obvious options are stay
189 // concrete and require clients to pass in a target like object. The other
190 // option is to make this abstract, and have targets provide concrete
191 // implementations as we do with AsmParser.
192 MCAssembler(MCContext &Context, std::unique_ptr<MCAsmBackend> Backend,
193 std::unique_ptr<MCCodeEmitter> Emitter,
194 std::unique_ptr<MCObjectWriter> Writer);
195 MCAssembler(const MCAssembler &) = delete;
198
199 /// Compute the effective fragment size.
201
202 void layoutBundle(MCFragment *Prev, MCFragment *F) const;
203 void ensureValid(MCSection &Sec) const;
204
205 // Get the offset of the given fragment inside its containing section.
207
208 uint64_t getSectionAddressSize(const MCSection &Sec) const;
209 uint64_t getSectionFileSize(const MCSection &Sec) const;
210
211 // Get the offset of the given symbol, as computed in the current
212 // layout.
213 // \return True on success.
214 bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const;
215
216 // Variant that reports a fatal error if the offset is not computable.
217 uint64_t getSymbolOffset(const MCSymbol &S) const;
218
219 // If this symbol is equivalent to A + Constant, return A.
220 const MCSymbol *getBaseSymbol(const MCSymbol &Symbol) const;
221
222 /// Emit the section contents to \p OS.
223 void writeSectionData(raw_ostream &OS, const MCSection *Section) const;
224
225 /// Check whether a given symbol has been flagged with .thumb_func.
226 bool isThumbFunc(const MCSymbol *Func) const;
227
228 /// Flag a function symbol as the target of a .thumb_func directive.
229 void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
230
231 /// ELF e_header flags
232 unsigned getELFHeaderEFlags() const { return ELFHeaderEFlags; }
233 void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags; }
234
235 /// MachO deployment target version information.
236 const VersionInfoType &getVersionInfo() const { return VersionInfo; }
238 unsigned Update,
240 VersionInfo.EmitBuildVersion = false;
241 VersionInfo.TypeOrPlatform.Type = Type;
242 VersionInfo.Major = Major;
243 VersionInfo.Minor = Minor;
244 VersionInfo.Update = Update;
245 VersionInfo.SDKVersion = SDKVersion;
246 }
248 unsigned Minor, unsigned Update,
250 VersionInfo.EmitBuildVersion = true;
251 VersionInfo.TypeOrPlatform.Platform = Platform;
252 VersionInfo.Major = Major;
253 VersionInfo.Minor = Minor;
254 VersionInfo.Update = Update;
255 VersionInfo.SDKVersion = SDKVersion;
256 }
257
259 return DarwinTargetVariantVersionInfo;
260 }
262 unsigned Major, unsigned Minor,
263 unsigned Update,
265 DarwinTargetVariantVersionInfo.EmitBuildVersion = true;
266 DarwinTargetVariantVersionInfo.TypeOrPlatform.Platform = Platform;
267 DarwinTargetVariantVersionInfo.Major = Major;
268 DarwinTargetVariantVersionInfo.Minor = Minor;
269 DarwinTargetVariantVersionInfo.Update = Update;
270 DarwinTargetVariantVersionInfo.SDKVersion = SDKVersion;
271 }
272
273 /// Reuse an assembler instance
274 ///
275 void reset();
276
277 MCContext &getContext() const { return Context; }
278
279 MCAsmBackend *getBackendPtr() const { return Backend.get(); }
280
281 MCCodeEmitter *getEmitterPtr() const { return Emitter.get(); }
282
283 MCObjectWriter *getWriterPtr() const { return Writer.get(); }
284
285 MCAsmBackend &getBackend() const { return *Backend; }
286
287 MCCodeEmitter &getEmitter() const { return *Emitter; }
288
289 MCObjectWriter &getWriter() const { return *Writer; }
290
293
294 /// Finish - Do final processing and write the object to the output stream.
295 /// \p Writer is used for custom object writer (as the MCJIT does),
296 /// if not specified it is automatically created from backend.
297 void Finish();
298
299 // Layout all section and prepare them for emission.
300 void layout();
301
302 // FIXME: This does not belong here.
303 bool getSubsectionsViaSymbols() const { return SubsectionsViaSymbols; }
304 void setSubsectionsViaSymbols(bool Value) { SubsectionsViaSymbols = Value; }
305
307 return IncrementalLinkerCompatible;
308 }
310 IncrementalLinkerCompatible = Value;
311 }
312
313 bool hasLayout() const { return HasLayout; }
314 bool getRelaxAll() const { return RelaxAll; }
315 void setRelaxAll(bool Value) { RelaxAll = Value; }
316
317 bool isBundlingEnabled() const { return BundleAlignSize != 0; }
318
319 unsigned getBundleAlignSize() const { return BundleAlignSize; }
320
321 void setBundleAlignSize(unsigned Size) {
322 assert((Size == 0 || !(Size & (Size - 1))) &&
323 "Expect a power-of-two bundle align size");
324 BundleAlignSize = Size;
325 }
326
327 const_iterator begin() const { return Sections.begin(); }
328 const_iterator end() const { return Sections.end(); }
329
332 symbols() const {
333 return make_pointee_range(Symbols);
334 }
335
336 /// @}
337 /// \name Linker Option List Access
338 /// @{
339
340 std::vector<std::vector<std::string>> &getLinkerOptions() {
341 return LinkerOptions;
342 }
343
344 // FIXME: This is a total hack, this should not be here. Once things are
345 // factored so that the streamer has direct access to the .o writer, it can
346 // disappear.
347 MCLOHContainer &getLOHContainer() { return LOHContainer; }
349 return const_cast<MCAssembler *>(this)->getLOHContainer();
350 }
351
356 };
357 std::vector<CGProfileEntry> CGProfile;
358 /// @}
359 /// \name Backend Data Access
360 /// @{
361
362 bool registerSection(MCSection &Section);
363 bool registerSymbol(const MCSymbol &Symbol);
364
366 return FileNames;
367 }
368
369 void addFileName(StringRef FileName) {
370 FileNames.emplace_back(std::string(FileName), Symbols.size());
371 }
372
373 void setCompilerVersion(std::string CompilerVers) {
374 if (CompilerVersion.empty())
375 CompilerVersion = std::move(CompilerVers);
376 }
377 StringRef getCompilerVersion() { return CompilerVersion; }
378
379 /// Write the necessary bundle padding to \p OS.
380 /// Expects a fragment \p F containing instructions and its size \p FSize.
382 uint64_t FSize) const;
383
384 /// @}
385
386 void dump() const;
387};
388
389} // end namespace llvm
390
391#endif // LLVM_MC_MCASSEMBLER_H
dxil DXContainer Global Emitter
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
uint64_t Size
#define F(x, y, z)
Definition: MD5.cpp:55
#define P(N)
PowerPC TLS Dynamic Call Fixup
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Defines the llvm::VersionTuple class, which represents a version in the form major[....
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:42
void setBuildVersion(MachO::PlatformType Platform, unsigned Major, unsigned Minor, unsigned Update, VersionTuple SDKVersion=VersionTuple())
Definition: MCAssembler.h:247
MachO::PlatformType Platform
Used when EmitBuildVersion==true.
Definition: MCAssembler.h:69
const_iterator begin() const
Definition: MCAssembler.h:327
MCContext & getContext() const
Definition: MCAssembler.h:277
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
void ensureValid(MCSection &Sec) const
uint64_t getSectionAddressSize(const MCSection &Sec) const
unsigned getELFHeaderEFlags() const
ELF e_header flags.
Definition: MCAssembler.h:232
MCAssembler & operator=(const MCAssembler &)=delete
void Finish()
Finish - Do final processing and write the object to the output stream.
SmallVector< MCSection *, 0 > SectionListType
Definition: MCAssembler.h:59
unsigned getBundleAlignSize() const
Definition: MCAssembler.h:319
bool isBundlingEnabled() const
Definition: MCAssembler.h:317
bool getSubsectionsViaSymbols() const
Definition: MCAssembler.h:303
void setBundleAlignSize(unsigned Size)
Definition: MCAssembler.h:321
void setIsThumbFunc(const MCSymbol *Func)
Flag a function symbol as the target of a .thumb_func directive.
Definition: MCAssembler.h:229
bool isIncrementalLinkerCompatible() const
Definition: MCAssembler.h:306
void setSubsectionsViaSymbols(bool Value)
Definition: MCAssembler.h:304
void writeSectionData(raw_ostream &OS, const MCSection *Section) const
Emit the section contents to OS.
void dump() const
const VersionInfoType & getVersionInfo() const
MachO deployment target version information.
Definition: MCAssembler.h:236
const MCLOHContainer & getLOHContainer() const
Definition: MCAssembler.h:348
MCObjectWriter * getWriterPtr() const
Definition: MCAssembler.h:283
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:289
union llvm::MCAssembler::@328 TypeOrPlatform
MCVersionMinType Type
Used when EmitBuildVersion==false.
Definition: MCAssembler.h:68
VersionTuple SDKVersion
An optional version of the SDK that was used to build the source.
Definition: MCAssembler.h:75
MutableArrayRef< std::pair< std::string, size_t > > getFileNames()
Definition: MCAssembler.h:365
MCCodeEmitter * getEmitterPtr() const
Definition: MCAssembler.h:281
uint64_t getFragmentOffset(const MCFragment &F) const
void layoutBundle(MCFragment *Prev, MCFragment *F) const
bool getRelaxAll() const
Definition: MCAssembler.h:314
std::vector< std::vector< std::string > > & getLinkerOptions()
Definition: MCAssembler.h:340
MCAssembler(const MCAssembler &)=delete
const VersionInfoType & getDarwinTargetVariantVersionInfo() const
Definition: MCAssembler.h:258
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:287
void setDarwinTargetVariantBuildVersion(MachO::PlatformType Platform, unsigned Major, unsigned Minor, unsigned Update, VersionTuple SDKVersion)
Definition: MCAssembler.h:261
void addFileName(StringRef FileName)
Definition: MCAssembler.h:369
void setIncrementalLinkerCompatible(bool Value)
Definition: MCAssembler.h:309
bool isThumbFunc(const MCSymbol *Func) const
Check whether a given symbol has been flagged with .thumb_func.
const_iterator end() const
Definition: MCAssembler.h:328
{ bool EmitBuildVersion VersionInfoType
MachO specific deployment target version info.
Definition: MCAssembler.h:66
MCAsmBackend & getBackend() const
Definition: MCAssembler.h:285
std::vector< Symver > Symvers
Definition: MCAssembler.h:184
std::vector< CGProfileEntry > CGProfile
Definition: MCAssembler.h:357
bool registerSection(MCSection &Section)
uint64_t computeFragmentSize(const MCFragment &F) const
Compute the effective fragment size.
const MCSymbol * getBaseSymbol(const MCSymbol &Symbol) const
MCAsmBackend * getBackendPtr() const
Definition: MCAssembler.h:279
void setELFHeaderEFlags(unsigned Flags)
Definition: MCAssembler.h:233
void setVersionMin(MCVersionMinType Type, unsigned Major, unsigned Minor, unsigned Update, VersionTuple SDKVersion=VersionTuple())
Definition: MCAssembler.h:237
iterator_range< pointee_iterator< typename SmallVector< const MCSymbol *, 0 >::const_iterator > > symbols() const
Definition: MCAssembler.h:332
MCLOHContainer & getLOHContainer()
Definition: MCAssembler.h:347
uint64_t getSectionFileSize(const MCSection &Sec) const
void setDWARFLinetableParams(MCDwarfLineTableParams P)
Definition: MCAssembler.h:292
void reset()
Reuse an assembler instance.
Definition: MCAssembler.cpp:94
bool registerSymbol(const MCSymbol &Symbol)
bool hasLayout() const
Definition: MCAssembler.h:313
MCDwarfLineTableParams getDWARFLinetableParams() const
Definition: MCAssembler.h:291
void writeFragmentPadding(raw_ostream &OS, const MCEncodedFragment &F, uint64_t FSize) const
Write the necessary bundle padding to OS.
void setRelaxAll(bool Value)
Definition: MCAssembler.h:315
void setCompilerVersion(std::string CompilerVers)
Definition: MCAssembler.h:373
StringRef getCompilerVersion()
Definition: MCAssembler.h:377
Represents required padding such that a particular other set of fragments does not cross a particular...
Definition: MCFragment.h:563
Fragment representing the .cv_def_range directive.
Definition: MCFragment.h:533
Fragment representing the binary annotations produced by the .cv_inline_linetable directive.
Definition: MCFragment.h:501
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:21
Context object for machine code objects.
Definition: MCContext.h:83
Interface implemented by fragments that contain encoded instructions and/or data.
Definition: MCFragment.h:118
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
Defines the object file and target independent interfaces used by the assembler backend to write nati...
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:261
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
Generic base class for all target subtargets.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:188
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
This represents an "assembler immediate".
Definition: MCValue.h:36
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
Represents a location in source code.
Definition: SMLoc.h:23
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
PlatformType
Definition: MachO.h:500
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition: iterator.h:336
MCVersionMinType
Definition: MCDirectives.h:69
const MCSymbolRefExpr * From
Definition: MCAssembler.h:353
const MCSymbolRefExpr * To
Definition: MCAssembler.h:354
const MCSymbol * Sym
Definition: MCAssembler.h:179
An iterator type that allows iterating over the pointees via some other iterator.
Definition: iterator.h:324