blob: 582a836023b570e6d4bf275332c4f2de37e2d4b1 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- MCStreamer.h - High-level Streaming Machine Code Output --*- 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 declares the MCStreamer class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_MC_MCSTREAMER_H
15#define LLVM_MC_MCSTREAMER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/MC/MCDirectives.h"
23#include "llvm/MC/MCDwarf.h"
24#include "llvm/MC/MCLinkerOptimizationHint.h"
25#include "llvm/MC/MCSymbol.h"
26#include "llvm/MC/MCWinEH.h"
27#include "llvm/Support/Error.h"
28#include "llvm/Support/MD5.h"
29#include "llvm/Support/SMLoc.h"
30#include "llvm/Support/TargetParser.h"
31#include <cassert>
32#include <cstdint>
33#include <memory>
34#include <string>
35#include <utility>
36#include <vector>
37
38namespace llvm {
39
40class AssemblerConstantPools;
41class formatted_raw_ostream;
42class MCAsmBackend;
43class MCCodeEmitter;
44struct MCCodePaddingContext;
45class MCContext;
46class MCExpr;
47class MCInst;
48class MCInstPrinter;
49class MCSection;
50class MCStreamer;
51class MCSymbolRefExpr;
52class MCSubtargetInfo;
53class raw_ostream;
54class Twine;
55
56using MCSectionSubPair = std::pair<MCSection *, const MCExpr *>;
57
58/// Target specific streamer interface. This is used so that targets can
59/// implement support for target specific assembly directives.
60///
61/// If target foo wants to use this, it should implement 3 classes:
62/// * FooTargetStreamer : public MCTargetStreamer
63/// * FooTargetAsmStreamer : public FooTargetStreamer
64/// * FooTargetELFStreamer : public FooTargetStreamer
65///
66/// FooTargetStreamer should have a pure virtual method for each directive. For
67/// example, for a ".bar symbol_name" directive, it should have
68/// virtual emitBar(const MCSymbol &Symbol) = 0;
69///
70/// The FooTargetAsmStreamer and FooTargetELFStreamer classes implement the
71/// method. The assembly streamer just prints ".bar symbol_name". The object
72/// streamer does whatever is needed to implement .bar in the object file.
73///
74/// In the assembly printer and parser the target streamer can be used by
75/// calling getTargetStreamer and casting it to FooTargetStreamer:
76///
77/// MCTargetStreamer &TS = OutStreamer.getTargetStreamer();
78/// FooTargetStreamer &ATS = static_cast<FooTargetStreamer &>(TS);
79///
80/// The base classes FooTargetAsmStreamer and FooTargetELFStreamer should
81/// *never* be treated differently. Callers should always talk to a
82/// FooTargetStreamer.
83class MCTargetStreamer {
84protected:
85 MCStreamer &Streamer;
86
87public:
88 MCTargetStreamer(MCStreamer &S);
89 virtual ~MCTargetStreamer();
90
91 MCStreamer &getStreamer() { return Streamer; }
92
93 // Allow a target to add behavior to the EmitLabel of MCStreamer.
94 virtual void emitLabel(MCSymbol *Symbol);
95 // Allow a target to add behavior to the emitAssignment of MCStreamer.
96 virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value);
97
98 virtual void prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS,
99 const MCInst &Inst, const MCSubtargetInfo &STI);
100
101 virtual void emitDwarfFileDirective(StringRef Directive);
102
103 /// Update streamer for a new active section.
104 ///
105 /// This is called by PopSection and SwitchSection, if the current
106 /// section changes.
107 virtual void changeSection(const MCSection *CurSection, MCSection *Section,
108 const MCExpr *SubSection, raw_ostream &OS);
109
110 virtual void emitValue(const MCExpr *Value);
111
112 virtual void finish();
113};
114
115// FIXME: declared here because it is used from
116// lib/CodeGen/AsmPrinter/ARMException.cpp.
117class ARMTargetStreamer : public MCTargetStreamer {
118public:
119 ARMTargetStreamer(MCStreamer &S);
120 ~ARMTargetStreamer() override;
121
122 virtual void emitFnStart();
123 virtual void emitFnEnd();
124 virtual void emitCantUnwind();
125 virtual void emitPersonality(const MCSymbol *Personality);
126 virtual void emitPersonalityIndex(unsigned Index);
127 virtual void emitHandlerData();
128 virtual void emitSetFP(unsigned FpReg, unsigned SpReg,
129 int64_t Offset = 0);
130 virtual void emitMovSP(unsigned Reg, int64_t Offset = 0);
131 virtual void emitPad(int64_t Offset);
132 virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
133 bool isVector);
134 virtual void emitUnwindRaw(int64_t StackOffset,
135 const SmallVectorImpl<uint8_t> &Opcodes);
136
137 virtual void switchVendor(StringRef Vendor);
138 virtual void emitAttribute(unsigned Attribute, unsigned Value);
139 virtual void emitTextAttribute(unsigned Attribute, StringRef String);
140 virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
141 StringRef StringValue = "");
142 virtual void emitFPU(unsigned FPU);
143 virtual void emitArch(ARM::ArchKind Arch);
144 virtual void emitArchExtension(unsigned ArchExt);
145 virtual void emitObjectArch(ARM::ArchKind Arch);
146 void emitTargetAttributes(const MCSubtargetInfo &STI);
147 virtual void finishAttributeSection();
148 virtual void emitInst(uint32_t Inst, char Suffix = '\0');
149
150 virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE);
151
152 virtual void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value);
153
154 void finish() override;
155
156 /// Reset any state between object emissions, i.e. the equivalent of
157 /// MCStreamer's reset method.
158 virtual void reset();
159
160 /// Callback used to implement the ldr= pseudo.
161 /// Add a new entry to the constant pool for the current section and return an
162 /// MCExpr that can be used to refer to the constant pool location.
163 const MCExpr *addConstantPoolEntry(const MCExpr *, SMLoc Loc);
164
165 /// Callback used to implemnt the .ltorg directive.
166 /// Emit contents of constant pool for the current section.
167 void emitCurrentConstantPool();
168
169private:
170 std::unique_ptr<AssemblerConstantPools> ConstantPools;
171};
172
173/// \brief Streaming machine code generation interface.
174///
175/// This interface is intended to provide a programatic interface that is very
176/// similar to the level that an assembler .s file provides. It has callbacks
177/// to emit bytes, handle directives, etc. The implementation of this interface
178/// retains state to know what the current section is etc.
179///
180/// There are multiple implementations of this interface: one for writing out
181/// a .s file, and implementations that write out .o files of various formats.
182///
183class MCStreamer {
184 MCContext &Context;
185 std::unique_ptr<MCTargetStreamer> TargetStreamer;
186
187 std::vector<MCDwarfFrameInfo> DwarfFrameInfos;
188 MCDwarfFrameInfo *getCurrentDwarfFrameInfo();
189
190 /// Similar to DwarfFrameInfos, but for SEH unwind info. Chained frames may
191 /// refer to each other, so use std::unique_ptr to provide pointer stability.
192 std::vector<std::unique_ptr<WinEH::FrameInfo>> WinFrameInfos;
193
194 WinEH::FrameInfo *CurrentWinFrameInfo;
195
196 /// Retreive the current frame info if one is available and it is not yet
197 /// closed. Otherwise, issue an error and return null.
198 WinEH::FrameInfo *EnsureValidWinFrameInfo(SMLoc Loc);
199
200 /// \brief Tracks an index to represent the order a symbol was emitted in.
201 /// Zero means we did not emit that symbol.
202 DenseMap<const MCSymbol *, unsigned> SymbolOrdering;
203
204 /// \brief This is stack of current and previous section values saved by
205 /// PushSection.
206 SmallVector<std::pair<MCSectionSubPair, MCSectionSubPair>, 4> SectionStack;
207
208 /// The next unique ID to use when creating a WinCFI-related section (.pdata
209 /// or .xdata). This ID ensures that we have a one-to-one mapping from
210 /// code section to unwind info section, which MSVC's incremental linker
211 /// requires.
212 unsigned NextWinCFIID = 0;
213
214protected:
215 MCStreamer(MCContext &Ctx);
216
217 virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
218 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame);
219
220 /// When emitting an object file, create and emit a real label. When emitting
221 /// textual assembly, this should do nothing to avoid polluting our output.
222 virtual MCSymbol *EmitCFILabel();
223
224 WinEH::FrameInfo *getCurrentWinFrameInfo() {
225 return CurrentWinFrameInfo;
226 }
227
228 virtual void EmitWindowsUnwindTables();
229
230 virtual void EmitRawTextImpl(StringRef String);
231
232public:
233 MCStreamer(const MCStreamer &) = delete;
234 MCStreamer &operator=(const MCStreamer &) = delete;
235 virtual ~MCStreamer();
236
237 void visitUsedExpr(const MCExpr &Expr);
238 virtual void visitUsedSymbol(const MCSymbol &Sym);
239
240 void setTargetStreamer(MCTargetStreamer *TS) {
241 TargetStreamer.reset(TS);
242 }
243
244 /// State management
245 ///
246 virtual void reset();
247
248 MCContext &getContext() const { return Context; }
249
250 MCTargetStreamer *getTargetStreamer() {
251 return TargetStreamer.get();
252 }
253
254 unsigned getNumFrameInfos() { return DwarfFrameInfos.size(); }
255 ArrayRef<MCDwarfFrameInfo> getDwarfFrameInfos() const {
256 return DwarfFrameInfos;
257 }
258
259 bool hasUnfinishedDwarfFrameInfo();
260
261 unsigned getNumWinFrameInfos() { return WinFrameInfos.size(); }
262 ArrayRef<std::unique_ptr<WinEH::FrameInfo>> getWinFrameInfos() const {
263 return WinFrameInfos;
264 }
265
266 void generateCompactUnwindEncodings(MCAsmBackend *MAB);
267
268 /// \name Assembly File Formatting.
269 /// @{
270
271 /// \brief Return true if this streamer supports verbose assembly and if it is
272 /// enabled.
273 virtual bool isVerboseAsm() const { return false; }
274
275 /// \brief Return true if this asm streamer supports emitting unformatted text
276 /// to the .s file with EmitRawText.
277 virtual bool hasRawTextSupport() const { return false; }
278
279 /// \brief Is the integrated assembler required for this streamer to function
280 /// correctly?
281 virtual bool isIntegratedAssemblerRequired() const { return false; }
282
283 /// \brief Add a textual comment.
284 ///
285 /// Typically for comments that can be emitted to the generated .s
286 /// file if applicable as a QoI issue to make the output of the compiler
287 /// more readable. This only affects the MCAsmStreamer, and only when
288 /// verbose assembly output is enabled.
289 ///
290 /// If the comment includes embedded \n's, they will each get the comment
291 /// prefix as appropriate. The added comment should not end with a \n.
292 /// By default, each comment is terminated with an end of line, i.e. the
293 /// EOL param is set to true by default. If one prefers not to end the
294 /// comment with a new line then the EOL param should be passed
295 /// with a false value.
296 virtual void AddComment(const Twine &T, bool EOL = true) {}
297
298 /// \brief Return a raw_ostream that comments can be written to. Unlike
299 /// AddComment, you are required to terminate comments with \n if you use this
300 /// method.
301 virtual raw_ostream &GetCommentOS();
302
303 /// \brief Print T and prefix it with the comment string (normally #) and
304 /// optionally a tab. This prints the comment immediately, not at the end of
305 /// the current line. It is basically a safe version of EmitRawText: since it
306 /// only prints comments, the object streamer ignores it instead of asserting.
307 virtual void emitRawComment(const Twine &T, bool TabPrefix = true);
308
309 /// \brief Add explicit comment T. T is required to be a valid
310 /// comment in the output and does not need to be escaped.
311 virtual void addExplicitComment(const Twine &T);
312
313 /// \brief Emit added explicit comments.
314 virtual void emitExplicitComments();
315
316 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
317 virtual void AddBlankLine() {}
318
319 /// @}
320
321 /// \name Symbol & Section Management
322 /// @{
323
324 /// \brief Return the current section that the streamer is emitting code to.
325 MCSectionSubPair getCurrentSection() const {
326 if (!SectionStack.empty())
327 return SectionStack.back().first;
328 return MCSectionSubPair();
329 }
330 MCSection *getCurrentSectionOnly() const { return getCurrentSection().first; }
331
332 /// \brief Return the previous section that the streamer is emitting code to.
333 MCSectionSubPair getPreviousSection() const {
334 if (!SectionStack.empty())
335 return SectionStack.back().second;
336 return MCSectionSubPair();
337 }
338
339 /// \brief Returns an index to represent the order a symbol was emitted in.
340 /// (zero if we did not emit that symbol)
341 unsigned GetSymbolOrder(const MCSymbol *Sym) const {
342 return SymbolOrdering.lookup(Sym);
343 }
344
345 /// \brief Update streamer for a new active section.
346 ///
347 /// This is called by PopSection and SwitchSection, if the current
348 /// section changes.
349 virtual void ChangeSection(MCSection *, const MCExpr *);
350
351 /// \brief Save the current and previous section on the section stack.
352 void PushSection() {
353 SectionStack.push_back(
354 std::make_pair(getCurrentSection(), getPreviousSection()));
355 }
356
357 /// \brief Restore the current and previous section from the section stack.
358 /// Calls ChangeSection as needed.
359 ///
360 /// Returns false if the stack was empty.
361 bool PopSection() {
362 if (SectionStack.size() <= 1)
363 return false;
364 auto I = SectionStack.end();
365 --I;
366 MCSectionSubPair OldSection = I->first;
367 --I;
368 MCSectionSubPair NewSection = I->first;
369
370 if (OldSection != NewSection)
371 ChangeSection(NewSection.first, NewSection.second);
372 SectionStack.pop_back();
373 return true;
374 }
375
376 bool SubSection(const MCExpr *Subsection) {
377 if (SectionStack.empty())
378 return false;
379
380 SwitchSection(SectionStack.back().first.first, Subsection);
381 return true;
382 }
383
384 /// Set the current section where code is being emitted to \p Section. This
385 /// is required to update CurSection.
386 ///
387 /// This corresponds to assembler directives like .section, .text, etc.
388 virtual void SwitchSection(MCSection *Section,
389 const MCExpr *Subsection = nullptr);
390
391 /// \brief Set the current section where code is being emitted to \p Section.
392 /// This is required to update CurSection. This version does not call
393 /// ChangeSection.
394 void SwitchSectionNoChange(MCSection *Section,
395 const MCExpr *Subsection = nullptr) {
396 assert(Section && "Cannot switch to a null section!");
397 MCSectionSubPair curSection = SectionStack.back().first;
398 SectionStack.back().second = curSection;
399 if (MCSectionSubPair(Section, Subsection) != curSection)
400 SectionStack.back().first = MCSectionSubPair(Section, Subsection);
401 }
402
403 /// \brief Create the default sections and set the initial one.
404 virtual void InitSections(bool NoExecStack);
405
406 MCSymbol *endSection(MCSection *Section);
407
408 /// \brief Sets the symbol's section.
409 ///
410 /// Each emitted symbol will be tracked in the ordering table,
411 /// so we can sort on them later.
412 void AssignFragment(MCSymbol *Symbol, MCFragment *Fragment);
413
414 /// \brief Emit a label for \p Symbol into the current section.
415 ///
416 /// This corresponds to an assembler statement such as:
417 /// foo:
418 ///
419 /// \param Symbol - The symbol to emit. A given symbol should only be
420 /// emitted as a label once, and symbols emitted as a label should never be
421 /// used in an assignment.
422 // FIXME: These emission are non-const because we mutate the symbol to
423 // add the section we're emitting it to later.
424 virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc());
425
426 virtual void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol);
427
428 /// \brief Note in the output the specified \p Flag.
429 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
430
431 /// \brief Emit the given list \p Options of strings as linker
432 /// options into the output.
433 virtual void EmitLinkerOptions(ArrayRef<std::string> Kind) {}
434
435 /// \brief Note in the output the specified region \p Kind.
436 virtual void EmitDataRegion(MCDataRegionType Kind) {}
437
438 /// \brief Specify the Mach-O minimum deployment target version.
439 virtual void EmitVersionMin(MCVersionMinType Type, unsigned Major,
440 unsigned Minor, unsigned Update) {}
441
442 /// Emit/Specify Mach-O build version command.
443 /// \p Platform should be one of MachO::PlatformType.
444 virtual void EmitBuildVersion(unsigned Platform, unsigned Major,
445 unsigned Minor, unsigned Update) {}
446
447 void EmitVersionForTarget(const Triple &Target);
448
449 /// \brief Note in the output that the specified \p Func is a Thumb mode
450 /// function (ARM target only).
451 virtual void EmitThumbFunc(MCSymbol *Func);
452
453 /// \brief Emit an assignment of \p Value to \p Symbol.
454 ///
455 /// This corresponds to an assembler statement such as:
456 /// symbol = value
457 ///
458 /// The assignment generates no code, but has the side effect of binding the
459 /// value in the current context. For the assembly streamer, this prints the
460 /// binding into the .s file.
461 ///
462 /// \param Symbol - The symbol being assigned to.
463 /// \param Value - The value for the symbol.
464 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
465
466 /// \brief Emit an weak reference from \p Alias to \p Symbol.
467 ///
468 /// This corresponds to an assembler statement such as:
469 /// .weakref alias, symbol
470 ///
471 /// \param Alias - The alias that is being created.
472 /// \param Symbol - The symbol being aliased.
473 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
474
475 /// \brief Add the given \p Attribute to \p Symbol.
476 virtual bool EmitSymbolAttribute(MCSymbol *Symbol,
477 MCSymbolAttr Attribute) = 0;
478
479 /// \brief Set the \p DescValue for the \p Symbol.
480 ///
481 /// \param Symbol - The symbol to have its n_desc field set.
482 /// \param DescValue - The value to set into the n_desc field.
483 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
484
485 /// \brief Start emitting COFF symbol definition
486 ///
487 /// \param Symbol - The symbol to have its External & Type fields set.
488 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
489
490 /// \brief Emit the storage class of the symbol.
491 ///
492 /// \param StorageClass - The storage class the symbol should have.
493 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
494
495 /// \brief Emit the type of the symbol.
496 ///
497 /// \param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
498 virtual void EmitCOFFSymbolType(int Type);
499
500 /// \brief Marks the end of the symbol definition.
501 virtual void EndCOFFSymbolDef();
502
503 virtual void EmitCOFFSafeSEH(MCSymbol const *Symbol);
504
505 /// \brief Emits the symbol table index of a Symbol into the current section.
506 virtual void EmitCOFFSymbolIndex(MCSymbol const *Symbol);
507
508 /// \brief Emits a COFF section index.
509 ///
510 /// \param Symbol - Symbol the section number relocation should point to.
511 virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
512
513 /// \brief Emits a COFF section relative relocation.
514 ///
515 /// \param Symbol - Symbol the section relative relocation should point to.
516 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset);
517
518 /// \brief Emit an ELF .size directive.
519 ///
520 /// This corresponds to an assembler statement such as:
521 /// .size symbol, expression
522 virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value);
523
524 /// \brief Emit an ELF .symver directive.
525 ///
526 /// This corresponds to an assembler statement such as:
527 /// .symver _start, foo@@SOME_VERSION
528 /// \param AliasName - The versioned alias (i.e. "foo@@SOME_VERSION")
529 /// \param Aliasee - The aliased symbol (i.e. "_start")
530 virtual void emitELFSymverDirective(StringRef AliasName,
531 const MCSymbol *Aliasee);
532
533 /// \brief Emit a Linker Optimization Hint (LOH) directive.
534 /// \param Args - Arguments of the LOH.
535 virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
536
537 /// \brief Emit a common symbol.
538 ///
539 /// \param Symbol - The common symbol to emit.
540 /// \param Size - The size of the common symbol.
541 /// \param ByteAlignment - The alignment of the symbol if
542 /// non-zero. This must be a power of 2.
543 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
544 unsigned ByteAlignment) = 0;
545
546 /// \brief Emit a local common (.lcomm) symbol.
547 ///
548 /// \param Symbol - The common symbol to emit.
549 /// \param Size - The size of the common symbol.
550 /// \param ByteAlignment - The alignment of the common symbol in bytes.
551 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
552 unsigned ByteAlignment);
553
554 /// \brief Emit the zerofill section and an optional symbol.
555 ///
556 /// \param Section - The zerofill section to create and or to put the symbol
557 /// \param Symbol - The zerofill symbol to emit, if non-NULL.
558 /// \param Size - The size of the zerofill symbol.
559 /// \param ByteAlignment - The alignment of the zerofill symbol if
560 /// non-zero. This must be a power of 2 on some targets.
561 virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
562 uint64_t Size = 0, unsigned ByteAlignment = 0) = 0;
563
564 /// \brief Emit a thread local bss (.tbss) symbol.
565 ///
566 /// \param Section - The thread local common section.
567 /// \param Symbol - The thread local common symbol to emit.
568 /// \param Size - The size of the symbol.
569 /// \param ByteAlignment - The alignment of the thread local common symbol
570 /// if non-zero. This must be a power of 2 on some targets.
571 virtual void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
572 uint64_t Size, unsigned ByteAlignment = 0);
573
574 /// @}
575 /// \name Generating Data
576 /// @{
577
578 /// \brief Emit the bytes in \p Data into the output.
579 ///
580 /// This is used to implement assembler directives such as .byte, .ascii,
581 /// etc.
582 virtual void EmitBytes(StringRef Data);
583
584 /// Functionally identical to EmitBytes. When emitting textual assembly, this
585 /// method uses .byte directives instead of .ascii or .asciz for readability.
586 virtual void EmitBinaryData(StringRef Data);
587
588 /// \brief Emit the expression \p Value into the output as a native
589 /// integer of the given \p Size bytes.
590 ///
591 /// This is used to implement assembler directives such as .word, .quad,
592 /// etc.
593 ///
594 /// \param Value - The value to emit.
595 /// \param Size - The size of the integer (in bytes) to emit. This must
596 /// match a native machine width.
597 /// \param Loc - The location of the expression for error reporting.
598 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
599 SMLoc Loc = SMLoc());
600
601 void EmitValue(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc());
602
603 /// \brief Special case of EmitValue that avoids the client having
604 /// to pass in a MCExpr for constant integers.
605 virtual void EmitIntValue(uint64_t Value, unsigned Size);
606
607 virtual void EmitULEB128Value(const MCExpr *Value);
608
609 virtual void EmitSLEB128Value(const MCExpr *Value);
610
611 /// \brief Special case of EmitULEB128Value that avoids the client having to
612 /// pass in a MCExpr for constant integers.
613 void EmitULEB128IntValue(uint64_t Value);
614
615 /// \brief Special case of EmitSLEB128Value that avoids the client having to
616 /// pass in a MCExpr for constant integers.
617 void EmitSLEB128IntValue(int64_t Value);
618
619 /// \brief Special case of EmitValue that avoids the client having to pass in
620 /// a MCExpr for MCSymbols.
621 void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
622 bool IsSectionRelative = false);
623
624 /// \brief Emit the expression \p Value into the output as a dtprel
625 /// (64-bit DTP relative) value.
626 ///
627 /// This is used to implement assembler directives such as .dtpreldword on
628 /// targets that support them.
629 virtual void EmitDTPRel64Value(const MCExpr *Value);
630
631 /// \brief Emit the expression \p Value into the output as a dtprel
632 /// (32-bit DTP relative) value.
633 ///
634 /// This is used to implement assembler directives such as .dtprelword on
635 /// targets that support them.
636 virtual void EmitDTPRel32Value(const MCExpr *Value);
637
638 /// \brief Emit the expression \p Value into the output as a tprel
639 /// (64-bit TP relative) value.
640 ///
641 /// This is used to implement assembler directives such as .tpreldword on
642 /// targets that support them.
643 virtual void EmitTPRel64Value(const MCExpr *Value);
644
645 /// \brief Emit the expression \p Value into the output as a tprel
646 /// (32-bit TP relative) value.
647 ///
648 /// This is used to implement assembler directives such as .tprelword on
649 /// targets that support them.
650 virtual void EmitTPRel32Value(const MCExpr *Value);
651
652 /// \brief Emit the expression \p Value into the output as a gprel64 (64-bit
653 /// GP relative) value.
654 ///
655 /// This is used to implement assembler directives such as .gpdword on
656 /// targets that support them.
657 virtual void EmitGPRel64Value(const MCExpr *Value);
658
659 /// \brief Emit the expression \p Value into the output as a gprel32 (32-bit
660 /// GP relative) value.
661 ///
662 /// This is used to implement assembler directives such as .gprel32 on
663 /// targets that support them.
664 virtual void EmitGPRel32Value(const MCExpr *Value);
665
666 /// \brief Emit NumBytes bytes worth of the value specified by FillValue.
667 /// This implements directives such as '.space'.
668 void emitFill(uint64_t NumBytes, uint8_t FillValue);
669
670 /// \brief Emit \p Size bytes worth of the value specified by \p FillValue.
671 ///
672 /// This is used to implement assembler directives such as .space or .skip.
673 ///
674 /// \param NumBytes - The number of bytes to emit.
675 /// \param FillValue - The value to use when filling bytes.
676 /// \param Loc - The location of the expression for error reporting.
677 virtual void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
678 SMLoc Loc = SMLoc());
679
680 /// \brief Emit \p NumValues copies of \p Size bytes. Each \p Size bytes is
681 /// taken from the lowest order 4 bytes of \p Expr expression.
682 ///
683 /// This is used to implement assembler directives such as .fill.
684 ///
685 /// \param NumValues - The number of copies of \p Size bytes to emit.
686 /// \param Size - The size (in bytes) of each repeated value.
687 /// \param Expr - The expression from which \p Size bytes are used.
688 virtual void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
689 SMLoc Loc = SMLoc());
690
691 /// \brief Emit NumBytes worth of zeros.
692 /// This function properly handles data in virtual sections.
693 void EmitZeros(uint64_t NumBytes);
694
695 /// \brief Emit some number of copies of \p Value until the byte alignment \p
696 /// ByteAlignment is reached.
697 ///
698 /// If the number of bytes need to emit for the alignment is not a multiple
699 /// of \p ValueSize, then the contents of the emitted fill bytes is
700 /// undefined.
701 ///
702 /// This used to implement the .align assembler directive.
703 ///
704 /// \param ByteAlignment - The alignment to reach. This must be a power of
705 /// two on some targets.
706 /// \param Value - The value to use when filling bytes.
707 /// \param ValueSize - The size of the integer (in bytes) to emit for
708 /// \p Value. This must match a native machine width.
709 /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
710 /// the alignment cannot be reached in this many bytes, no bytes are
711 /// emitted.
712 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
713 unsigned ValueSize = 1,
714 unsigned MaxBytesToEmit = 0);
715
716 /// \brief Emit nops until the byte alignment \p ByteAlignment is reached.
717 ///
718 /// This used to align code where the alignment bytes may be executed. This
719 /// can emit different bytes for different sizes to optimize execution.
720 ///
721 /// \param ByteAlignment - The alignment to reach. This must be a power of
722 /// two on some targets.
723 /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
724 /// the alignment cannot be reached in this many bytes, no bytes are
725 /// emitted.
726 virtual void EmitCodeAlignment(unsigned ByteAlignment,
727 unsigned MaxBytesToEmit = 0);
728
729 /// \brief Emit some number of copies of \p Value until the byte offset \p
730 /// Offset is reached.
731 ///
732 /// This is used to implement assembler directives such as .org.
733 ///
734 /// \param Offset - The offset to reach. This may be an expression, but the
735 /// expression must be associated with the current section.
736 /// \param Value - The value to use when filling bytes.
737 virtual void emitValueToOffset(const MCExpr *Offset, unsigned char Value,
738 SMLoc Loc);
739
740 virtual void
741 EmitCodePaddingBasicBlockStart(const MCCodePaddingContext &Context) {}
742
743 virtual void
744 EmitCodePaddingBasicBlockEnd(const MCCodePaddingContext &Context) {}
745
746 /// @}
747
748 /// \brief Switch to a new logical file. This is used to implement the '.file
749 /// "foo.c"' assembler directive.
750 virtual void EmitFileDirective(StringRef Filename);
751
752 /// \brief Emit the "identifiers" directive. This implements the
753 /// '.ident "version foo"' assembler directive.
754 virtual void EmitIdent(StringRef IdentString) {}
755
756 /// \brief Associate a filename with a specified logical file number. This
757 /// implements the DWARF2 '.file 4 "foo.c"' assembler directive.
758 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
759 StringRef Filename,
760 MD5::MD5Result *Checksum = nullptr,
761 Optional<StringRef> Source = None,
762 unsigned CUID = 0) {
763 return cantFail(
764 tryEmitDwarfFileDirective(FileNo, Directory, Filename, Checksum,
765 Source, CUID));
766 }
767
768 /// Associate a filename with a specified logical file number.
769 /// Also associate a directory, optional checksum, and optional source
770 /// text with the logical file. This implements the DWARF2
771 /// '.file 4 "dir/foo.c"' assembler directive, and the DWARF5
772 /// '.file 4 "dir/foo.c" md5 "..." source "..."' assembler directive.
773 virtual Expected<unsigned> tryEmitDwarfFileDirective(
774 unsigned FileNo, StringRef Directory, StringRef Filename,
775 MD5::MD5Result *Checksum = nullptr, Optional<StringRef> Source = None,
776 unsigned CUID = 0);
777
778 /// Specify the "root" file of the compilation, using the ".file 0" extension.
779 virtual void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
780 MD5::MD5Result *Checksum,
781 Optional<StringRef> Source,
782 unsigned CUID = 0);
783
784 /// \brief This implements the DWARF2 '.loc fileno lineno ...' assembler
785 /// directive.
786 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
787 unsigned Column, unsigned Flags,
788 unsigned Isa, unsigned Discriminator,
789 StringRef FileName);
790
791 /// Associate a filename with a specified logical file number, and also
792 /// specify that file's checksum information. This implements the '.cv_file 4
793 /// "foo.c"' assembler directive. Returns true on success.
794 virtual bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
795 ArrayRef<uint8_t> Checksum,
796 unsigned ChecksumKind);
797
798 /// \brief Introduces a function id for use with .cv_loc.
799 virtual bool EmitCVFuncIdDirective(unsigned FunctionId);
800
801 /// \brief Introduces an inline call site id for use with .cv_loc. Includes
802 /// extra information for inline line table generation.
803 virtual bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
804 unsigned IAFile, unsigned IALine,
805 unsigned IACol, SMLoc Loc);
806
807 /// \brief This implements the CodeView '.cv_loc' assembler directive.
808 virtual void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
809 unsigned Line, unsigned Column,
810 bool PrologueEnd, bool IsStmt,
811 StringRef FileName, SMLoc Loc);
812
813 /// \brief This implements the CodeView '.cv_linetable' assembler directive.
814 virtual void EmitCVLinetableDirective(unsigned FunctionId,
815 const MCSymbol *FnStart,
816 const MCSymbol *FnEnd);
817
818 /// \brief This implements the CodeView '.cv_inline_linetable' assembler
819 /// directive.
820 virtual void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
821 unsigned SourceFileId,
822 unsigned SourceLineNum,
823 const MCSymbol *FnStartSym,
824 const MCSymbol *FnEndSym);
825
826 /// \brief This implements the CodeView '.cv_def_range' assembler
827 /// directive.
828 virtual void EmitCVDefRangeDirective(
829 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
830 StringRef FixedSizePortion);
831
832 /// \brief This implements the CodeView '.cv_stringtable' assembler directive.
833 virtual void EmitCVStringTableDirective() {}
834
835 /// \brief This implements the CodeView '.cv_filechecksums' assembler directive.
836 virtual void EmitCVFileChecksumsDirective() {}
837
838 /// This implements the CodeView '.cv_filechecksumoffset' assembler
839 /// directive.
840 virtual void EmitCVFileChecksumOffsetDirective(unsigned FileNo) {}
841
842 /// This implements the CodeView '.cv_fpo_data' assembler directive.
843 virtual void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc = {}) {}
844
845 /// Emit the absolute difference between two symbols.
846 ///
847 /// \pre Offset of \c Hi is greater than the offset \c Lo.
848 virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
849 unsigned Size);
850
851 /// Emit the absolute difference between two symbols encoded with ULEB128.
852 virtual void emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
853 const MCSymbol *Lo);
854
855 virtual MCSymbol *getDwarfLineTableSymbol(unsigned CUID);
856 virtual void EmitCFISections(bool EH, bool Debug);
857 void EmitCFIStartProc(bool IsSimple);
858 void EmitCFIEndProc();
859 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
860 virtual void EmitCFIDefCfaOffset(int64_t Offset);
861 virtual void EmitCFIDefCfaRegister(int64_t Register);
862 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
863 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
864 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
865 virtual void EmitCFIRememberState();
866 virtual void EmitCFIRestoreState();
867 virtual void EmitCFISameValue(int64_t Register);
868 virtual void EmitCFIRestore(int64_t Register);
869 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
870 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
871 virtual void EmitCFIEscape(StringRef Values);
872 virtual void EmitCFIReturnColumn(int64_t Register);
873 virtual void EmitCFIGnuArgsSize(int64_t Size);
874 virtual void EmitCFISignalFrame();
875 virtual void EmitCFIUndefined(int64_t Register);
876 virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
877 virtual void EmitCFIWindowSave();
878
879 virtual void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc = SMLoc());
880 virtual void EmitWinCFIEndProc(SMLoc Loc = SMLoc());
881 virtual void EmitWinCFIStartChained(SMLoc Loc = SMLoc());
882 virtual void EmitWinCFIEndChained(SMLoc Loc = SMLoc());
883 virtual void EmitWinCFIPushReg(unsigned Register, SMLoc Loc = SMLoc());
884 virtual void EmitWinCFISetFrame(unsigned Register, unsigned Offset,
885 SMLoc Loc = SMLoc());
886 virtual void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc = SMLoc());
887 virtual void EmitWinCFISaveReg(unsigned Register, unsigned Offset,
888 SMLoc Loc = SMLoc());
889 virtual void EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
890 SMLoc Loc = SMLoc());
891 virtual void EmitWinCFIPushFrame(bool Code, SMLoc Loc = SMLoc());
892 virtual void EmitWinCFIEndProlog(SMLoc Loc = SMLoc());
893 virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
894 SMLoc Loc = SMLoc());
895 virtual void EmitWinEHHandlerData(SMLoc Loc = SMLoc());
896
897 /// Get the .pdata section used for the given section. Typically the given
898 /// section is either the main .text section or some other COMDAT .text
899 /// section, but it may be any section containing code.
900 MCSection *getAssociatedPDataSection(const MCSection *TextSec);
901
902 /// Get the .xdata section used for the given section.
903 MCSection *getAssociatedXDataSection(const MCSection *TextSec);
904
905 virtual void EmitSyntaxDirective();
906
907 /// \brief Emit a .reloc directive.
908 /// Returns true if the relocation could not be emitted because Name is not
909 /// known.
910 virtual bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
911 const MCExpr *Expr, SMLoc Loc) {
912 return true;
913 }
914
915 /// \brief Emit the given \p Instruction into the current section.
916 /// PrintSchedInfo == true then schedul comment should be added to output
917 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
918 bool PrintSchedInfo = false);
919
920 /// \brief Set the bundle alignment mode from now on in the section.
921 /// The argument is the power of 2 to which the alignment is set. The
922 /// value 0 means turn the bundle alignment off.
923 virtual void EmitBundleAlignMode(unsigned AlignPow2);
924
925 /// \brief The following instructions are a bundle-locked group.
926 ///
927 /// \param AlignToEnd - If true, the bundle-locked group will be aligned to
928 /// the end of a bundle.
929 virtual void EmitBundleLock(bool AlignToEnd);
930
931 /// \brief Ends a bundle-locked group.
932 virtual void EmitBundleUnlock();
933
934 /// \brief If this file is backed by a assembly streamer, this dumps the
935 /// specified string in the output .s file. This capability is indicated by
936 /// the hasRawTextSupport() predicate. By default this aborts.
937 void EmitRawText(const Twine &String);
938
939 /// \brief Streamer specific finalization.
940 virtual void FinishImpl();
941 /// \brief Finish emission of machine code.
942 void Finish();
943
944 virtual bool mayHaveInstructions(MCSection &Sec) const { return true; }
945};
946
947/// Create a dummy machine code streamer, which does nothing. This is useful for
948/// timing the assembler front end.
949MCStreamer *createNullStreamer(MCContext &Ctx);
950
951/// Create a machine code streamer which will print out assembly for the native
952/// target, suitable for compiling with a native assembler.
953///
954/// \param InstPrint - If given, the instruction printer to use. If not given
955/// the MCInst representation will be printed. This method takes ownership of
956/// InstPrint.
957///
958/// \param CE - If given, a code emitter to use to show the instruction
959/// encoding inline with the assembly. This method takes ownership of \p CE.
960///
961/// \param TAB - If given, a target asm backend to use to show the fixup
962/// information in conjunction with encoding information. This method takes
963/// ownership of \p TAB.
964///
965/// \param ShowInst - Whether to show the MCInst representation inline with
966/// the assembly.
967MCStreamer *createAsmStreamer(MCContext &Ctx,
968 std::unique_ptr<formatted_raw_ostream> OS,
969 bool isVerboseAsm, bool useDwarfDirectory,
970 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
971 MCAsmBackend *TAB, bool ShowInst);
972
973} // end namespace llvm
974
975#endif // LLVM_MC_MCSTREAMER_H