[ARM] Generate 8.1-m CSINC, CSNEG and CSINV instructions.
[llvm-core.git] / lib / MC / MCAsmStreamer.cpp
blobd2f99efef22abae78d6e4c2362c8b2709f57a8e8
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- 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 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/Optional.h"
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/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCCodeView.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCRegister.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include <cctype>
39 using namespace llvm;
41 namespace {
43 class MCAsmStreamer final : public MCStreamer {
44 std::unique_ptr<formatted_raw_ostream> OSOwner;
45 formatted_raw_ostream &OS;
46 const MCAsmInfo *MAI;
47 std::unique_ptr<MCInstPrinter> InstPrinter;
48 std::unique_ptr<MCAssembler> Assembler;
50 SmallString<128> ExplicitCommentToEmit;
51 SmallString<128> CommentToEmit;
52 raw_svector_ostream CommentStream;
53 raw_null_ostream NullStream;
55 unsigned IsVerboseAsm : 1;
56 unsigned ShowInst : 1;
57 unsigned UseDwarfDirectory : 1;
59 void EmitRegisterName(int64_t Register);
60 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
61 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
63 public:
64 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
65 bool isVerboseAsm, bool useDwarfDirectory,
66 MCInstPrinter *printer, std::unique_ptr<MCCodeEmitter> emitter,
67 std::unique_ptr<MCAsmBackend> asmbackend, bool showInst)
68 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
69 MAI(Context.getAsmInfo()), InstPrinter(printer),
70 Assembler(std::make_unique<MCAssembler>(
71 Context, std::move(asmbackend), std::move(emitter),
72 (asmbackend) ? asmbackend->createObjectWriter(NullStream)
73 : nullptr)),
74 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
75 ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
76 assert(InstPrinter);
77 if (IsVerboseAsm)
78 InstPrinter->setCommentStream(CommentStream);
81 MCAssembler &getAssembler() { return *Assembler; }
82 MCAssembler *getAssemblerPtr() override { return nullptr; }
84 inline void EmitEOL() {
85 // Dump Explicit Comments here.
86 emitExplicitComments();
87 // If we don't have any comments, just emit a \n.
88 if (!IsVerboseAsm) {
89 OS << '\n';
90 return;
92 EmitCommentsAndEOL();
95 void EmitSyntaxDirective() override;
97 void EmitCommentsAndEOL();
99 /// Return true if this streamer supports verbose assembly at all.
100 bool isVerboseAsm() const override { return IsVerboseAsm; }
102 /// Do we support EmitRawText?
103 bool hasRawTextSupport() const override { return true; }
105 /// Add a comment that can be emitted to the generated .s file to make the
106 /// output of the compiler more readable. This only affects the MCAsmStreamer
107 /// and only when verbose assembly output is enabled.
108 void AddComment(const Twine &T, bool EOL = true) override;
110 /// Add a comment showing the encoding of an instruction.
111 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
113 /// Return a raw_ostream that comments can be written to.
114 /// Unlike AddComment, you are required to terminate comments with \n if you
115 /// use this method.
116 raw_ostream &GetCommentOS() override {
117 if (!IsVerboseAsm)
118 return nulls(); // Discard comments unless in verbose asm mode.
119 return CommentStream;
122 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
124 void addExplicitComment(const Twine &T) override;
125 void emitExplicitComments() override;
127 /// Emit a blank line to a .s file to pretty it up.
128 void AddBlankLine() override {
129 EmitEOL();
132 /// @name MCStreamer Interface
133 /// @{
135 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
137 void emitELFSymverDirective(StringRef AliasName,
138 const MCSymbol *Aliasee) override;
140 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
141 void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
143 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
144 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
145 void EmitDataRegion(MCDataRegionType Kind) override;
146 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
147 unsigned Update, VersionTuple SDKVersion) override;
148 void EmitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
149 unsigned Update, VersionTuple SDKVersion) override;
150 void EmitThumbFunc(MCSymbol *Func) override;
152 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
153 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
154 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
156 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
157 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
158 void EmitCOFFSymbolStorageClass(int StorageClass) override;
159 void EmitCOFFSymbolType(int Type) override;
160 void EndCOFFSymbolDef() override;
161 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
162 void EmitCOFFSymbolIndex(MCSymbol const *Symbol) override;
163 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
164 void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
165 void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override;
166 void EmitXCOFFLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
167 unsigned ByteAlign) override;
168 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
169 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
170 unsigned ByteAlignment) override;
172 /// Emit a local common (.lcomm) symbol.
174 /// @param Symbol - The common symbol to emit.
175 /// @param Size - The size of the common symbol.
176 /// @param ByteAlignment - The alignment of the common symbol in bytes.
177 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
178 unsigned ByteAlignment) override;
180 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
181 uint64_t Size = 0, unsigned ByteAlignment = 0,
182 SMLoc Loc = SMLoc()) override;
184 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
185 unsigned ByteAlignment = 0) override;
187 void EmitBinaryData(StringRef Data) override;
189 void EmitBytes(StringRef Data) override;
191 void EmitValueImpl(const MCExpr *Value, unsigned Size,
192 SMLoc Loc = SMLoc()) override;
193 void EmitIntValue(uint64_t Value, unsigned Size) override;
194 void EmitIntValueInHex(uint64_t Value, unsigned Size) override;
196 void EmitULEB128Value(const MCExpr *Value) override;
198 void EmitSLEB128Value(const MCExpr *Value) override;
200 void EmitDTPRel32Value(const MCExpr *Value) override;
201 void EmitDTPRel64Value(const MCExpr *Value) override;
202 void EmitTPRel32Value(const MCExpr *Value) override;
203 void EmitTPRel64Value(const MCExpr *Value) override;
205 void EmitGPRel64Value(const MCExpr *Value) override;
207 void EmitGPRel32Value(const MCExpr *Value) override;
209 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
210 SMLoc Loc = SMLoc()) override;
212 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
213 SMLoc Loc = SMLoc()) override;
215 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
216 unsigned ValueSize = 1,
217 unsigned MaxBytesToEmit = 0) override;
219 void EmitCodeAlignment(unsigned ByteAlignment,
220 unsigned MaxBytesToEmit = 0) override;
222 void emitValueToOffset(const MCExpr *Offset,
223 unsigned char Value,
224 SMLoc Loc) override;
226 void EmitFileDirective(StringRef Filename) override;
227 Expected<unsigned> tryEmitDwarfFileDirective(unsigned FileNo,
228 StringRef Directory,
229 StringRef Filename,
230 Optional<MD5::MD5Result> Checksum = None,
231 Optional<StringRef> Source = None,
232 unsigned CUID = 0) override;
233 void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
234 Optional<MD5::MD5Result> Checksum,
235 Optional<StringRef> Source,
236 unsigned CUID = 0) override;
237 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
238 unsigned Column, unsigned Flags,
239 unsigned Isa, unsigned Discriminator,
240 StringRef FileName) override;
241 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
243 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
244 ArrayRef<uint8_t> Checksum,
245 unsigned ChecksumKind) override;
246 bool EmitCVFuncIdDirective(unsigned FuncId) override;
247 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
248 unsigned IAFile, unsigned IALine,
249 unsigned IACol, SMLoc Loc) override;
250 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
251 unsigned Column, bool PrologueEnd, bool IsStmt,
252 StringRef FileName, SMLoc Loc) override;
253 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
254 const MCSymbol *FnEnd) override;
255 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
256 unsigned SourceFileId,
257 unsigned SourceLineNum,
258 const MCSymbol *FnStartSym,
259 const MCSymbol *FnEndSym) override;
261 void PrintCVDefRangePrefix(
262 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
264 void EmitCVDefRangeDirective(
265 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
266 codeview::DefRangeRegisterRelSym::Header DRHdr) override;
268 void EmitCVDefRangeDirective(
269 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
270 codeview::DefRangeSubfieldRegisterSym::Header DRHdr) override;
272 void EmitCVDefRangeDirective(
273 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
274 codeview::DefRangeRegisterSym::Header DRHdr) override;
276 void EmitCVDefRangeDirective(
277 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
278 codeview::DefRangeFramePointerRelSym::Header DRHdr) override;
280 void EmitCVStringTableDirective() override;
281 void EmitCVFileChecksumsDirective() override;
282 void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override;
283 void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
285 void EmitIdent(StringRef IdentString) override;
286 void EmitCFIBKeyFrame() override;
287 void EmitCFISections(bool EH, bool Debug) override;
288 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
289 void EmitCFIDefCfaOffset(int64_t Offset) override;
290 void EmitCFIDefCfaRegister(int64_t Register) override;
291 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
292 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
293 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
294 void EmitCFIRememberState() override;
295 void EmitCFIRestoreState() override;
296 void EmitCFIRestore(int64_t Register) override;
297 void EmitCFISameValue(int64_t Register) override;
298 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
299 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
300 void EmitCFIEscape(StringRef Values) override;
301 void EmitCFIGnuArgsSize(int64_t Size) override;
302 void EmitCFISignalFrame() override;
303 void EmitCFIUndefined(int64_t Register) override;
304 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
305 void EmitCFIWindowSave() override;
306 void EmitCFINegateRAState() override;
307 void EmitCFIReturnColumn(int64_t Register) override;
309 void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
310 void EmitWinCFIEndProc(SMLoc Loc) override;
311 void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
312 void EmitWinCFIStartChained(SMLoc Loc) override;
313 void EmitWinCFIEndChained(SMLoc Loc) override;
314 void EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) override;
315 void EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
316 SMLoc Loc) override;
317 void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
318 void EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
319 SMLoc Loc) override;
320 void EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
321 SMLoc Loc) override;
322 void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
323 void EmitWinCFIEndProlog(SMLoc Loc) override;
325 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
326 SMLoc Loc) override;
327 void EmitWinEHHandlerData(SMLoc Loc) override;
329 void emitCGProfileEntry(const MCSymbolRefExpr *From,
330 const MCSymbolRefExpr *To, uint64_t Count) override;
332 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
334 void EmitBundleAlignMode(unsigned AlignPow2) override;
335 void EmitBundleLock(bool AlignToEnd) override;
336 void EmitBundleUnlock() override;
338 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
339 const MCExpr *Expr, SMLoc Loc,
340 const MCSubtargetInfo &STI) override;
342 void EmitAddrsig() override;
343 void EmitAddrsigSym(const MCSymbol *Sym) override;
345 /// If this file is backed by an assembly streamer, this dumps the specified
346 /// string in the output .s file. This capability is indicated by the
347 /// hasRawTextSupport() predicate.
348 void EmitRawTextImpl(StringRef String) override;
350 void FinishImpl() override;
353 } // end anonymous namespace.
355 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
356 if (!IsVerboseAsm) return;
358 T.toVector(CommentToEmit);
360 if (EOL)
361 CommentToEmit.push_back('\n'); // Place comment in a new line.
364 void MCAsmStreamer::EmitCommentsAndEOL() {
365 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
366 OS << '\n';
367 return;
370 StringRef Comments = CommentToEmit;
372 assert(Comments.back() == '\n' &&
373 "Comment array not newline terminated");
374 do {
375 // Emit a line of comments.
376 OS.PadToColumn(MAI->getCommentColumn());
377 size_t Position = Comments.find('\n');
378 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
380 Comments = Comments.substr(Position+1);
381 } while (!Comments.empty());
383 CommentToEmit.clear();
386 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
387 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
388 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
391 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
392 if (TabPrefix)
393 OS << '\t';
394 OS << MAI->getCommentString() << T;
395 EmitEOL();
398 void MCAsmStreamer::addExplicitComment(const Twine &T) {
399 StringRef c = T.getSingleStringRef();
400 if (c.equals(StringRef(MAI->getSeparatorString())))
401 return;
402 if (c.startswith(StringRef("//"))) {
403 ExplicitCommentToEmit.append("\t");
404 ExplicitCommentToEmit.append(MAI->getCommentString());
405 // drop //
406 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
407 } else if (c.startswith(StringRef("/*"))) {
408 size_t p = 2, len = c.size() - 2;
409 // emit each line in comment as separate newline.
410 do {
411 size_t newp = std::min(len, c.find_first_of("\r\n", p));
412 ExplicitCommentToEmit.append("\t");
413 ExplicitCommentToEmit.append(MAI->getCommentString());
414 ExplicitCommentToEmit.append(c.slice(p, newp).str());
415 // If we have another line in this comment add line
416 if (newp < len)
417 ExplicitCommentToEmit.append("\n");
418 p = newp + 1;
419 } while (p < len);
420 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
421 ExplicitCommentToEmit.append("\t");
422 ExplicitCommentToEmit.append(c.str());
423 } else if (c.front() == '#') {
425 ExplicitCommentToEmit.append("\t");
426 ExplicitCommentToEmit.append(MAI->getCommentString());
427 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
428 } else
429 assert(false && "Unexpected Assembly Comment");
430 // full line comments immediately output
431 if (c.back() == '\n')
432 emitExplicitComments();
435 void MCAsmStreamer::emitExplicitComments() {
436 StringRef Comments = ExplicitCommentToEmit;
437 if (!Comments.empty())
438 OS << Comments;
439 ExplicitCommentToEmit.clear();
442 void MCAsmStreamer::ChangeSection(MCSection *Section,
443 const MCExpr *Subsection) {
444 assert(Section && "Cannot switch to a null section!");
445 if (MCTargetStreamer *TS = getTargetStreamer()) {
446 TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
447 } else {
448 Section->PrintSwitchToSection(
449 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
450 Subsection);
454 void MCAsmStreamer::emitELFSymverDirective(StringRef AliasName,
455 const MCSymbol *Aliasee) {
456 OS << ".symver ";
457 Aliasee->print(OS, MAI);
458 OS << ", " << AliasName;
459 EmitEOL();
462 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
463 MCStreamer::EmitLabel(Symbol, Loc);
465 Symbol->print(OS, MAI);
466 OS << MAI->getLabelSuffix();
468 EmitEOL();
471 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
472 StringRef str = MCLOHIdToName(Kind);
474 #ifndef NDEBUG
475 int NbArgs = MCLOHIdToNbArgs(Kind);
476 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
477 assert(str != "" && "Invalid LOH name");
478 #endif
480 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
481 bool IsFirst = true;
482 for (const MCSymbol *Arg : Args) {
483 if (!IsFirst)
484 OS << ", ";
485 IsFirst = false;
486 Arg->print(OS, MAI);
488 EmitEOL();
491 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
492 switch (Flag) {
493 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
494 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
495 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
496 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
497 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
499 EmitEOL();
502 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
503 assert(!Options.empty() && "At least one option is required!");
504 OS << "\t.linker_option \"" << Options[0] << '"';
505 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
506 ie = Options.end(); it != ie; ++it) {
507 OS << ", " << '"' << *it << '"';
509 EmitEOL();
512 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
513 if (!MAI->doesSupportDataRegionDirectives())
514 return;
515 switch (Kind) {
516 case MCDR_DataRegion: OS << "\t.data_region"; break;
517 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
518 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
519 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
520 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
522 EmitEOL();
525 static const char *getVersionMinDirective(MCVersionMinType Type) {
526 switch (Type) {
527 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
528 case MCVM_TvOSVersionMin: return ".tvos_version_min";
529 case MCVM_IOSVersionMin: return ".ios_version_min";
530 case MCVM_OSXVersionMin: return ".macosx_version_min";
532 llvm_unreachable("Invalid MC version min type");
535 static void EmitSDKVersionSuffix(raw_ostream &OS,
536 const VersionTuple &SDKVersion) {
537 if (SDKVersion.empty())
538 return;
539 OS << '\t' << "sdk_version " << SDKVersion.getMajor();
540 if (auto Minor = SDKVersion.getMinor()) {
541 OS << ", " << *Minor;
542 if (auto Subminor = SDKVersion.getSubminor()) {
543 OS << ", " << *Subminor;
548 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major,
549 unsigned Minor, unsigned Update,
550 VersionTuple SDKVersion) {
551 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
552 if (Update)
553 OS << ", " << Update;
554 EmitSDKVersionSuffix(OS, SDKVersion);
555 EmitEOL();
558 static const char *getPlatformName(MachO::PlatformType Type) {
559 switch (Type) {
560 case MachO::PLATFORM_MACOS: return "macos";
561 case MachO::PLATFORM_IOS: return "ios";
562 case MachO::PLATFORM_TVOS: return "tvos";
563 case MachO::PLATFORM_WATCHOS: return "watchos";
564 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
565 case MachO::PLATFORM_MACCATALYST: return "macCatalyst";
566 case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator";
567 case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator";
568 case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
570 llvm_unreachable("Invalid Mach-O platform type");
573 void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major,
574 unsigned Minor, unsigned Update,
575 VersionTuple SDKVersion) {
576 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
577 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
578 if (Update)
579 OS << ", " << Update;
580 EmitSDKVersionSuffix(OS, SDKVersion);
581 EmitEOL();
584 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
585 // This needs to emit to a temporary string to get properly quoted
586 // MCSymbols when they have spaces in them.
587 OS << "\t.thumb_func";
588 // Only Mach-O hasSubsectionsViaSymbols()
589 if (MAI->hasSubsectionsViaSymbols()) {
590 OS << '\t';
591 Func->print(OS, MAI);
593 EmitEOL();
596 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
597 // Do not emit a .set on inlined target assignments.
598 bool EmitSet = true;
599 if (auto *E = dyn_cast<MCTargetExpr>(Value))
600 if (E->inlineAssignedExpr())
601 EmitSet = false;
602 if (EmitSet) {
603 OS << ".set ";
604 Symbol->print(OS, MAI);
605 OS << ", ";
606 Value->print(OS, MAI);
608 EmitEOL();
611 MCStreamer::EmitAssignment(Symbol, Value);
614 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
615 OS << ".weakref ";
616 Alias->print(OS, MAI);
617 OS << ", ";
618 Symbol->print(OS, MAI);
619 EmitEOL();
622 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
623 MCSymbolAttr Attribute) {
624 switch (Attribute) {
625 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
626 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
627 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
628 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
629 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
630 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
631 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
632 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
633 if (!MAI->hasDotTypeDotSizeDirective())
634 return false; // Symbol attribute not supported
635 OS << "\t.type\t";
636 Symbol->print(OS, MAI);
637 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
638 switch (Attribute) {
639 default: return false;
640 case MCSA_ELF_TypeFunction: OS << "function"; break;
641 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
642 case MCSA_ELF_TypeObject: OS << "object"; break;
643 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
644 case MCSA_ELF_TypeCommon: OS << "common"; break;
645 case MCSA_ELF_TypeNoType: OS << "notype"; break;
646 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
648 EmitEOL();
649 return true;
650 case MCSA_Global: // .globl/.global
651 OS << MAI->getGlobalDirective();
652 break;
653 case MCSA_Hidden: OS << "\t.hidden\t"; break;
654 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
655 case MCSA_Internal: OS << "\t.internal\t"; break;
656 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
657 case MCSA_Local: OS << "\t.local\t"; break;
658 case MCSA_NoDeadStrip:
659 if (!MAI->hasNoDeadStrip())
660 return false;
661 OS << "\t.no_dead_strip\t";
662 break;
663 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
664 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
665 case MCSA_PrivateExtern:
666 OS << "\t.private_extern\t";
667 break;
668 case MCSA_Protected: OS << "\t.protected\t"; break;
669 case MCSA_Reference: OS << "\t.reference\t"; break;
670 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
671 case MCSA_WeakDefinition:
672 OS << "\t.weak_definition\t";
673 break;
674 // .weak_reference
675 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
676 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
677 case MCSA_Cold:
678 // Assemblers currently do not support a .cold directive.
679 return false;
682 Symbol->print(OS, MAI);
683 EmitEOL();
685 return true;
688 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
689 OS << ".desc" << ' ';
690 Symbol->print(OS, MAI);
691 OS << ',' << DescValue;
692 EmitEOL();
695 void MCAsmStreamer::EmitSyntaxDirective() {
696 if (MAI->getAssemblerDialect() == 1) {
697 OS << "\t.intel_syntax noprefix";
698 EmitEOL();
700 // FIXME: Currently emit unprefix'ed registers.
701 // The intel_syntax directive has one optional argument
702 // with may have a value of prefix or noprefix.
705 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
706 OS << "\t.def\t ";
707 Symbol->print(OS, MAI);
708 OS << ';';
709 EmitEOL();
712 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
713 OS << "\t.scl\t" << StorageClass << ';';
714 EmitEOL();
717 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
718 OS << "\t.type\t" << Type << ';';
719 EmitEOL();
722 void MCAsmStreamer::EndCOFFSymbolDef() {
723 OS << "\t.endef";
724 EmitEOL();
727 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
728 OS << "\t.safeseh\t";
729 Symbol->print(OS, MAI);
730 EmitEOL();
733 void MCAsmStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
734 OS << "\t.symidx\t";
735 Symbol->print(OS, MAI);
736 EmitEOL();
739 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
740 OS << "\t.secidx\t";
741 Symbol->print(OS, MAI);
742 EmitEOL();
745 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
746 OS << "\t.secrel32\t";
747 Symbol->print(OS, MAI);
748 if (Offset != 0)
749 OS << '+' << Offset;
750 EmitEOL();
753 void MCAsmStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
754 OS << "\t.rva\t";
755 Symbol->print(OS, MAI);
756 if (Offset > 0)
757 OS << '+' << Offset;
758 else if (Offset < 0)
759 OS << '-' << -Offset;
760 EmitEOL();
763 // We need an XCOFF-specific version of this directive as the AIX syntax
764 // requires a QualName argument identifying the csect name and storage mapping
765 // class to appear before the alignment if we are specifying it.
766 void MCAsmStreamer::EmitXCOFFLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
767 unsigned ByteAlignment) {
768 assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
769 "We only support writing log base-2 alignment format with XCOFF.");
770 assert(isPowerOf2_32(ByteAlignment) && "Alignment must be a power of 2.");
772 OS << "\t.lcomm\t";
773 Symbol->print(OS, MAI);
774 OS << ',' << Size;
775 OS << ',' << Symbol->getName();
776 OS << ',' << Log2_32(ByteAlignment);
778 EmitEOL();
781 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
782 assert(MAI->hasDotTypeDotSizeDirective());
783 OS << "\t.size\t";
784 Symbol->print(OS, MAI);
785 OS << ", ";
786 Value->print(OS, MAI);
787 EmitEOL();
790 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
791 unsigned ByteAlignment) {
792 OS << "\t.comm\t";
793 Symbol->print(OS, MAI);
794 OS << ',' << Size;
796 if (ByteAlignment != 0) {
797 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
798 OS << ',' << ByteAlignment;
799 else
800 OS << ',' << Log2_32(ByteAlignment);
802 EmitEOL();
805 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
806 unsigned ByteAlign) {
807 OS << "\t.lcomm\t";
808 Symbol->print(OS, MAI);
809 OS << ',' << Size;
811 if (ByteAlign > 1) {
812 switch (MAI->getLCOMMDirectiveAlignmentType()) {
813 case LCOMM::NoAlignment:
814 llvm_unreachable("alignment not supported on .lcomm!");
815 case LCOMM::ByteAlignment:
816 OS << ',' << ByteAlign;
817 break;
818 case LCOMM::Log2Alignment:
819 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
820 OS << ',' << Log2_32(ByteAlign);
821 break;
824 EmitEOL();
827 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
828 uint64_t Size, unsigned ByteAlignment,
829 SMLoc Loc) {
830 if (Symbol)
831 AssignFragment(Symbol, &Section->getDummyFragment());
833 // Note: a .zerofill directive does not switch sections.
834 OS << ".zerofill ";
836 assert(Section->getVariant() == MCSection::SV_MachO &&
837 ".zerofill is a Mach-O specific directive");
838 // This is a mach-o specific directive.
840 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
841 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
843 if (Symbol) {
844 OS << ',';
845 Symbol->print(OS, MAI);
846 OS << ',' << Size;
847 if (ByteAlignment != 0)
848 OS << ',' << Log2_32(ByteAlignment);
850 EmitEOL();
853 // .tbss sym, size, align
854 // This depends that the symbol has already been mangled from the original,
855 // e.g. _a.
856 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
857 uint64_t Size, unsigned ByteAlignment) {
858 AssignFragment(Symbol, &Section->getDummyFragment());
860 assert(Symbol && "Symbol shouldn't be NULL!");
861 // Instead of using the Section we'll just use the shortcut.
863 assert(Section->getVariant() == MCSection::SV_MachO &&
864 ".zerofill is a Mach-O specific directive");
865 // This is a mach-o specific directive and section.
867 OS << ".tbss ";
868 Symbol->print(OS, MAI);
869 OS << ", " << Size;
871 // Output align if we have it. We default to 1 so don't bother printing
872 // that.
873 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
875 EmitEOL();
878 static inline char toOctal(int X) { return (X&7)+'0'; }
880 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
881 OS << '"';
883 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
884 unsigned char C = Data[i];
885 if (C == '"' || C == '\\') {
886 OS << '\\' << (char)C;
887 continue;
890 if (isPrint((unsigned char)C)) {
891 OS << (char)C;
892 continue;
895 switch (C) {
896 case '\b': OS << "\\b"; break;
897 case '\f': OS << "\\f"; break;
898 case '\n': OS << "\\n"; break;
899 case '\r': OS << "\\r"; break;
900 case '\t': OS << "\\t"; break;
901 default:
902 OS << '\\';
903 OS << toOctal(C >> 6);
904 OS << toOctal(C >> 3);
905 OS << toOctal(C >> 0);
906 break;
910 OS << '"';
913 void MCAsmStreamer::EmitBytes(StringRef Data) {
914 assert(getCurrentSectionOnly() &&
915 "Cannot emit contents before setting section!");
916 if (Data.empty()) return;
918 // If only single byte is provided or no ascii or asciz directives is
919 // supported, emit as vector of 8bits data.
920 if (Data.size() == 1 ||
921 !(MAI->getAscizDirective() || MAI->getAsciiDirective())) {
922 if (MCTargetStreamer *TS = getTargetStreamer()) {
923 TS->emitRawBytes(Data);
924 } else {
925 const char *Directive = MAI->getData8bitsDirective();
926 for (const unsigned char C : Data.bytes()) {
927 OS << Directive << (unsigned)C;
928 EmitEOL();
931 return;
934 // If the data ends with 0 and the target supports .asciz, use it, otherwise
935 // use .ascii
936 if (MAI->getAscizDirective() && Data.back() == 0) {
937 OS << MAI->getAscizDirective();
938 Data = Data.substr(0, Data.size()-1);
939 } else {
940 OS << MAI->getAsciiDirective();
943 PrintQuotedString(Data, OS);
944 EmitEOL();
947 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
948 // This is binary data. Print it in a grid of hex bytes for readability.
949 const size_t Cols = 4;
950 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
951 size_t J = I, EJ = std::min(I + Cols, Data.size());
952 assert(EJ > 0);
953 OS << MAI->getData8bitsDirective();
954 for (; J < EJ - 1; ++J)
955 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
956 OS << format("0x%02x", uint8_t(Data[J]));
957 EmitEOL();
961 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
962 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
965 void MCAsmStreamer::EmitIntValueInHex(uint64_t Value, unsigned Size) {
966 EmitValue(MCConstantExpr::create(Value, getContext(), true), Size);
969 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
970 SMLoc Loc) {
971 assert(Size <= 8 && "Invalid size");
972 assert(getCurrentSectionOnly() &&
973 "Cannot emit contents before setting section!");
974 const char *Directive = nullptr;
975 switch (Size) {
976 default: break;
977 case 1: Directive = MAI->getData8bitsDirective(); break;
978 case 2: Directive = MAI->getData16bitsDirective(); break;
979 case 4: Directive = MAI->getData32bitsDirective(); break;
980 case 8: Directive = MAI->getData64bitsDirective(); break;
983 if (!Directive) {
984 int64_t IntValue;
985 if (!Value->evaluateAsAbsolute(IntValue))
986 report_fatal_error("Don't know how to emit this value.");
988 // We couldn't handle the requested integer size so we fallback by breaking
989 // the request down into several, smaller, integers.
990 // Since sizes greater or equal to "Size" are invalid, we use the greatest
991 // power of 2 that is less than "Size" as our largest piece of granularity.
992 bool IsLittleEndian = MAI->isLittleEndian();
993 for (unsigned Emitted = 0; Emitted != Size;) {
994 unsigned Remaining = Size - Emitted;
995 // The size of our partial emission must be a power of two less than
996 // Size.
997 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
998 // Calculate the byte offset of our partial emission taking into account
999 // the endianness of the target.
1000 unsigned ByteOffset =
1001 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
1002 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
1003 // We truncate our partial emission to fit within the bounds of the
1004 // emission domain. This produces nicer output and silences potential
1005 // truncation warnings when round tripping through another assembler.
1006 uint64_t Shift = 64 - EmissionSize * 8;
1007 assert(Shift < static_cast<uint64_t>(
1008 std::numeric_limits<unsigned long long>::digits) &&
1009 "undefined behavior");
1010 ValueToEmit &= ~0ULL >> Shift;
1011 EmitIntValue(ValueToEmit, EmissionSize);
1012 Emitted += EmissionSize;
1014 return;
1017 assert(Directive && "Invalid size for machine code value!");
1018 OS << Directive;
1019 if (MCTargetStreamer *TS = getTargetStreamer()) {
1020 TS->emitValue(Value);
1021 } else {
1022 Value->print(OS, MAI);
1023 EmitEOL();
1027 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
1028 int64_t IntValue;
1029 if (Value->evaluateAsAbsolute(IntValue)) {
1030 EmitULEB128IntValue(IntValue);
1031 return;
1033 OS << "\t.uleb128 ";
1034 Value->print(OS, MAI);
1035 EmitEOL();
1038 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
1039 int64_t IntValue;
1040 if (Value->evaluateAsAbsolute(IntValue)) {
1041 EmitSLEB128IntValue(IntValue);
1042 return;
1044 OS << "\t.sleb128 ";
1045 Value->print(OS, MAI);
1046 EmitEOL();
1049 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
1050 assert(MAI->getDTPRel64Directive() != nullptr);
1051 OS << MAI->getDTPRel64Directive();
1052 Value->print(OS, MAI);
1053 EmitEOL();
1056 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
1057 assert(MAI->getDTPRel32Directive() != nullptr);
1058 OS << MAI->getDTPRel32Directive();
1059 Value->print(OS, MAI);
1060 EmitEOL();
1063 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
1064 assert(MAI->getTPRel64Directive() != nullptr);
1065 OS << MAI->getTPRel64Directive();
1066 Value->print(OS, MAI);
1067 EmitEOL();
1070 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
1071 assert(MAI->getTPRel32Directive() != nullptr);
1072 OS << MAI->getTPRel32Directive();
1073 Value->print(OS, MAI);
1074 EmitEOL();
1077 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
1078 assert(MAI->getGPRel64Directive() != nullptr);
1079 OS << MAI->getGPRel64Directive();
1080 Value->print(OS, MAI);
1081 EmitEOL();
1084 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
1085 assert(MAI->getGPRel32Directive() != nullptr);
1086 OS << MAI->getGPRel32Directive();
1087 Value->print(OS, MAI);
1088 EmitEOL();
1091 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
1092 SMLoc Loc) {
1093 int64_t IntNumBytes;
1094 if (NumBytes.evaluateAsAbsolute(IntNumBytes) && IntNumBytes == 0)
1095 return;
1097 if (const char *ZeroDirective = MAI->getZeroDirective()) {
1098 // FIXME: Emit location directives
1099 OS << ZeroDirective;
1100 NumBytes.print(OS, MAI);
1101 if (FillValue != 0)
1102 OS << ',' << (int)FillValue;
1103 EmitEOL();
1104 return;
1107 MCStreamer::emitFill(NumBytes, FillValue);
1110 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1111 int64_t Expr, SMLoc Loc) {
1112 // FIXME: Emit location directives
1113 OS << "\t.fill\t";
1114 NumValues.print(OS, MAI);
1115 OS << ", " << Size << ", 0x";
1116 OS.write_hex(truncateToSize(Expr, 4));
1117 EmitEOL();
1120 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1121 unsigned ValueSize,
1122 unsigned MaxBytesToEmit) {
1123 if (MAI->useDotAlignForAlignment()) {
1124 if (!isPowerOf2_32(ByteAlignment))
1125 report_fatal_error("Only power-of-two alignments are supported "
1126 "with .align.");
1127 OS << "\t.align\t";
1128 OS << Log2_32(ByteAlignment);
1129 EmitEOL();
1130 return;
1133 // Some assemblers don't support non-power of two alignments, so we always
1134 // emit alignments as a power of two if possible.
1135 if (isPowerOf2_32(ByteAlignment)) {
1136 switch (ValueSize) {
1137 default:
1138 llvm_unreachable("Invalid size for machine code value!");
1139 case 1:
1140 OS << "\t.p2align\t";
1141 break;
1142 case 2:
1143 OS << ".p2alignw ";
1144 break;
1145 case 4:
1146 OS << ".p2alignl ";
1147 break;
1148 case 8:
1149 llvm_unreachable("Unsupported alignment size!");
1152 OS << Log2_32(ByteAlignment);
1154 if (Value || MaxBytesToEmit) {
1155 OS << ", 0x";
1156 OS.write_hex(truncateToSize(Value, ValueSize));
1158 if (MaxBytesToEmit)
1159 OS << ", " << MaxBytesToEmit;
1161 EmitEOL();
1162 return;
1165 // Non-power of two alignment. This is not widely supported by assemblers.
1166 // FIXME: Parameterize this based on MAI.
1167 switch (ValueSize) {
1168 default: llvm_unreachable("Invalid size for machine code value!");
1169 case 1: OS << ".balign"; break;
1170 case 2: OS << ".balignw"; break;
1171 case 4: OS << ".balignl"; break;
1172 case 8: llvm_unreachable("Unsupported alignment size!");
1175 OS << ' ' << ByteAlignment;
1176 OS << ", " << truncateToSize(Value, ValueSize);
1177 if (MaxBytesToEmit)
1178 OS << ", " << MaxBytesToEmit;
1179 EmitEOL();
1182 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1183 unsigned MaxBytesToEmit) {
1184 // Emit with a text fill value.
1185 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1186 1, MaxBytesToEmit);
1189 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1190 unsigned char Value,
1191 SMLoc Loc) {
1192 // FIXME: Verify that Offset is associated with the current section.
1193 OS << ".org ";
1194 Offset->print(OS, MAI);
1195 OS << ", " << (unsigned)Value;
1196 EmitEOL();
1199 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1200 assert(MAI->hasSingleParameterDotFile());
1201 OS << "\t.file\t";
1202 PrintQuotedString(Filename, OS);
1203 EmitEOL();
1206 static void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
1207 StringRef Filename,
1208 Optional<MD5::MD5Result> Checksum,
1209 Optional<StringRef> Source,
1210 bool UseDwarfDirectory,
1211 raw_svector_ostream &OS) {
1212 SmallString<128> FullPathName;
1214 if (!UseDwarfDirectory && !Directory.empty()) {
1215 if (sys::path::is_absolute(Filename))
1216 Directory = "";
1217 else {
1218 FullPathName = Directory;
1219 sys::path::append(FullPathName, Filename);
1220 Directory = "";
1221 Filename = FullPathName;
1225 OS << "\t.file\t" << FileNo << ' ';
1226 if (!Directory.empty()) {
1227 PrintQuotedString(Directory, OS);
1228 OS << ' ';
1230 PrintQuotedString(Filename, OS);
1231 if (Checksum)
1232 OS << " md5 0x" << Checksum->digest();
1233 if (Source) {
1234 OS << " source ";
1235 PrintQuotedString(*Source, OS);
1239 Expected<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
1240 unsigned FileNo, StringRef Directory, StringRef Filename,
1241 Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source, unsigned CUID) {
1242 assert(CUID == 0 && "multiple CUs not supported by MCAsmStreamer");
1244 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1245 unsigned NumFiles = Table.getMCDwarfFiles().size();
1246 Expected<unsigned> FileNoOrErr =
1247 Table.tryGetFile(Directory, Filename, Checksum, Source,
1248 getContext().getDwarfVersion(), FileNo);
1249 if (!FileNoOrErr)
1250 return FileNoOrErr.takeError();
1251 FileNo = FileNoOrErr.get();
1252 if (NumFiles == Table.getMCDwarfFiles().size())
1253 return FileNo;
1255 SmallString<128> Str;
1256 raw_svector_ostream OS1(Str);
1257 printDwarfFileDirective(FileNo, Directory, Filename, Checksum, Source,
1258 UseDwarfDirectory, OS1);
1260 if (MCTargetStreamer *TS = getTargetStreamer())
1261 TS->emitDwarfFileDirective(OS1.str());
1262 else
1263 EmitRawText(OS1.str());
1265 return FileNo;
1268 void MCAsmStreamer::emitDwarfFile0Directive(StringRef Directory,
1269 StringRef Filename,
1270 Optional<MD5::MD5Result> Checksum,
1271 Optional<StringRef> Source,
1272 unsigned CUID) {
1273 assert(CUID == 0);
1274 // .file 0 is new for DWARF v5.
1275 if (getContext().getDwarfVersion() < 5)
1276 return;
1277 // Inform MCDwarf about the root file.
1278 getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
1279 Source);
1281 SmallString<128> Str;
1282 raw_svector_ostream OS1(Str);
1283 printDwarfFileDirective(0, Directory, Filename, Checksum, Source,
1284 UseDwarfDirectory, OS1);
1286 if (MCTargetStreamer *TS = getTargetStreamer())
1287 TS->emitDwarfFileDirective(OS1.str());
1288 else
1289 EmitRawText(OS1.str());
1292 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1293 unsigned Column, unsigned Flags,
1294 unsigned Isa,
1295 unsigned Discriminator,
1296 StringRef FileName) {
1297 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1298 if (MAI->supportsExtendedDwarfLocDirective()) {
1299 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1300 OS << " basic_block";
1301 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1302 OS << " prologue_end";
1303 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1304 OS << " epilogue_begin";
1306 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1307 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1308 OS << " is_stmt ";
1310 if (Flags & DWARF2_FLAG_IS_STMT)
1311 OS << "1";
1312 else
1313 OS << "0";
1316 if (Isa)
1317 OS << " isa " << Isa;
1318 if (Discriminator)
1319 OS << " discriminator " << Discriminator;
1322 if (IsVerboseAsm) {
1323 OS.PadToColumn(MAI->getCommentColumn());
1324 OS << MAI->getCommentString() << ' ' << FileName << ':'
1325 << Line << ':' << Column;
1327 EmitEOL();
1328 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1329 Isa, Discriminator, FileName);
1332 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1333 // Always use the zeroth line table, since asm syntax only supports one line
1334 // table for now.
1335 return MCStreamer::getDwarfLineTableSymbol(0);
1338 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1339 ArrayRef<uint8_t> Checksum,
1340 unsigned ChecksumKind) {
1341 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1342 ChecksumKind))
1343 return false;
1345 OS << "\t.cv_file\t" << FileNo << ' ';
1346 PrintQuotedString(Filename, OS);
1348 if (!ChecksumKind) {
1349 EmitEOL();
1350 return true;
1353 OS << ' ';
1354 PrintQuotedString(toHex(Checksum), OS);
1355 OS << ' ' << ChecksumKind;
1357 EmitEOL();
1358 return true;
1361 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1362 OS << "\t.cv_func_id " << FuncId << '\n';
1363 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1366 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1367 unsigned IAFunc,
1368 unsigned IAFile,
1369 unsigned IALine, unsigned IACol,
1370 SMLoc Loc) {
1371 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1372 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1373 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1374 IALine, IACol, Loc);
1377 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1378 unsigned Line, unsigned Column,
1379 bool PrologueEnd, bool IsStmt,
1380 StringRef FileName, SMLoc Loc) {
1381 // Validate the directive.
1382 if (!checkCVLocSection(FunctionId, FileNo, Loc))
1383 return;
1385 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1386 << Column;
1387 if (PrologueEnd)
1388 OS << " prologue_end";
1390 if (IsStmt)
1391 OS << " is_stmt 1";
1393 if (IsVerboseAsm) {
1394 OS.PadToColumn(MAI->getCommentColumn());
1395 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1396 << Column;
1398 EmitEOL();
1401 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1402 const MCSymbol *FnStart,
1403 const MCSymbol *FnEnd) {
1404 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1405 FnStart->print(OS, MAI);
1406 OS << ", ";
1407 FnEnd->print(OS, MAI);
1408 EmitEOL();
1409 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1412 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1413 unsigned SourceFileId,
1414 unsigned SourceLineNum,
1415 const MCSymbol *FnStartSym,
1416 const MCSymbol *FnEndSym) {
1417 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1418 << ' ' << SourceLineNum << ' ';
1419 FnStartSym->print(OS, MAI);
1420 OS << ' ';
1421 FnEndSym->print(OS, MAI);
1422 EmitEOL();
1423 this->MCStreamer::EmitCVInlineLinetableDirective(
1424 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1427 void MCAsmStreamer::PrintCVDefRangePrefix(
1428 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges) {
1429 OS << "\t.cv_def_range\t";
1430 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1431 OS << ' ';
1432 Range.first->print(OS, MAI);
1433 OS << ' ';
1434 Range.second->print(OS, MAI);
1438 void MCAsmStreamer::EmitCVDefRangeDirective(
1439 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1440 codeview::DefRangeRegisterRelSym::Header DRHdr) {
1441 PrintCVDefRangePrefix(Ranges);
1442 OS << ", reg_rel, ";
1443 OS << DRHdr.Register << ", " << DRHdr.Flags << ", "
1444 << DRHdr.BasePointerOffset;
1445 EmitEOL();
1448 void MCAsmStreamer::EmitCVDefRangeDirective(
1449 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1450 codeview::DefRangeSubfieldRegisterSym::Header DRHdr) {
1451 PrintCVDefRangePrefix(Ranges);
1452 OS << ", subfield_reg, ";
1453 OS << DRHdr.Register << ", " << DRHdr.OffsetInParent;
1454 EmitEOL();
1457 void MCAsmStreamer::EmitCVDefRangeDirective(
1458 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1459 codeview::DefRangeRegisterSym::Header DRHdr) {
1460 PrintCVDefRangePrefix(Ranges);
1461 OS << ", reg, ";
1462 OS << DRHdr.Register;
1463 EmitEOL();
1466 void MCAsmStreamer::EmitCVDefRangeDirective(
1467 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1468 codeview::DefRangeFramePointerRelSym::Header DRHdr) {
1469 PrintCVDefRangePrefix(Ranges);
1470 OS << ", frame_ptr_rel, ";
1471 OS << DRHdr.Offset;
1472 EmitEOL();
1475 void MCAsmStreamer::EmitCVStringTableDirective() {
1476 OS << "\t.cv_stringtable";
1477 EmitEOL();
1480 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1481 OS << "\t.cv_filechecksums";
1482 EmitEOL();
1485 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1486 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1487 EmitEOL();
1490 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1491 OS << "\t.cv_fpo_data\t";
1492 ProcSym->print(OS, MAI);
1493 EmitEOL();
1496 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1497 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1498 OS << "\t.ident\t";
1499 PrintQuotedString(IdentString, OS);
1500 EmitEOL();
1503 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1504 MCStreamer::EmitCFISections(EH, Debug);
1505 OS << "\t.cfi_sections ";
1506 if (EH) {
1507 OS << ".eh_frame";
1508 if (Debug)
1509 OS << ", .debug_frame";
1510 } else if (Debug) {
1511 OS << ".debug_frame";
1514 EmitEOL();
1517 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1518 OS << "\t.cfi_startproc";
1519 if (Frame.IsSimple)
1520 OS << " simple";
1521 EmitEOL();
1524 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1525 MCStreamer::EmitCFIEndProcImpl(Frame);
1526 OS << "\t.cfi_endproc";
1527 EmitEOL();
1530 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1531 if (!MAI->useDwarfRegNumForCFI()) {
1532 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1533 // just ones that map to LLVM register numbers and have known names.
1534 // Fall back to using the original number directly if no name is known.
1535 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1536 int LLVMRegister = MRI->getLLVMRegNumFromEH(Register);
1537 if (LLVMRegister != -1) {
1538 InstPrinter->printRegName(OS, LLVMRegister);
1539 return;
1542 OS << Register;
1545 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1546 MCStreamer::EmitCFIDefCfa(Register, Offset);
1547 OS << "\t.cfi_def_cfa ";
1548 EmitRegisterName(Register);
1549 OS << ", " << Offset;
1550 EmitEOL();
1553 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1554 MCStreamer::EmitCFIDefCfaOffset(Offset);
1555 OS << "\t.cfi_def_cfa_offset " << Offset;
1556 EmitEOL();
1559 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1560 OS << "\t.cfi_escape ";
1561 if (!Values.empty()) {
1562 size_t e = Values.size() - 1;
1563 for (size_t i = 0; i < e; ++i)
1564 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1565 OS << format("0x%02x", uint8_t(Values[e]));
1569 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1570 MCStreamer::EmitCFIEscape(Values);
1571 PrintCFIEscape(OS, Values);
1572 EmitEOL();
1575 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1576 MCStreamer::EmitCFIGnuArgsSize(Size);
1578 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1579 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1581 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1582 EmitEOL();
1585 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1586 MCStreamer::EmitCFIDefCfaRegister(Register);
1587 OS << "\t.cfi_def_cfa_register ";
1588 EmitRegisterName(Register);
1589 EmitEOL();
1592 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1593 this->MCStreamer::EmitCFIOffset(Register, Offset);
1594 OS << "\t.cfi_offset ";
1595 EmitRegisterName(Register);
1596 OS << ", " << Offset;
1597 EmitEOL();
1600 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1601 unsigned Encoding) {
1602 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1603 OS << "\t.cfi_personality " << Encoding << ", ";
1604 Sym->print(OS, MAI);
1605 EmitEOL();
1608 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1609 MCStreamer::EmitCFILsda(Sym, Encoding);
1610 OS << "\t.cfi_lsda " << Encoding << ", ";
1611 Sym->print(OS, MAI);
1612 EmitEOL();
1615 void MCAsmStreamer::EmitCFIRememberState() {
1616 MCStreamer::EmitCFIRememberState();
1617 OS << "\t.cfi_remember_state";
1618 EmitEOL();
1621 void MCAsmStreamer::EmitCFIRestoreState() {
1622 MCStreamer::EmitCFIRestoreState();
1623 OS << "\t.cfi_restore_state";
1624 EmitEOL();
1627 void MCAsmStreamer::EmitCFIRestore(int64_t Register) {
1628 MCStreamer::EmitCFIRestore(Register);
1629 OS << "\t.cfi_restore ";
1630 EmitRegisterName(Register);
1631 EmitEOL();
1634 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1635 MCStreamer::EmitCFISameValue(Register);
1636 OS << "\t.cfi_same_value ";
1637 EmitRegisterName(Register);
1638 EmitEOL();
1641 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1642 MCStreamer::EmitCFIRelOffset(Register, Offset);
1643 OS << "\t.cfi_rel_offset ";
1644 EmitRegisterName(Register);
1645 OS << ", " << Offset;
1646 EmitEOL();
1649 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1650 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1651 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1652 EmitEOL();
1655 void MCAsmStreamer::EmitCFISignalFrame() {
1656 MCStreamer::EmitCFISignalFrame();
1657 OS << "\t.cfi_signal_frame";
1658 EmitEOL();
1661 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1662 MCStreamer::EmitCFIUndefined(Register);
1663 OS << "\t.cfi_undefined " << Register;
1664 EmitEOL();
1667 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1668 MCStreamer::EmitCFIRegister(Register1, Register2);
1669 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1670 EmitEOL();
1673 void MCAsmStreamer::EmitCFIWindowSave() {
1674 MCStreamer::EmitCFIWindowSave();
1675 OS << "\t.cfi_window_save";
1676 EmitEOL();
1679 void MCAsmStreamer::EmitCFINegateRAState() {
1680 MCStreamer::EmitCFINegateRAState();
1681 OS << "\t.cfi_negate_ra_state";
1682 EmitEOL();
1685 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1686 MCStreamer::EmitCFIReturnColumn(Register);
1687 OS << "\t.cfi_return_column " << Register;
1688 EmitEOL();
1691 void MCAsmStreamer::EmitCFIBKeyFrame() {
1692 MCStreamer::EmitCFIBKeyFrame();
1693 OS << "\t.cfi_b_key_frame";
1694 EmitEOL();
1697 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1698 MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1700 OS << ".seh_proc ";
1701 Symbol->print(OS, MAI);
1702 EmitEOL();
1705 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1706 MCStreamer::EmitWinCFIEndProc(Loc);
1708 OS << "\t.seh_endproc";
1709 EmitEOL();
1712 // TODO: Implement
1713 void MCAsmStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
1716 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1717 MCStreamer::EmitWinCFIStartChained(Loc);
1719 OS << "\t.seh_startchained";
1720 EmitEOL();
1723 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1724 MCStreamer::EmitWinCFIEndChained(Loc);
1726 OS << "\t.seh_endchained";
1727 EmitEOL();
1730 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1731 bool Except, SMLoc Loc) {
1732 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1734 OS << "\t.seh_handler ";
1735 Sym->print(OS, MAI);
1736 if (Unwind)
1737 OS << ", @unwind";
1738 if (Except)
1739 OS << ", @except";
1740 EmitEOL();
1743 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1744 MCStreamer::EmitWinEHHandlerData(Loc);
1746 // Switch sections. Don't call SwitchSection directly, because that will
1747 // cause the section switch to be visible in the emitted assembly.
1748 // We only do this so the section switch that terminates the handler
1749 // data block is visible.
1750 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1752 // Do nothing if no frame is open. MCStreamer should've already reported an
1753 // error.
1754 if (!CurFrame)
1755 return;
1757 MCSection *TextSec = &CurFrame->Function->getSection();
1758 MCSection *XData = getAssociatedXDataSection(TextSec);
1759 SwitchSectionNoChange(XData);
1761 OS << "\t.seh_handlerdata";
1762 EmitEOL();
1765 void MCAsmStreamer::EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
1766 MCStreamer::EmitWinCFIPushReg(Register, Loc);
1768 OS << "\t.seh_pushreg ";
1769 InstPrinter->printRegName(OS, Register);
1770 EmitEOL();
1773 void MCAsmStreamer::EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
1774 SMLoc Loc) {
1775 MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1777 OS << "\t.seh_setframe ";
1778 InstPrinter->printRegName(OS, Register);
1779 OS << ", " << Offset;
1780 EmitEOL();
1783 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1784 MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1786 OS << "\t.seh_stackalloc " << Size;
1787 EmitEOL();
1790 void MCAsmStreamer::EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
1791 SMLoc Loc) {
1792 MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1794 OS << "\t.seh_savereg ";
1795 InstPrinter->printRegName(OS, Register);
1796 OS << ", " << Offset;
1797 EmitEOL();
1800 void MCAsmStreamer::EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
1801 SMLoc Loc) {
1802 MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1804 OS << "\t.seh_savexmm ";
1805 InstPrinter->printRegName(OS, Register);
1806 OS << ", " << Offset;
1807 EmitEOL();
1810 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1811 MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1813 OS << "\t.seh_pushframe";
1814 if (Code)
1815 OS << " @code";
1816 EmitEOL();
1819 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1820 MCStreamer::EmitWinCFIEndProlog(Loc);
1822 OS << "\t.seh_endprologue";
1823 EmitEOL();
1826 void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
1827 const MCSymbolRefExpr *To,
1828 uint64_t Count) {
1829 OS << "\t.cg_profile ";
1830 From->getSymbol().print(OS, MAI);
1831 OS << ", ";
1832 To->getSymbol().print(OS, MAI);
1833 OS << ", " << Count;
1834 EmitEOL();
1837 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1838 const MCSubtargetInfo &STI) {
1839 raw_ostream &OS = GetCommentOS();
1840 SmallString<256> Code;
1841 SmallVector<MCFixup, 4> Fixups;
1842 raw_svector_ostream VecOS(Code);
1844 // If we have no code emitter, don't emit code.
1845 if (!getAssembler().getEmitterPtr())
1846 return;
1848 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
1850 // If we are showing fixups, create symbolic markers in the encoded
1851 // representation. We do this by making a per-bit map to the fixup item index,
1852 // then trying to display it as nicely as possible.
1853 SmallVector<uint8_t, 64> FixupMap;
1854 FixupMap.resize(Code.size() * 8);
1855 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1856 FixupMap[i] = 0;
1858 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1859 MCFixup &F = Fixups[i];
1860 const MCFixupKindInfo &Info =
1861 getAssembler().getBackend().getFixupKindInfo(F.getKind());
1862 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1863 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1864 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1865 FixupMap[Index] = 1 + i;
1869 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1870 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1871 OS << "encoding: [";
1872 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1873 if (i)
1874 OS << ',';
1876 // See if all bits are the same map entry.
1877 uint8_t MapEntry = FixupMap[i * 8 + 0];
1878 for (unsigned j = 1; j != 8; ++j) {
1879 if (FixupMap[i * 8 + j] == MapEntry)
1880 continue;
1882 MapEntry = uint8_t(~0U);
1883 break;
1886 if (MapEntry != uint8_t(~0U)) {
1887 if (MapEntry == 0) {
1888 OS << format("0x%02x", uint8_t(Code[i]));
1889 } else {
1890 if (Code[i]) {
1891 // FIXME: Some of the 8 bits require fix up.
1892 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1893 << char('A' + MapEntry - 1) << '\'';
1894 } else
1895 OS << char('A' + MapEntry - 1);
1897 } else {
1898 // Otherwise, write out in binary.
1899 OS << "0b";
1900 for (unsigned j = 8; j--;) {
1901 unsigned Bit = (Code[i] >> j) & 1;
1903 unsigned FixupBit;
1904 if (MAI->isLittleEndian())
1905 FixupBit = i * 8 + j;
1906 else
1907 FixupBit = i * 8 + (7-j);
1909 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1910 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1911 OS << char('A' + MapEntry - 1);
1912 } else
1913 OS << Bit;
1917 OS << "]\n";
1919 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1920 MCFixup &F = Fixups[i];
1921 const MCFixupKindInfo &Info =
1922 getAssembler().getBackend().getFixupKindInfo(F.getKind());
1923 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1924 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1928 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1929 const MCSubtargetInfo &STI) {
1930 assert(getCurrentSectionOnly() &&
1931 "Cannot emit contents before setting section!");
1933 // Show the encoding in a comment if we have a code emitter.
1934 AddEncodingComment(Inst, STI);
1936 // Show the MCInst if enabled.
1937 if (ShowInst) {
1938 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1939 GetCommentOS() << "\n";
1942 if(getTargetStreamer())
1943 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1944 else
1945 InstPrinter->printInst(&Inst, OS, "", STI);
1947 StringRef Comments = CommentToEmit;
1948 if (Comments.size() && Comments.back() != '\n')
1949 GetCommentOS() << "\n";
1951 EmitEOL();
1954 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1955 OS << "\t.bundle_align_mode " << AlignPow2;
1956 EmitEOL();
1959 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1960 OS << "\t.bundle_lock";
1961 if (AlignToEnd)
1962 OS << " align_to_end";
1963 EmitEOL();
1966 void MCAsmStreamer::EmitBundleUnlock() {
1967 OS << "\t.bundle_unlock";
1968 EmitEOL();
1971 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1972 const MCExpr *Expr, SMLoc,
1973 const MCSubtargetInfo &STI) {
1974 OS << "\t.reloc ";
1975 Offset.print(OS, MAI);
1976 OS << ", " << Name;
1977 if (Expr) {
1978 OS << ", ";
1979 Expr->print(OS, MAI);
1981 EmitEOL();
1982 return false;
1985 void MCAsmStreamer::EmitAddrsig() {
1986 OS << "\t.addrsig";
1987 EmitEOL();
1990 void MCAsmStreamer::EmitAddrsigSym(const MCSymbol *Sym) {
1991 OS << "\t.addrsig_sym ";
1992 Sym->print(OS, MAI);
1993 EmitEOL();
1996 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1997 /// the specified string in the output .s file. This capability is
1998 /// indicated by the hasRawTextSupport() predicate.
1999 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
2000 if (!String.empty() && String.back() == '\n')
2001 String = String.substr(0, String.size()-1);
2002 OS << String;
2003 EmitEOL();
2006 void MCAsmStreamer::FinishImpl() {
2007 // If we are generating dwarf for assembly source files dump out the sections.
2008 if (getContext().getGenDwarfForAssembly())
2009 MCGenDwarfInfo::Emit(this);
2011 // Emit the label for the line table, if requested - since the rest of the
2012 // line table will be defined by .loc/.file directives, and not emitted
2013 // directly, the label is the only work required here.
2014 const auto &Tables = getContext().getMCDwarfLineTables();
2015 if (!Tables.empty()) {
2016 assert(Tables.size() == 1 && "asm output only supports one line table");
2017 if (auto *Label = Tables.begin()->second.getLabel()) {
2018 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
2019 EmitLabel(Label);
2024 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
2025 std::unique_ptr<formatted_raw_ostream> OS,
2026 bool isVerboseAsm, bool useDwarfDirectory,
2027 MCInstPrinter *IP,
2028 std::unique_ptr<MCCodeEmitter> &&CE,
2029 std::unique_ptr<MCAsmBackend> &&MAB,
2030 bool ShowInst) {
2031 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
2032 useDwarfDirectory, IP, std::move(CE), std::move(MAB),
2033 ShowInst);