1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCCodeView.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Path.h"
39 class MCAsmStreamer final : public MCStreamer {
40 std::unique_ptr<formatted_raw_ostream> OSOwner;
41 formatted_raw_ostream &OS;
43 std::unique_ptr<MCInstPrinter> InstPrinter;
44 std::unique_ptr<MCCodeEmitter> Emitter;
45 std::unique_ptr<MCAsmBackend> AsmBackend;
47 SmallString<128> ExplicitCommentToEmit;
48 SmallString<128> CommentToEmit;
49 raw_svector_ostream CommentStream;
51 unsigned IsVerboseAsm : 1;
52 unsigned ShowInst : 1;
53 unsigned UseDwarfDirectory : 1;
55 void EmitRegisterName(int64_t Register);
56 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
57 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
60 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
61 bool isVerboseAsm, bool useDwarfDirectory,
62 MCInstPrinter *printer, MCCodeEmitter *emitter,
63 MCAsmBackend *asmbackend, bool showInst)
64 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
65 MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
66 AsmBackend(asmbackend), CommentStream(CommentToEmit),
67 IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
68 UseDwarfDirectory(useDwarfDirectory) {
71 InstPrinter->setCommentStream(CommentStream);
74 inline void EmitEOL() {
75 // Dump Explicit Comments here.
76 emitExplicitComments();
77 // If we don't have any comments, just emit a \n.
85 void EmitSyntaxDirective() override;
87 void EmitCommentsAndEOL();
89 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
91 bool isVerboseAsm() const override { return IsVerboseAsm; }
93 /// hasRawTextSupport - We support EmitRawText.
94 bool hasRawTextSupport() const override { return true; }
96 /// AddComment - Add a comment that can be emitted to the generated .s
97 /// file if applicable as a QoI issue to make the output of the compiler
98 /// more readable. This only affects the MCAsmStreamer, and only when
99 /// verbose assembly output is enabled.
100 void AddComment(const Twine &T, bool EOL = true) override;
102 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
103 /// If PrintSchedInfo - is true then the comment sched:[x:y] should
104 // be added to output if it's being supported by target
105 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &,
106 bool PrintSchedInfo);
108 /// GetCommentOS - Return a raw_ostream that comments can be written to.
109 /// Unlike AddComment, you are required to terminate comments with \n if you
111 raw_ostream &GetCommentOS() override {
113 return nulls(); // Discard comments unless in verbose asm mode.
114 return CommentStream;
117 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
119 void addExplicitComment(const Twine &T) override;
120 void emitExplicitComments() override;
122 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
123 void AddBlankLine() override {
127 /// @name MCStreamer Interface
130 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
132 void emitELFSymverDirective(StringRef AliasName,
133 const MCSymbol *Aliasee) override;
135 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
136 void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
138 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
139 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
140 void EmitDataRegion(MCDataRegionType Kind) override;
141 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
142 unsigned Update) override;
143 void EmitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
144 unsigned Update) override;
145 void EmitThumbFunc(MCSymbol *Func) override;
147 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
148 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
149 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
151 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
152 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
153 void EmitCOFFSymbolStorageClass(int StorageClass) override;
154 void EmitCOFFSymbolType(int Type) override;
155 void EndCOFFSymbolDef() override;
156 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
157 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
158 void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
159 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
160 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
161 unsigned ByteAlignment) override;
163 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
165 /// @param Symbol - The common symbol to emit.
166 /// @param Size - The size of the common symbol.
167 /// @param ByteAlignment - The alignment of the common symbol in bytes.
168 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
169 unsigned ByteAlignment) override;
171 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
172 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
174 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
175 unsigned ByteAlignment = 0) override;
177 void EmitBinaryData(StringRef Data) override;
179 void EmitBytes(StringRef Data) override;
181 void EmitValueImpl(const MCExpr *Value, unsigned Size,
182 SMLoc Loc = SMLoc()) override;
183 void EmitIntValue(uint64_t Value, unsigned Size) override;
185 void EmitULEB128Value(const MCExpr *Value) override;
187 void EmitSLEB128Value(const MCExpr *Value) override;
189 void EmitDTPRel32Value(const MCExpr *Value) override;
190 void EmitDTPRel64Value(const MCExpr *Value) override;
191 void EmitTPRel32Value(const MCExpr *Value) override;
192 void EmitTPRel64Value(const MCExpr *Value) override;
194 void EmitGPRel64Value(const MCExpr *Value) override;
196 void EmitGPRel32Value(const MCExpr *Value) override;
198 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
199 SMLoc Loc = SMLoc()) override;
201 void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) override;
203 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
204 SMLoc Loc = SMLoc()) override;
206 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
207 unsigned ValueSize = 1,
208 unsigned MaxBytesToEmit = 0) override;
210 void EmitCodeAlignment(unsigned ByteAlignment,
211 unsigned MaxBytesToEmit = 0) override;
213 void emitValueToOffset(const MCExpr *Offset,
217 void EmitFileDirective(StringRef Filename) override;
218 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
220 unsigned CUID = 0) override;
221 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
222 unsigned Column, unsigned Flags,
223 unsigned Isa, unsigned Discriminator,
224 StringRef FileName) override;
225 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
227 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
228 ArrayRef<uint8_t> Checksum,
229 unsigned ChecksumKind) override;
230 bool EmitCVFuncIdDirective(unsigned FuncId) override;
231 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
232 unsigned IAFile, unsigned IALine,
233 unsigned IACol, SMLoc Loc) override;
234 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
235 unsigned Column, bool PrologueEnd, bool IsStmt,
236 StringRef FileName, SMLoc Loc) override;
237 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
238 const MCSymbol *FnEnd) override;
239 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
240 unsigned SourceFileId,
241 unsigned SourceLineNum,
242 const MCSymbol *FnStartSym,
243 const MCSymbol *FnEndSym) override;
244 void EmitCVDefRangeDirective(
245 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
246 StringRef FixedSizePortion) override;
247 void EmitCVStringTableDirective() override;
248 void EmitCVFileChecksumsDirective() override;
249 void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override;
250 void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
252 void EmitIdent(StringRef IdentString) override;
253 void EmitCFISections(bool EH, bool Debug) override;
254 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
255 void EmitCFIDefCfaOffset(int64_t Offset) override;
256 void EmitCFIDefCfaRegister(int64_t Register) override;
257 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
258 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
259 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
260 void EmitCFIRememberState() override;
261 void EmitCFIRestoreState() override;
262 void EmitCFIRestore(int64_t Register) override;
263 void EmitCFISameValue(int64_t Register) override;
264 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
265 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
266 void EmitCFIEscape(StringRef Values) override;
267 void EmitCFIGnuArgsSize(int64_t Size) override;
268 void EmitCFISignalFrame() override;
269 void EmitCFIUndefined(int64_t Register) override;
270 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
271 void EmitCFIWindowSave() override;
272 void EmitCFIReturnColumn(int64_t Register) override;
274 void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
275 void EmitWinCFIEndProc(SMLoc Loc) override;
276 void EmitWinCFIStartChained(SMLoc Loc) override;
277 void EmitWinCFIEndChained(SMLoc Loc) override;
278 void EmitWinCFIPushReg(unsigned Register, SMLoc Loc) override;
279 void EmitWinCFISetFrame(unsigned Register, unsigned Offset,
281 void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
282 void EmitWinCFISaveReg(unsigned Register, unsigned Offset,
284 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
286 void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
287 void EmitWinCFIEndProlog(SMLoc Loc) override;
289 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
291 void EmitWinEHHandlerData(SMLoc Loc) override;
293 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
294 bool PrintSchedInfo) override;
296 void EmitBundleAlignMode(unsigned AlignPow2) override;
297 void EmitBundleLock(bool AlignToEnd) override;
298 void EmitBundleUnlock() override;
300 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
301 const MCExpr *Expr, SMLoc Loc) override;
303 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
304 /// the specified string in the output .s file. This capability is
305 /// indicated by the hasRawTextSupport() predicate.
306 void EmitRawTextImpl(StringRef String) override;
308 void FinishImpl() override;
311 } // end anonymous namespace.
313 /// AddComment - Add a comment that can be emitted to the generated .s
314 /// file if applicable as a QoI issue to make the output of the compiler
315 /// more readable. This only affects the MCAsmStreamer, and only when
316 /// verbose assembly output is enabled.
317 /// By deafult EOL is set to true so that each comment goes on its own line.
318 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
319 if (!IsVerboseAsm) return;
321 T.toVector(CommentToEmit);
324 CommentToEmit.push_back('\n'); // Place comment in a new line.
327 void MCAsmStreamer::EmitCommentsAndEOL() {
328 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
333 StringRef Comments = CommentToEmit;
335 assert(Comments.back() == '\n' &&
336 "Comment array not newline terminated");
338 // Emit a line of comments.
339 OS.PadToColumn(MAI->getCommentColumn());
340 size_t Position = Comments.find('\n');
341 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
343 Comments = Comments.substr(Position+1);
344 } while (!Comments.empty());
346 CommentToEmit.clear();
349 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
350 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
351 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
354 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
357 OS << MAI->getCommentString() << T;
361 void MCAsmStreamer::addExplicitComment(const Twine &T) {
362 StringRef c = T.getSingleStringRef();
363 if (c.equals(StringRef(MAI->getSeparatorString())))
365 if (c.startswith(StringRef("//"))) {
366 ExplicitCommentToEmit.append("\t");
367 ExplicitCommentToEmit.append(MAI->getCommentString());
369 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
370 } else if (c.startswith(StringRef("/*"))) {
371 size_t p = 2, len = c.size() - 2;
372 // emit each line in comment as separate newline.
374 size_t newp = std::min(len, c.find_first_of("\r\n", p));
375 ExplicitCommentToEmit.append("\t");
376 ExplicitCommentToEmit.append(MAI->getCommentString());
377 ExplicitCommentToEmit.append(c.slice(p, newp).str());
378 // If we have another line in this comment add line
380 ExplicitCommentToEmit.append("\n");
383 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
384 ExplicitCommentToEmit.append("\t");
385 ExplicitCommentToEmit.append(c.str());
386 } else if (c.front() == '#') {
388 ExplicitCommentToEmit.append("\t");
389 ExplicitCommentToEmit.append(MAI->getCommentString());
390 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
392 assert(false && "Unexpected Assembly Comment");
393 // full line comments immediately output
394 if (c.back() == '\n')
395 emitExplicitComments();
398 void MCAsmStreamer::emitExplicitComments() {
399 StringRef Comments = ExplicitCommentToEmit;
400 if (!Comments.empty())
402 ExplicitCommentToEmit.clear();
405 void MCAsmStreamer::ChangeSection(MCSection *Section,
406 const MCExpr *Subsection) {
407 assert(Section && "Cannot switch to a null section!");
408 if (MCTargetStreamer *TS = getTargetStreamer()) {
409 TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
411 Section->PrintSwitchToSection(
412 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
417 void MCAsmStreamer::emitELFSymverDirective(StringRef AliasName,
418 const MCSymbol *Aliasee) {
420 Aliasee->print(OS, MAI);
421 OS << ", " << AliasName;
425 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
426 MCStreamer::EmitLabel(Symbol, Loc);
428 Symbol->print(OS, MAI);
429 OS << MAI->getLabelSuffix();
434 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
435 StringRef str = MCLOHIdToName(Kind);
438 int NbArgs = MCLOHIdToNbArgs(Kind);
439 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
440 assert(str != "" && "Invalid LOH name");
443 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
445 for (const MCSymbol *Arg : Args) {
454 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
456 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
457 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
458 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
459 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
460 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
465 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
466 assert(!Options.empty() && "At least one option is required!");
467 OS << "\t.linker_option \"" << Options[0] << '"';
468 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
469 ie = Options.end(); it != ie; ++it) {
470 OS << ", " << '"' << *it << '"';
475 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
476 if (!MAI->doesSupportDataRegionDirectives())
479 case MCDR_DataRegion: OS << "\t.data_region"; break;
480 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
481 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
482 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
483 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
488 static const char *getVersionMinDirective(MCVersionMinType Type) {
490 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
491 case MCVM_TvOSVersionMin: return ".tvos_version_min";
492 case MCVM_IOSVersionMin: return ".ios_version_min";
493 case MCVM_OSXVersionMin: return ".macosx_version_min";
495 llvm_unreachable("Invalid MC version min type");
498 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major,
499 unsigned Minor, unsigned Update) {
500 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
502 OS << ", " << Update;
506 static const char *getPlatformName(MachO::PlatformType Type) {
508 case MachO::PLATFORM_MACOS: return "macos";
509 case MachO::PLATFORM_IOS: return "ios";
510 case MachO::PLATFORM_TVOS: return "tvos";
511 case MachO::PLATFORM_WATCHOS: return "watchos";
512 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
514 llvm_unreachable("Invalid Mach-O platform type");
517 void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major,
518 unsigned Minor, unsigned Update) {
519 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
520 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
522 OS << ", " << Update;
526 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
527 // This needs to emit to a temporary string to get properly quoted
528 // MCSymbols when they have spaces in them.
529 OS << "\t.thumb_func";
530 // Only Mach-O hasSubsectionsViaSymbols()
531 if (MAI->hasSubsectionsViaSymbols()) {
533 Func->print(OS, MAI);
538 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
539 Symbol->print(OS, MAI);
541 Value->print(OS, MAI);
545 MCStreamer::EmitAssignment(Symbol, Value);
548 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
550 Alias->print(OS, MAI);
552 Symbol->print(OS, MAI);
556 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
557 MCSymbolAttr Attribute) {
559 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
560 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
561 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
562 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
563 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
564 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
565 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
566 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
567 if (!MAI->hasDotTypeDotSizeDirective())
568 return false; // Symbol attribute not supported
570 Symbol->print(OS, MAI);
571 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
573 default: return false;
574 case MCSA_ELF_TypeFunction: OS << "function"; break;
575 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
576 case MCSA_ELF_TypeObject: OS << "object"; break;
577 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
578 case MCSA_ELF_TypeCommon: OS << "common"; break;
579 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
580 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
584 case MCSA_Global: // .globl/.global
585 OS << MAI->getGlobalDirective();
587 case MCSA_Hidden: OS << "\t.hidden\t"; break;
588 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
589 case MCSA_Internal: OS << "\t.internal\t"; break;
590 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
591 case MCSA_Local: OS << "\t.local\t"; break;
592 case MCSA_NoDeadStrip:
593 if (!MAI->hasNoDeadStrip())
595 OS << "\t.no_dead_strip\t";
597 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
598 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
599 case MCSA_PrivateExtern:
600 OS << "\t.private_extern\t";
602 case MCSA_Protected: OS << "\t.protected\t"; break;
603 case MCSA_Reference: OS << "\t.reference\t"; break;
604 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
605 case MCSA_WeakDefinition:
606 OS << "\t.weak_definition\t";
609 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
610 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
613 Symbol->print(OS, MAI);
619 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
620 OS << ".desc" << ' ';
621 Symbol->print(OS, MAI);
622 OS << ',' << DescValue;
626 void MCAsmStreamer::EmitSyntaxDirective() {
627 if (MAI->getAssemblerDialect() == 1) {
628 OS << "\t.intel_syntax noprefix";
631 // FIXME: Currently emit unprefix'ed registers.
632 // The intel_syntax directive has one optional argument
633 // with may have a value of prefix or noprefix.
636 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
638 Symbol->print(OS, MAI);
643 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
644 OS << "\t.scl\t" << StorageClass << ';';
648 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
649 OS << "\t.type\t" << Type << ';';
653 void MCAsmStreamer::EndCOFFSymbolDef() {
658 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
659 OS << "\t.safeseh\t";
660 Symbol->print(OS, MAI);
664 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
666 Symbol->print(OS, MAI);
670 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
671 OS << "\t.secrel32\t";
672 Symbol->print(OS, MAI);
678 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
679 assert(MAI->hasDotTypeDotSizeDirective());
681 Symbol->print(OS, MAI);
683 Value->print(OS, MAI);
687 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
688 unsigned ByteAlignment) {
690 Symbol->print(OS, MAI);
693 if (ByteAlignment != 0) {
694 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
695 OS << ',' << ByteAlignment;
697 OS << ',' << Log2_32(ByteAlignment);
702 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
704 /// @param Symbol - The common symbol to emit.
705 /// @param Size - The size of the common symbol.
706 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
707 unsigned ByteAlign) {
709 Symbol->print(OS, MAI);
713 switch (MAI->getLCOMMDirectiveAlignmentType()) {
714 case LCOMM::NoAlignment:
715 llvm_unreachable("alignment not supported on .lcomm!");
716 case LCOMM::ByteAlignment:
717 OS << ',' << ByteAlign;
719 case LCOMM::Log2Alignment:
720 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
721 OS << ',' << Log2_32(ByteAlign);
728 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
729 uint64_t Size, unsigned ByteAlignment) {
731 AssignFragment(Symbol, &Section->getDummyFragment());
733 // Note: a .zerofill directive does not switch sections.
736 // This is a mach-o specific directive.
737 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
738 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
742 Symbol->print(OS, MAI);
744 if (ByteAlignment != 0)
745 OS << ',' << Log2_32(ByteAlignment);
750 // .tbss sym, size, align
751 // This depends that the symbol has already been mangled from the original,
753 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
754 uint64_t Size, unsigned ByteAlignment) {
755 AssignFragment(Symbol, &Section->getDummyFragment());
757 assert(Symbol && "Symbol shouldn't be NULL!");
758 // Instead of using the Section we'll just use the shortcut.
759 // This is a mach-o specific directive and section.
761 Symbol->print(OS, MAI);
764 // Output align if we have it. We default to 1 so don't bother printing
766 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
771 static inline char toOctal(int X) { return (X&7)+'0'; }
773 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
776 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
777 unsigned char C = Data[i];
778 if (C == '"' || C == '\\') {
779 OS << '\\' << (char)C;
783 if (isprint((unsigned char)C)) {
789 case '\b': OS << "\\b"; break;
790 case '\f': OS << "\\f"; break;
791 case '\n': OS << "\\n"; break;
792 case '\r': OS << "\\r"; break;
793 case '\t': OS << "\\t"; break;
796 OS << toOctal(C >> 6);
797 OS << toOctal(C >> 3);
798 OS << toOctal(C >> 0);
806 void MCAsmStreamer::EmitBytes(StringRef Data) {
807 assert(getCurrentSectionOnly() &&
808 "Cannot emit contents before setting section!");
809 if (Data.empty()) return;
811 // If only single byte is provided or no ascii or asciz directives is
812 // supported, emit as vector of 8bits data.
813 if (Data.size() == 1 ||
814 !(MAI->getAscizDirective() || MAI->getAsciiDirective())) {
815 const char *Directive = MAI->getData8bitsDirective();
816 for (const unsigned char C : Data.bytes()) {
817 OS << Directive << (unsigned)C;
823 // If the data ends with 0 and the target supports .asciz, use it, otherwise
825 if (MAI->getAscizDirective() && Data.back() == 0) {
826 OS << MAI->getAscizDirective();
827 Data = Data.substr(0, Data.size()-1);
829 OS << MAI->getAsciiDirective();
832 PrintQuotedString(Data, OS);
836 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
837 // This is binary data. Print it in a grid of hex bytes for readability.
838 const size_t Cols = 4;
839 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
840 size_t J = I, EJ = std::min(I + Cols, Data.size());
842 OS << MAI->getData8bitsDirective();
843 for (; J < EJ - 1; ++J)
844 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
845 OS << format("0x%02x", uint8_t(Data[J]));
850 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
851 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
854 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
856 assert(Size <= 8 && "Invalid size");
857 assert(getCurrentSectionOnly() &&
858 "Cannot emit contents before setting section!");
859 const char *Directive = nullptr;
862 case 1: Directive = MAI->getData8bitsDirective(); break;
863 case 2: Directive = MAI->getData16bitsDirective(); break;
864 case 4: Directive = MAI->getData32bitsDirective(); break;
865 case 8: Directive = MAI->getData64bitsDirective(); break;
870 if (!Value->evaluateAsAbsolute(IntValue))
871 report_fatal_error("Don't know how to emit this value.");
873 // We couldn't handle the requested integer size so we fallback by breaking
874 // the request down into several, smaller, integers.
875 // Since sizes greater or equal to "Size" are invalid, we use the greatest
876 // power of 2 that is less than "Size" as our largest piece of granularity.
877 bool IsLittleEndian = MAI->isLittleEndian();
878 for (unsigned Emitted = 0; Emitted != Size;) {
879 unsigned Remaining = Size - Emitted;
880 // The size of our partial emission must be a power of two less than
882 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
883 // Calculate the byte offset of our partial emission taking into account
884 // the endianness of the target.
885 unsigned ByteOffset =
886 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
887 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
888 // We truncate our partial emission to fit within the bounds of the
889 // emission domain. This produces nicer output and silences potential
890 // truncation warnings when round tripping through another assembler.
891 uint64_t Shift = 64 - EmissionSize * 8;
892 assert(Shift < static_cast<uint64_t>(
893 std::numeric_limits<unsigned long long>::digits) &&
894 "undefined behavior");
895 ValueToEmit &= ~0ULL >> Shift;
896 EmitIntValue(ValueToEmit, EmissionSize);
897 Emitted += EmissionSize;
902 assert(Directive && "Invalid size for machine code value!");
904 if (MCTargetStreamer *TS = getTargetStreamer()) {
905 TS->emitValue(Value);
907 Value->print(OS, MAI);
912 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
914 if (Value->evaluateAsAbsolute(IntValue)) {
915 EmitULEB128IntValue(IntValue);
919 Value->print(OS, MAI);
923 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
925 if (Value->evaluateAsAbsolute(IntValue)) {
926 EmitSLEB128IntValue(IntValue);
930 Value->print(OS, MAI);
934 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
935 assert(MAI->getDTPRel64Directive() != nullptr);
936 OS << MAI->getDTPRel64Directive();
937 Value->print(OS, MAI);
941 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
942 assert(MAI->getDTPRel32Directive() != nullptr);
943 OS << MAI->getDTPRel32Directive();
944 Value->print(OS, MAI);
948 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
949 assert(MAI->getTPRel64Directive() != nullptr);
950 OS << MAI->getTPRel64Directive();
951 Value->print(OS, MAI);
955 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
956 assert(MAI->getTPRel32Directive() != nullptr);
957 OS << MAI->getTPRel32Directive();
958 Value->print(OS, MAI);
962 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
963 assert(MAI->getGPRel64Directive() != nullptr);
964 OS << MAI->getGPRel64Directive();
965 Value->print(OS, MAI);
969 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
970 assert(MAI->getGPRel32Directive() != nullptr);
971 OS << MAI->getGPRel32Directive();
972 Value->print(OS, MAI);
976 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
979 if (NumBytes.evaluateAsAbsolute(IntNumBytes) && IntNumBytes == 0)
982 if (const char *ZeroDirective = MAI->getZeroDirective()) {
983 // FIXME: Emit location directives
985 NumBytes.print(OS, MAI);
987 OS << ',' << (int)FillValue;
992 MCStreamer::emitFill(NumBytes, FillValue);
995 void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) {
999 const MCExpr *E = MCConstantExpr::create(NumValues, getContext());
1000 emitFill(*E, Size, Expr);
1003 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1004 int64_t Expr, SMLoc Loc) {
1005 // FIXME: Emit location directives
1007 NumValues.print(OS, MAI);
1008 OS << ", " << Size << ", 0x";
1009 OS.write_hex(truncateToSize(Expr, 4));
1013 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1015 unsigned MaxBytesToEmit) {
1016 // Some assemblers don't support non-power of two alignments, so we always
1017 // emit alignments as a power of two if possible.
1018 if (isPowerOf2_32(ByteAlignment)) {
1019 switch (ValueSize) {
1021 llvm_unreachable("Invalid size for machine code value!");
1023 OS << "\t.p2align\t";
1032 llvm_unreachable("Unsupported alignment size!");
1035 OS << Log2_32(ByteAlignment);
1037 if (Value || MaxBytesToEmit) {
1039 OS.write_hex(truncateToSize(Value, ValueSize));
1042 OS << ", " << MaxBytesToEmit;
1048 // Non-power of two alignment. This is not widely supported by assemblers.
1049 // FIXME: Parameterize this based on MAI.
1050 switch (ValueSize) {
1051 default: llvm_unreachable("Invalid size for machine code value!");
1052 case 1: OS << ".balign"; break;
1053 case 2: OS << ".balignw"; break;
1054 case 4: OS << ".balignl"; break;
1055 case 8: llvm_unreachable("Unsupported alignment size!");
1058 OS << ' ' << ByteAlignment;
1059 OS << ", " << truncateToSize(Value, ValueSize);
1061 OS << ", " << MaxBytesToEmit;
1065 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1066 unsigned MaxBytesToEmit) {
1067 // Emit with a text fill value.
1068 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1072 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1073 unsigned char Value,
1075 // FIXME: Verify that Offset is associated with the current section.
1077 Offset->print(OS, MAI);
1078 OS << ", " << (unsigned)Value;
1082 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1083 assert(MAI->hasSingleParameterDotFile());
1085 PrintQuotedString(Filename, OS);
1089 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
1090 StringRef Directory,
1095 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1096 unsigned NumFiles = Table.getMCDwarfFiles().size();
1097 FileNo = Table.getFile(Directory, Filename, FileNo);
1100 if (NumFiles == Table.getMCDwarfFiles().size())
1103 SmallString<128> FullPathName;
1105 if (!UseDwarfDirectory && !Directory.empty()) {
1106 if (sys::path::is_absolute(Filename))
1109 FullPathName = Directory;
1110 sys::path::append(FullPathName, Filename);
1112 Filename = FullPathName;
1116 SmallString<128> Str;
1117 raw_svector_ostream OS1(Str);
1118 OS1 << "\t.file\t" << FileNo << ' ';
1119 if (!Directory.empty()) {
1120 PrintQuotedString(Directory, OS1);
1123 PrintQuotedString(Filename, OS1);
1124 if (MCTargetStreamer *TS = getTargetStreamer()) {
1125 TS->emitDwarfFileDirective(OS1.str());
1127 EmitRawText(OS1.str());
1133 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1134 unsigned Column, unsigned Flags,
1136 unsigned Discriminator,
1137 StringRef FileName) {
1138 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1139 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1140 OS << " basic_block";
1141 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1142 OS << " prologue_end";
1143 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1144 OS << " epilogue_begin";
1146 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1147 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1150 if (Flags & DWARF2_FLAG_IS_STMT)
1157 OS << " isa " << Isa;
1159 OS << " discriminator " << Discriminator;
1162 OS.PadToColumn(MAI->getCommentColumn());
1163 OS << MAI->getCommentString() << ' ' << FileName << ':'
1164 << Line << ':' << Column;
1167 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1168 Isa, Discriminator, FileName);
1171 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1172 // Always use the zeroth line table, since asm syntax only supports one line
1174 return MCStreamer::getDwarfLineTableSymbol(0);
1177 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1178 ArrayRef<uint8_t> Checksum,
1179 unsigned ChecksumKind) {
1180 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1184 OS << "\t.cv_file\t" << FileNo << ' ';
1185 PrintQuotedString(Filename, OS);
1187 if (!ChecksumKind) {
1193 PrintQuotedString(toHex(Checksum), OS);
1194 OS << ' ' << ChecksumKind;
1200 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1201 OS << "\t.cv_func_id " << FuncId << '\n';
1202 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1205 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1208 unsigned IALine, unsigned IACol,
1210 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1211 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1212 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1213 IALine, IACol, Loc);
1216 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1217 unsigned Line, unsigned Column,
1218 bool PrologueEnd, bool IsStmt,
1219 StringRef FileName, SMLoc Loc) {
1220 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1223 OS << " prologue_end";
1225 unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt();
1226 if (IsStmt != OldIsStmt) {
1236 OS.PadToColumn(MAI->getCommentColumn());
1237 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1241 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
1242 PrologueEnd, IsStmt, FileName, Loc);
1245 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1246 const MCSymbol *FnStart,
1247 const MCSymbol *FnEnd) {
1248 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1249 FnStart->print(OS, MAI);
1251 FnEnd->print(OS, MAI);
1253 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1256 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1257 unsigned SourceFileId,
1258 unsigned SourceLineNum,
1259 const MCSymbol *FnStartSym,
1260 const MCSymbol *FnEndSym) {
1261 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1262 << ' ' << SourceLineNum << ' ';
1263 FnStartSym->print(OS, MAI);
1265 FnEndSym->print(OS, MAI);
1267 this->MCStreamer::EmitCVInlineLinetableDirective(
1268 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1271 void MCAsmStreamer::EmitCVDefRangeDirective(
1272 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1273 StringRef FixedSizePortion) {
1274 OS << "\t.cv_def_range\t";
1275 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1277 Range.first->print(OS, MAI);
1279 Range.second->print(OS, MAI);
1282 PrintQuotedString(FixedSizePortion, OS);
1284 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
1287 void MCAsmStreamer::EmitCVStringTableDirective() {
1288 OS << "\t.cv_stringtable";
1292 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1293 OS << "\t.cv_filechecksums";
1297 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1298 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1302 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1303 OS << "\t.cv_fpo_data\t";
1304 ProcSym->print(OS, MAI);
1308 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1309 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1311 PrintQuotedString(IdentString, OS);
1315 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1316 MCStreamer::EmitCFISections(EH, Debug);
1317 OS << "\t.cfi_sections ";
1321 OS << ", .debug_frame";
1323 OS << ".debug_frame";
1329 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1330 OS << "\t.cfi_startproc";
1336 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1337 MCStreamer::EmitCFIEndProcImpl(Frame);
1338 OS << "\t.cfi_endproc";
1342 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1343 if (!MAI->useDwarfRegNumForCFI()) {
1344 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1345 // just ones that map to LLVM register numbers and have known names.
1346 // Fall back to using the original number directly if no name is known.
1347 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1348 int LLVMRegister = MRI->getLLVMRegNumFromEH(Register);
1349 if (LLVMRegister != -1) {
1350 InstPrinter->printRegName(OS, LLVMRegister);
1357 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1358 MCStreamer::EmitCFIDefCfa(Register, Offset);
1359 OS << "\t.cfi_def_cfa ";
1360 EmitRegisterName(Register);
1361 OS << ", " << Offset;
1365 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1366 MCStreamer::EmitCFIDefCfaOffset(Offset);
1367 OS << "\t.cfi_def_cfa_offset " << Offset;
1371 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1372 OS << "\t.cfi_escape ";
1373 if (!Values.empty()) {
1374 size_t e = Values.size() - 1;
1375 for (size_t i = 0; i < e; ++i)
1376 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1377 OS << format("0x%02x", uint8_t(Values[e]));
1381 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1382 MCStreamer::EmitCFIEscape(Values);
1383 PrintCFIEscape(OS, Values);
1387 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1388 MCStreamer::EmitCFIGnuArgsSize(Size);
1390 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1391 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1393 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1397 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1398 MCStreamer::EmitCFIDefCfaRegister(Register);
1399 OS << "\t.cfi_def_cfa_register ";
1400 EmitRegisterName(Register);
1404 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1405 this->MCStreamer::EmitCFIOffset(Register, Offset);
1406 OS << "\t.cfi_offset ";
1407 EmitRegisterName(Register);
1408 OS << ", " << Offset;
1412 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1413 unsigned Encoding) {
1414 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1415 OS << "\t.cfi_personality " << Encoding << ", ";
1416 Sym->print(OS, MAI);
1420 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1421 MCStreamer::EmitCFILsda(Sym, Encoding);
1422 OS << "\t.cfi_lsda " << Encoding << ", ";
1423 Sym->print(OS, MAI);
1427 void MCAsmStreamer::EmitCFIRememberState() {
1428 MCStreamer::EmitCFIRememberState();
1429 OS << "\t.cfi_remember_state";
1433 void MCAsmStreamer::EmitCFIRestoreState() {
1434 MCStreamer::EmitCFIRestoreState();
1435 OS << "\t.cfi_restore_state";
1439 void MCAsmStreamer::EmitCFIRestore(int64_t Register) {
1440 MCStreamer::EmitCFIRestore(Register);
1441 OS << "\t.cfi_restore ";
1442 EmitRegisterName(Register);
1446 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1447 MCStreamer::EmitCFISameValue(Register);
1448 OS << "\t.cfi_same_value ";
1449 EmitRegisterName(Register);
1453 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1454 MCStreamer::EmitCFIRelOffset(Register, Offset);
1455 OS << "\t.cfi_rel_offset ";
1456 EmitRegisterName(Register);
1457 OS << ", " << Offset;
1461 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1462 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1463 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1467 void MCAsmStreamer::EmitCFISignalFrame() {
1468 MCStreamer::EmitCFISignalFrame();
1469 OS << "\t.cfi_signal_frame";
1473 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1474 MCStreamer::EmitCFIUndefined(Register);
1475 OS << "\t.cfi_undefined " << Register;
1479 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1480 MCStreamer::EmitCFIRegister(Register1, Register2);
1481 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1485 void MCAsmStreamer::EmitCFIWindowSave() {
1486 MCStreamer::EmitCFIWindowSave();
1487 OS << "\t.cfi_window_save";
1491 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1492 MCStreamer::EmitCFIReturnColumn(Register);
1493 OS << "\t.cfi_return_column " << Register;
1497 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1498 MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1501 Symbol->print(OS, MAI);
1505 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1506 MCStreamer::EmitWinCFIEndProc(Loc);
1508 OS << "\t.seh_endproc";
1512 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1513 MCStreamer::EmitWinCFIStartChained(Loc);
1515 OS << "\t.seh_startchained";
1519 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1520 MCStreamer::EmitWinCFIEndChained(Loc);
1522 OS << "\t.seh_endchained";
1526 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1527 bool Except, SMLoc Loc) {
1528 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1530 OS << "\t.seh_handler ";
1531 Sym->print(OS, MAI);
1539 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1540 MCStreamer::EmitWinEHHandlerData(Loc);
1542 // Switch sections. Don't call SwitchSection directly, because that will
1543 // cause the section switch to be visible in the emitted assembly.
1544 // We only do this so the section switch that terminates the handler
1545 // data block is visible.
1546 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1547 MCSection *TextSec = &CurFrame->Function->getSection();
1548 MCSection *XData = getAssociatedXDataSection(TextSec);
1549 SwitchSectionNoChange(XData);
1551 OS << "\t.seh_handlerdata";
1555 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) {
1556 MCStreamer::EmitWinCFIPushReg(Register, Loc);
1558 OS << "\t.seh_pushreg " << Register;
1562 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset,
1564 MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1566 OS << "\t.seh_setframe " << Register << ", " << Offset;
1570 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1571 MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1573 OS << "\t.seh_stackalloc " << Size;
1577 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset,
1579 MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1581 OS << "\t.seh_savereg " << Register << ", " << Offset;
1585 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
1587 MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1589 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1593 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1594 MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1596 OS << "\t.seh_pushframe";
1602 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1603 MCStreamer::EmitWinCFIEndProlog(Loc);
1605 OS << "\t.seh_endprologue";
1609 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1610 const MCSubtargetInfo &STI,
1611 bool PrintSchedInfo) {
1612 raw_ostream &OS = GetCommentOS();
1613 SmallString<256> Code;
1614 SmallVector<MCFixup, 4> Fixups;
1615 raw_svector_ostream VecOS(Code);
1616 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1618 // If we are showing fixups, create symbolic markers in the encoded
1619 // representation. We do this by making a per-bit map to the fixup item index,
1620 // then trying to display it as nicely as possible.
1621 SmallVector<uint8_t, 64> FixupMap;
1622 FixupMap.resize(Code.size() * 8);
1623 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1626 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1627 MCFixup &F = Fixups[i];
1628 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1629 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1630 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1631 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1632 FixupMap[Index] = 1 + i;
1636 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1637 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1638 OS << "encoding: [";
1639 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1643 // See if all bits are the same map entry.
1644 uint8_t MapEntry = FixupMap[i * 8 + 0];
1645 for (unsigned j = 1; j != 8; ++j) {
1646 if (FixupMap[i * 8 + j] == MapEntry)
1649 MapEntry = uint8_t(~0U);
1653 if (MapEntry != uint8_t(~0U)) {
1654 if (MapEntry == 0) {
1655 OS << format("0x%02x", uint8_t(Code[i]));
1658 // FIXME: Some of the 8 bits require fix up.
1659 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1660 << char('A' + MapEntry - 1) << '\'';
1662 OS << char('A' + MapEntry - 1);
1665 // Otherwise, write out in binary.
1667 for (unsigned j = 8; j--;) {
1668 unsigned Bit = (Code[i] >> j) & 1;
1671 if (MAI->isLittleEndian())
1672 FixupBit = i * 8 + j;
1674 FixupBit = i * 8 + (7-j);
1676 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1677 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1678 OS << char('A' + MapEntry - 1);
1685 // If we are not going to add fixup or schedule comments after this point
1686 // then we have to end the current comment line with "\n".
1687 if (Fixups.size() || !PrintSchedInfo)
1690 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1691 MCFixup &F = Fixups[i];
1692 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1693 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1694 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1698 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1699 const MCSubtargetInfo &STI,
1700 bool PrintSchedInfo) {
1701 assert(getCurrentSectionOnly() &&
1702 "Cannot emit contents before setting section!");
1704 // Show the encoding in a comment if we have a code emitter.
1706 AddEncodingComment(Inst, STI, PrintSchedInfo);
1708 // Show the MCInst if enabled.
1711 GetCommentOS() << "\n";
1712 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1713 GetCommentOS() << "\n";
1716 if(getTargetStreamer())
1717 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1719 InstPrinter->printInst(&Inst, OS, "", STI);
1721 if (PrintSchedInfo) {
1722 std::string SI = STI.getSchedInfoStr(Inst);
1724 GetCommentOS() << SI;
1727 StringRef Comments = CommentToEmit;
1728 if (Comments.size() && Comments.back() != '\n')
1729 GetCommentOS() << "\n";
1734 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1735 OS << "\t.bundle_align_mode " << AlignPow2;
1739 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1740 OS << "\t.bundle_lock";
1742 OS << " align_to_end";
1746 void MCAsmStreamer::EmitBundleUnlock() {
1747 OS << "\t.bundle_unlock";
1751 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1752 const MCExpr *Expr, SMLoc) {
1754 Offset.print(OS, MAI);
1758 Expr->print(OS, MAI);
1764 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1765 /// the specified string in the output .s file. This capability is
1766 /// indicated by the hasRawTextSupport() predicate.
1767 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1768 if (!String.empty() && String.back() == '\n')
1769 String = String.substr(0, String.size()-1);
1774 void MCAsmStreamer::FinishImpl() {
1775 // If we are generating dwarf for assembly source files dump out the sections.
1776 if (getContext().getGenDwarfForAssembly())
1777 MCGenDwarfInfo::Emit(this);
1779 // Emit the label for the line table, if requested - since the rest of the
1780 // line table will be defined by .loc/.file directives, and not emitted
1781 // directly, the label is the only work required here.
1782 auto &Tables = getContext().getMCDwarfLineTables();
1783 if (!Tables.empty()) {
1784 assert(Tables.size() == 1 && "asm output only supports one line table");
1785 if (auto *Label = Tables.begin()->second.getLabel()) {
1786 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1792 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1793 std::unique_ptr<formatted_raw_ostream> OS,
1794 bool isVerboseAsm, bool useDwarfDirectory,
1795 MCInstPrinter *IP, MCCodeEmitter *CE,
1796 MCAsmBackend *MAB, bool ShowInst) {
1797 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1798 useDwarfDirectory, IP, CE, MAB, ShowInst);