forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMCAsmStreamer.cpp
2520 lines (2167 loc) · 83.1 KB
/
MCAsmStreamer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCCodeView.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCPseudoProbe.h"
#include "llvm/MC/MCRegister.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbolXCOFF.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include <cctype>
using namespace llvm;
namespace {
class MCAsmStreamer final : public MCStreamer {
std::unique_ptr<formatted_raw_ostream> OSOwner;
formatted_raw_ostream &OS;
const MCAsmInfo *MAI;
std::unique_ptr<MCInstPrinter> InstPrinter;
std::unique_ptr<MCAssembler> Assembler;
SmallString<128> ExplicitCommentToEmit;
SmallString<128> CommentToEmit;
raw_svector_ostream CommentStream;
raw_null_ostream NullStream;
unsigned IsVerboseAsm : 1;
unsigned ShowInst : 1;
unsigned UseDwarfDirectory : 1;
void EmitRegisterName(int64_t Register);
void PrintQuotedString(StringRef Data, raw_ostream &OS) const;
void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
StringRef Filename,
Optional<MD5::MD5Result> Checksum,
Optional<StringRef> Source,
bool UseDwarfDirectory,
raw_svector_ostream &OS) const;
void emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
void emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
public:
MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
bool isVerboseAsm, bool useDwarfDirectory,
MCInstPrinter *printer, std::unique_ptr<MCCodeEmitter> emitter,
std::unique_ptr<MCAsmBackend> asmbackend, bool showInst)
: MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
MAI(Context.getAsmInfo()), InstPrinter(printer),
Assembler(std::make_unique<MCAssembler>(
Context, std::move(asmbackend), std::move(emitter),
(asmbackend) ? asmbackend->createObjectWriter(NullStream)
: nullptr)),
CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
assert(InstPrinter);
if (IsVerboseAsm)
InstPrinter->setCommentStream(CommentStream);
if (Assembler->getBackendPtr())
setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
Context.setUseNamesOnTempLabels(true);
}
MCAssembler &getAssembler() { return *Assembler; }
MCAssembler *getAssemblerPtr() override { return nullptr; }
inline void EmitEOL() {
// Dump Explicit Comments here.
emitExplicitComments();
// If we don't have any comments, just emit a \n.
if (!IsVerboseAsm) {
OS << '\n';
return;
}
EmitCommentsAndEOL();
}
void emitSyntaxDirective() override;
void EmitCommentsAndEOL();
/// Return true if this streamer supports verbose assembly at all.
bool isVerboseAsm() const override { return IsVerboseAsm; }
/// Do we support EmitRawText?
bool hasRawTextSupport() const override { return true; }
/// Add a comment that can be emitted to the generated .s file to make the
/// output of the compiler more readable. This only affects the MCAsmStreamer
/// and only when verbose assembly output is enabled.
void AddComment(const Twine &T, bool EOL = true) override;
/// Add a comment showing the encoding of an instruction.
void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
/// Return a raw_ostream that comments can be written to.
/// Unlike AddComment, you are required to terminate comments with \n if you
/// use this method.
raw_ostream &GetCommentOS() override {
if (!IsVerboseAsm)
return nulls(); // Discard comments unless in verbose asm mode.
return CommentStream;
}
void emitRawComment(const Twine &T, bool TabPrefix = true) override;
void addExplicitComment(const Twine &T) override;
void emitExplicitComments() override;
/// Emit a blank line to a .s file to pretty it up.
void AddBlankLine() override {
EmitEOL();
}
/// @name MCStreamer Interface
/// @{
void changeSection(MCSection *Section, const MCExpr *Subsection) override;
void emitELFSymverDirective(const MCSymbol *OriginalSym, StringRef Name,
bool KeepOriginalSym) override;
void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
void emitGNUAttribute(unsigned Tag, unsigned Value) override;
StringRef getMnemonic(MCInst &MI) override {
return InstPrinter->getMnemonic(&MI).first;
}
void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
void emitAssemblerFlag(MCAssemblerFlag Flag) override;
void emitLinkerOptions(ArrayRef<std::string> Options) override;
void emitDataRegion(MCDataRegionType Kind) override;
void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
unsigned Update, VersionTuple SDKVersion) override;
void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
unsigned Update, VersionTuple SDKVersion) override;
void emitDarwinTargetVariantBuildVersion(unsigned Platform, unsigned Major,
unsigned Minor, unsigned Update,
VersionTuple SDKVersion) override;
void emitThumbFunc(MCSymbol *Func) override;
void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
void emitConditionalAssignment(MCSymbol *Symbol,
const MCExpr *Value) override;
void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
void EmitCOFFSymbolStorageClass(int StorageClass) override;
void EmitCOFFSymbolType(int Type) override;
void EndCOFFSymbolDef() override;
void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
void EmitCOFFSymbolIndex(MCSymbol const *Symbol) override;
void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override;
void emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
MCSymbol *CsectSym,
unsigned ByteAlign) override;
void emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
MCSymbolAttr Linakge,
MCSymbolAttr Visibility) override;
void emitXCOFFRenameDirective(const MCSymbol *Name,
StringRef Rename) override;
void emitXCOFFRefDirective(StringRef Name) override;
void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
/// Emit a local common (.lcomm) symbol.
///
/// @param Symbol - The common symbol to emit.
/// @param Size - The size of the common symbol.
/// @param ByteAlignment - The alignment of the common symbol in bytes.
void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
uint64_t Size = 0, unsigned ByteAlignment = 0,
SMLoc Loc = SMLoc()) override;
void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment = 0) override;
void emitBinaryData(StringRef Data) override;
void emitBytes(StringRef Data) override;
void emitValueImpl(const MCExpr *Value, unsigned Size,
SMLoc Loc = SMLoc()) override;
void emitIntValue(uint64_t Value, unsigned Size) override;
void emitIntValueInHex(uint64_t Value, unsigned Size) override;
void emitIntValueInHexWithPadding(uint64_t Value, unsigned Size) override;
void emitULEB128Value(const MCExpr *Value) override;
void emitSLEB128Value(const MCExpr *Value) override;
void emitDTPRel32Value(const MCExpr *Value) override;
void emitDTPRel64Value(const MCExpr *Value) override;
void emitTPRel32Value(const MCExpr *Value) override;
void emitTPRel64Value(const MCExpr *Value) override;
void emitGPRel64Value(const MCExpr *Value) override;
void emitGPRel32Value(const MCExpr *Value) override;
void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
SMLoc Loc = SMLoc()) override;
void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
SMLoc Loc = SMLoc()) override;
void emitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
unsigned ValueSize = 1,
unsigned MaxBytesToEmit = 0) override;
void emitCodeAlignment(unsigned ByteAlignment, const MCSubtargetInfo *STI,
unsigned MaxBytesToEmit = 0) override;
void emitValueToOffset(const MCExpr *Offset,
unsigned char Value,
SMLoc Loc) override;
void emitFileDirective(StringRef Filename) override;
void emitFileDirective(StringRef Filename, StringRef CompilerVerion,
StringRef TimeStamp, StringRef Description) override;
Expected<unsigned> tryEmitDwarfFileDirective(unsigned FileNo,
StringRef Directory,
StringRef Filename,
Optional<MD5::MD5Result> Checksum = None,
Optional<StringRef> Source = None,
unsigned CUID = 0) override;
void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
Optional<MD5::MD5Result> Checksum,
Optional<StringRef> Source,
unsigned CUID = 0) override;
void emitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column,
unsigned Flags, unsigned Isa,
unsigned Discriminator,
StringRef FileName) override;
MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
ArrayRef<uint8_t> Checksum,
unsigned ChecksumKind) override;
bool EmitCVFuncIdDirective(unsigned FuncId) override;
bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
unsigned IAFile, unsigned IALine,
unsigned IACol, SMLoc Loc) override;
void emitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
unsigned Column, bool PrologueEnd, bool IsStmt,
StringRef FileName, SMLoc Loc) override;
void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
const MCSymbol *FnEnd) override;
void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
unsigned SourceFileId,
unsigned SourceLineNum,
const MCSymbol *FnStartSym,
const MCSymbol *FnEndSym) override;
void PrintCVDefRangePrefix(
ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
void emitCVDefRangeDirective(
ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
codeview::DefRangeRegisterRelHeader DRHdr) override;
void emitCVDefRangeDirective(
ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
codeview::DefRangeSubfieldRegisterHeader DRHdr) override;
void emitCVDefRangeDirective(
ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
codeview::DefRangeRegisterHeader DRHdr) override;
void emitCVDefRangeDirective(
ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
codeview::DefRangeFramePointerRelHeader DRHdr) override;
void emitCVStringTableDirective() override;
void emitCVFileChecksumsDirective() override;
void emitCVFileChecksumOffsetDirective(unsigned FileNo) override;
void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
void emitIdent(StringRef IdentString) override;
void emitCFIBKeyFrame() override;
void emitCFISections(bool EH, bool Debug) override;
void emitCFIDefCfa(int64_t Register, int64_t Offset) override;
void emitCFIDefCfaOffset(int64_t Offset) override;
void emitCFIDefCfaRegister(int64_t Register) override;
void emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
int64_t AddressSpace) override;
void emitCFIOffset(int64_t Register, int64_t Offset) override;
void emitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
void emitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
void emitCFIRememberState() override;
void emitCFIRestoreState() override;
void emitCFIRestore(int64_t Register) override;
void emitCFISameValue(int64_t Register) override;
void emitCFIRelOffset(int64_t Register, int64_t Offset) override;
void emitCFIAdjustCfaOffset(int64_t Adjustment) override;
void emitCFIEscape(StringRef Values) override;
void emitCFIGnuArgsSize(int64_t Size) override;
void emitCFISignalFrame() override;
void emitCFIUndefined(int64_t Register) override;
void emitCFIRegister(int64_t Register1, int64_t Register2) override;
void emitCFIWindowSave() override;
void emitCFINegateRAState() override;
void emitCFIReturnColumn(int64_t Register) override;
void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
void EmitWinCFIEndProc(SMLoc Loc) override;
void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
void EmitWinCFIStartChained(SMLoc Loc) override;
void EmitWinCFIEndChained(SMLoc Loc) override;
void EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) override;
void EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
SMLoc Loc) override;
void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
void EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
SMLoc Loc) override;
void EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
SMLoc Loc) override;
void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
void EmitWinCFIEndProlog(SMLoc Loc) override;
void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
SMLoc Loc) override;
void EmitWinEHHandlerData(SMLoc Loc) override;
void emitCGProfileEntry(const MCSymbolRefExpr *From,
const MCSymbolRefExpr *To, uint64_t Count) override;
void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
void emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
uint64_t Attr,
const MCPseudoProbeInlineStack &InlineStack) override;
void emitBundleAlignMode(unsigned AlignPow2) override;
void emitBundleLock(bool AlignToEnd) override;
void emitBundleUnlock() override;
Optional<std::pair<bool, std::string>>
emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr,
SMLoc Loc, const MCSubtargetInfo &STI) override;
void emitAddrsig() override;
void emitAddrsigSym(const MCSymbol *Sym) override;
/// If this file is backed by an assembly streamer, this dumps the specified
/// string in the output .s file. This capability is indicated by the
/// hasRawTextSupport() predicate.
void emitRawTextImpl(StringRef String) override;
void finishImpl() override;
void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) override;
MCSymbol *emitDwarfUnitLength(const Twine &Prefix,
const Twine &Comment) override;
void emitDwarfLineStartLabel(MCSymbol *StartSym) override;
void emitDwarfLineEndEntry(MCSection *Section, MCSymbol *LastLabel) override;
void emitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
const MCSymbol *Label,
unsigned PointerSize) override;
void doFinalizationAtSectionEnd(MCSection *Section) override;
};
} // end anonymous namespace.
void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
if (!IsVerboseAsm) return;
T.toVector(CommentToEmit);
if (EOL)
CommentToEmit.push_back('\n'); // Place comment in a new line.
}
void MCAsmStreamer::EmitCommentsAndEOL() {
if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
OS << '\n';
return;
}
StringRef Comments = CommentToEmit;
assert(Comments.back() == '\n' &&
"Comment array not newline terminated");
do {
// Emit a line of comments.
OS.PadToColumn(MAI->getCommentColumn());
size_t Position = Comments.find('\n');
OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
Comments = Comments.substr(Position+1);
} while (!Comments.empty());
CommentToEmit.clear();
}
static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
}
void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
if (TabPrefix)
OS << '\t';
OS << MAI->getCommentString() << T;
EmitEOL();
}
void MCAsmStreamer::addExplicitComment(const Twine &T) {
StringRef c = T.getSingleStringRef();
if (c.equals(StringRef(MAI->getSeparatorString())))
return;
if (c.startswith(StringRef("//"))) {
ExplicitCommentToEmit.append("\t");
ExplicitCommentToEmit.append(MAI->getCommentString());
// drop //
ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
} else if (c.startswith(StringRef("/*"))) {
size_t p = 2, len = c.size() - 2;
// emit each line in comment as separate newline.
do {
size_t newp = std::min(len, c.find_first_of("\r\n", p));
ExplicitCommentToEmit.append("\t");
ExplicitCommentToEmit.append(MAI->getCommentString());
ExplicitCommentToEmit.append(c.slice(p, newp).str());
// If we have another line in this comment add line
if (newp < len)
ExplicitCommentToEmit.append("\n");
p = newp + 1;
} while (p < len);
} else if (c.startswith(StringRef(MAI->getCommentString()))) {
ExplicitCommentToEmit.append("\t");
ExplicitCommentToEmit.append(c.str());
} else if (c.front() == '#') {
ExplicitCommentToEmit.append("\t");
ExplicitCommentToEmit.append(MAI->getCommentString());
ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
} else
assert(false && "Unexpected Assembly Comment");
// full line comments immediately output
if (c.back() == '\n')
emitExplicitComments();
}
void MCAsmStreamer::emitExplicitComments() {
StringRef Comments = ExplicitCommentToEmit;
if (!Comments.empty())
OS << Comments;
ExplicitCommentToEmit.clear();
}
void MCAsmStreamer::changeSection(MCSection *Section,
const MCExpr *Subsection) {
assert(Section && "Cannot switch to a null section!");
if (MCTargetStreamer *TS = getTargetStreamer()) {
TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
} else {
Section->PrintSwitchToSection(*MAI, getContext().getTargetTriple(), OS,
Subsection);
}
}
void MCAsmStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
StringRef Name,
bool KeepOriginalSym) {
OS << ".symver ";
OriginalSym->print(OS, MAI);
OS << ", " << Name;
if (!KeepOriginalSym && !Name.contains("@@@"))
OS << ", remove";
EmitEOL();
}
void MCAsmStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
MCStreamer::emitLabel(Symbol, Loc);
Symbol->print(OS, MAI);
OS << MAI->getLabelSuffix();
EmitEOL();
}
void MCAsmStreamer::emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
StringRef str = MCLOHIdToName(Kind);
#ifndef NDEBUG
int NbArgs = MCLOHIdToNbArgs(Kind);
assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
assert(str != "" && "Invalid LOH name");
#endif
OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
bool IsFirst = true;
for (const MCSymbol *Arg : Args) {
if (!IsFirst)
OS << ", ";
IsFirst = false;
Arg->print(OS, MAI);
}
EmitEOL();
}
void MCAsmStreamer::emitGNUAttribute(unsigned Tag, unsigned Value) {
OS << "\t.gnu_attribute " << Tag << ", " << Value << "\n";
}
void MCAsmStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
switch (Flag) {
case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
}
EmitEOL();
}
void MCAsmStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
assert(!Options.empty() && "At least one option is required!");
OS << "\t.linker_option \"" << Options[0] << '"';
for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
ie = Options.end(); it != ie; ++it) {
OS << ", " << '"' << *it << '"';
}
EmitEOL();
}
void MCAsmStreamer::emitDataRegion(MCDataRegionType Kind) {
if (!MAI->doesSupportDataRegionDirectives())
return;
switch (Kind) {
case MCDR_DataRegion: OS << "\t.data_region"; break;
case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
}
EmitEOL();
}
static const char *getVersionMinDirective(MCVersionMinType Type) {
switch (Type) {
case MCVM_WatchOSVersionMin: return ".watchos_version_min";
case MCVM_TvOSVersionMin: return ".tvos_version_min";
case MCVM_IOSVersionMin: return ".ios_version_min";
case MCVM_OSXVersionMin: return ".macosx_version_min";
}
llvm_unreachable("Invalid MC version min type");
}
static void EmitSDKVersionSuffix(raw_ostream &OS,
const VersionTuple &SDKVersion) {
if (SDKVersion.empty())
return;
OS << '\t' << "sdk_version " << SDKVersion.getMajor();
if (auto Minor = SDKVersion.getMinor()) {
OS << ", " << *Minor;
if (auto Subminor = SDKVersion.getSubminor()) {
OS << ", " << *Subminor;
}
}
}
void MCAsmStreamer::emitVersionMin(MCVersionMinType Type, unsigned Major,
unsigned Minor, unsigned Update,
VersionTuple SDKVersion) {
OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
if (Update)
OS << ", " << Update;
EmitSDKVersionSuffix(OS, SDKVersion);
EmitEOL();
}
static const char *getPlatformName(MachO::PlatformType Type) {
switch (Type) {
case MachO::PLATFORM_UNKNOWN: /* silence warning*/
break;
case MachO::PLATFORM_MACOS: return "macos";
case MachO::PLATFORM_IOS: return "ios";
case MachO::PLATFORM_TVOS: return "tvos";
case MachO::PLATFORM_WATCHOS: return "watchos";
case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
case MachO::PLATFORM_MACCATALYST: return "macCatalyst";
case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator";
case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator";
case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
case MachO::PLATFORM_DRIVERKIT: return "driverkit";
}
llvm_unreachable("Invalid Mach-O platform type");
}
void MCAsmStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
unsigned Minor, unsigned Update,
VersionTuple SDKVersion) {
const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
if (Update)
OS << ", " << Update;
EmitSDKVersionSuffix(OS, SDKVersion);
EmitEOL();
}
void MCAsmStreamer::emitDarwinTargetVariantBuildVersion(
unsigned Platform, unsigned Major, unsigned Minor, unsigned Update,
VersionTuple SDKVersion) {
emitBuildVersion(Platform, Major, Minor, Update, SDKVersion);
}
void MCAsmStreamer::emitThumbFunc(MCSymbol *Func) {
// This needs to emit to a temporary string to get properly quoted
// MCSymbols when they have spaces in them.
OS << "\t.thumb_func";
// Only Mach-O hasSubsectionsViaSymbols()
if (MAI->hasSubsectionsViaSymbols()) {
OS << '\t';
Func->print(OS, MAI);
}
EmitEOL();
}
void MCAsmStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
// Do not emit a .set on inlined target assignments.
bool EmitSet = true;
if (auto *E = dyn_cast<MCTargetExpr>(Value))
if (E->inlineAssignedExpr())
EmitSet = false;
if (EmitSet) {
OS << ".set ";
Symbol->print(OS, MAI);
OS << ", ";
Value->print(OS, MAI);
EmitEOL();
}
MCStreamer::emitAssignment(Symbol, Value);
}
void MCAsmStreamer::emitConditionalAssignment(MCSymbol *Symbol,
const MCExpr *Value) {
OS << ".lto_set_conditional ";
Symbol->print(OS, MAI);
OS << ", ";
Value->print(OS, MAI);
EmitEOL();
}
void MCAsmStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
OS << ".weakref ";
Alias->print(OS, MAI);
OS << ", ";
Symbol->print(OS, MAI);
EmitEOL();
}
bool MCAsmStreamer::emitSymbolAttribute(MCSymbol *Symbol,
MCSymbolAttr Attribute) {
switch (Attribute) {
case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
if (!MAI->hasDotTypeDotSizeDirective())
return false; // Symbol attribute not supported
OS << "\t.type\t";
Symbol->print(OS, MAI);
OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
switch (Attribute) {
default: return false;
case MCSA_ELF_TypeFunction: OS << "function"; break;
case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
case MCSA_ELF_TypeObject: OS << "object"; break;
case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
case MCSA_ELF_TypeCommon: OS << "common"; break;
case MCSA_ELF_TypeNoType: OS << "notype"; break;
case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
}
EmitEOL();
return true;
case MCSA_Global: // .globl/.global
OS << MAI->getGlobalDirective();
break;
case MCSA_LGlobal: OS << "\t.lglobl\t"; break;
case MCSA_Hidden: OS << "\t.hidden\t"; break;
case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
case MCSA_Internal: OS << "\t.internal\t"; break;
case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
case MCSA_Local: OS << "\t.local\t"; break;
case MCSA_NoDeadStrip:
if (!MAI->hasNoDeadStrip())
return false;
OS << "\t.no_dead_strip\t";
break;
case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
case MCSA_PrivateExtern:
OS << "\t.private_extern\t";
break;
case MCSA_Protected: OS << "\t.protected\t"; break;
case MCSA_Reference: OS << "\t.reference\t"; break;
case MCSA_Extern:
OS << "\t.extern\t";
break;
case MCSA_Weak: OS << MAI->getWeakDirective(); break;
case MCSA_WeakDefinition:
OS << "\t.weak_definition\t";
break;
// .weak_reference
case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
case MCSA_Cold:
// Assemblers currently do not support a .cold directive.
return false;
}
Symbol->print(OS, MAI);
EmitEOL();
return true;
}
void MCAsmStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
OS << ".desc" << ' ';
Symbol->print(OS, MAI);
OS << ',' << DescValue;
EmitEOL();
}
void MCAsmStreamer::emitSyntaxDirective() {
if (MAI->getAssemblerDialect() == 1) {
OS << "\t.intel_syntax noprefix";
EmitEOL();
}
// FIXME: Currently emit unprefix'ed registers.
// The intel_syntax directive has one optional argument
// with may have a value of prefix or noprefix.
}
void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
OS << "\t.def\t";
Symbol->print(OS, MAI);
OS << ';';
EmitEOL();
}
void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
OS << "\t.scl\t" << StorageClass << ';';
EmitEOL();
}
void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
OS << "\t.type\t" << Type << ';';
EmitEOL();
}
void MCAsmStreamer::EndCOFFSymbolDef() {
OS << "\t.endef";
EmitEOL();
}
void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
OS << "\t.safeseh\t";
Symbol->print(OS, MAI);
EmitEOL();
}
void MCAsmStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
OS << "\t.symidx\t";
Symbol->print(OS, MAI);
EmitEOL();
}
void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
OS << "\t.secidx\t";
Symbol->print(OS, MAI);
EmitEOL();
}
void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
OS << "\t.secrel32\t";
Symbol->print(OS, MAI);
if (Offset != 0)
OS << '+' << Offset;
EmitEOL();
}
void MCAsmStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
OS << "\t.rva\t";
Symbol->print(OS, MAI);
if (Offset > 0)
OS << '+' << Offset;
else if (Offset < 0)
OS << '-' << -Offset;
EmitEOL();
}
// We need an XCOFF-specific version of this directive as the AIX syntax
// requires a QualName argument identifying the csect name and storage mapping
// class to appear before the alignment if we are specifying it.
void MCAsmStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym,
uint64_t Size,
MCSymbol *CsectSym,
unsigned ByteAlignment) {
assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
"We only support writing log base-2 alignment format with XCOFF.");
assert(isPowerOf2_32(ByteAlignment) && "Alignment must be a power of 2.");
OS << "\t.lcomm\t";
LabelSym->print(OS, MAI);
OS << ',' << Size << ',';
CsectSym->print(OS, MAI);
OS << ',' << Log2_32(ByteAlignment);
EmitEOL();
// Print symbol's rename (original name contains invalid character(s)) if
// there is one.
MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(CsectSym);
if (XSym->hasRename())
emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
}
void MCAsmStreamer::emitXCOFFSymbolLinkageWithVisibility(
MCSymbol *Symbol, MCSymbolAttr Linkage, MCSymbolAttr Visibility) {
switch (Linkage) {
case MCSA_Global:
OS << MAI->getGlobalDirective();
break;
case MCSA_Weak:
OS << MAI->getWeakDirective();
break;
case MCSA_Extern:
OS << "\t.extern\t";
break;
case MCSA_LGlobal:
OS << "\t.lglobl\t";
break;
default:
report_fatal_error("unhandled linkage type");
}
Symbol->print(OS, MAI);
switch (Visibility) {
case MCSA_Invalid:
// Nothing to do.
break;
case MCSA_Hidden:
OS << ",hidden";
break;
case MCSA_Protected:
OS << ",protected";
break;
default:
report_fatal_error("unexpected value for Visibility type");
}
EmitEOL();
// Print symbol's rename (original name contains invalid character(s)) if
// there is one.
if (cast<MCSymbolXCOFF>(Symbol)->hasRename())
emitXCOFFRenameDirective(Symbol,
cast<MCSymbolXCOFF>(Symbol)->getSymbolTableName());
}
void MCAsmStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
StringRef Rename) {
OS << "\t.rename\t";
Name->print(OS, MAI);
const char DQ = '"';
OS << ',' << DQ;
for (char C : Rename) {
// To escape a double quote character, the character should be doubled.
if (C == DQ)
OS << DQ;
OS << C;
}
OS << DQ;
EmitEOL();
}
void MCAsmStreamer::emitXCOFFRefDirective(StringRef Name) {
OS << "\t.ref " << Name;
EmitEOL();
}
void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
assert(MAI->hasDotTypeDotSizeDirective());
OS << "\t.size\t";
Symbol->print(OS, MAI);
OS << ", ";
Value->print(OS, MAI);
EmitEOL();
}
void MCAsmStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) {
OS << "\t.comm\t";
Symbol->print(OS, MAI);
OS << ',' << Size;
if (ByteAlignment != 0) {
if (MAI->getCOMMDirectiveAlignmentIsInBytes())
OS << ',' << ByteAlignment;
else
OS << ',' << Log2_32(ByteAlignment);
}
EmitEOL();
// Print symbol's rename (original name contains invalid character(s)) if
// there is one.
MCSymbolXCOFF *XSym = dyn_cast<MCSymbolXCOFF>(Symbol);
if (XSym && XSym->hasRename())
emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
}
void MCAsmStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlign) {
OS << "\t.lcomm\t";
Symbol->print(OS, MAI);
OS << ',' << Size;
if (ByteAlign > 1) {
switch (MAI->getLCOMMDirectiveAlignmentType()) {
case LCOMM::NoAlignment:
llvm_unreachable("alignment not supported on .lcomm!");
case LCOMM::ByteAlignment:
OS << ',' << ByteAlign;
break;
case LCOMM::Log2Alignment:
assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
OS << ',' << Log2_32(ByteAlign);
break;
}
}
EmitEOL();
}
void MCAsmStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
uint64_t Size, unsigned ByteAlignment,
SMLoc Loc) {
if (Symbol)
AssignFragment(Symbol, &Section->getDummyFragment());
// Note: a .zerofill directive does not switch sections.