1 //===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/MC/MCStreamer.h"
10 #include "llvm/ADT/Optional.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/BinaryFormat/COFF.h"
15 #include "llvm/BinaryFormat/MachO.h"
16 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCCodeView.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCPseudoProbe.h"
27 #include "llvm/MC/MCRegister.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCWin64EH.h"
33 #include "llvm/MC/MCWinEH.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/LEB128.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <cstdlib>
42 #include <utility>
43 
44 using namespace llvm;
45 
46 MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) {
47   S.setTargetStreamer(this);
48 }
49 
50 // Pin the vtables to this file.
51 MCTargetStreamer::~MCTargetStreamer() = default;
52 
53 void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {}
54 
55 void MCTargetStreamer::finish() {}
56 
57 void MCTargetStreamer::emitConstantPools() {}
58 
59 void MCTargetStreamer::changeSection(const MCSection *CurSection,
60                                      MCSection *Section,
61                                      const MCExpr *Subsection,
62                                      raw_ostream &OS) {
63   Section->printSwitchToSection(*Streamer.getContext().getAsmInfo(),
64                                 Streamer.getContext().getTargetTriple(), OS,
65                                 Subsection);
66 }
67 
68 void MCTargetStreamer::emitDwarfFileDirective(StringRef Directive) {
69   Streamer.emitRawText(Directive);
70 }
71 
72 void MCTargetStreamer::emitValue(const MCExpr *Value) {
73   SmallString<128> Str;
74   raw_svector_ostream OS(Str);
75 
76   Value->print(OS, Streamer.getContext().getAsmInfo());
77   Streamer.emitRawText(OS.str());
78 }
79 
80 void MCTargetStreamer::emitRawBytes(StringRef Data) {
81   const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
82   const char *Directive = MAI->getData8bitsDirective();
83   for (const unsigned char C : Data.bytes()) {
84     SmallString<128> Str;
85     raw_svector_ostream OS(Str);
86 
87     OS << Directive << (unsigned)C;
88     Streamer.emitRawText(OS.str());
89   }
90 }
91 
92 void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {}
93 
94 MCStreamer::MCStreamer(MCContext &Ctx)
95     : Context(Ctx), CurrentWinFrameInfo(nullptr),
96       CurrentProcWinFrameInfoStartIndex(0), UseAssemblerInfoForParsing(false) {
97   SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
98 }
99 
100 MCStreamer::~MCStreamer() = default;
101 
102 void MCStreamer::reset() {
103   DwarfFrameInfos.clear();
104   CurrentWinFrameInfo = nullptr;
105   WinFrameInfos.clear();
106   SymbolOrdering.clear();
107   SectionStack.clear();
108   SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
109 }
110 
111 raw_ostream &MCStreamer::GetCommentOS() {
112   // By default, discard comments.
113   return nulls();
114 }
115 
116 unsigned MCStreamer::getNumFrameInfos() { return DwarfFrameInfos.size(); }
117 ArrayRef<MCDwarfFrameInfo> MCStreamer::getDwarfFrameInfos() const {
118   return DwarfFrameInfos;
119 }
120 
121 void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {}
122 
123 void MCStreamer::addExplicitComment(const Twine &T) {}
124 void MCStreamer::emitExplicitComments() {}
125 
126 void MCStreamer::generateCompactUnwindEncodings(MCAsmBackend *MAB) {
127   for (auto &FI : DwarfFrameInfos)
128     FI.CompactUnwindEncoding =
129         (MAB ? MAB->generateCompactUnwindEncoding(FI.Instructions) : 0);
130 }
131 
132 /// EmitIntValue - Special case of EmitValue that avoids the client having to
133 /// pass in a MCExpr for constant integers.
134 void MCStreamer::emitIntValue(uint64_t Value, unsigned Size) {
135   assert(1 <= Size && Size <= 8 && "Invalid size");
136   assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) &&
137          "Invalid size");
138   const bool IsLittleEndian = Context.getAsmInfo()->isLittleEndian();
139   uint64_t Swapped = support::endian::byte_swap(
140       Value, IsLittleEndian ? support::little : support::big);
141   unsigned Index = IsLittleEndian ? 0 : 8 - Size;
142   emitBytes(StringRef(reinterpret_cast<char *>(&Swapped) + Index, Size));
143 }
144 void MCStreamer::emitIntValue(APInt Value) {
145   if (Value.getNumWords() == 1) {
146     emitIntValue(Value.getLimitedValue(), Value.getBitWidth() / 8);
147     return;
148   }
149 
150   const bool IsLittleEndianTarget = Context.getAsmInfo()->isLittleEndian();
151   const bool ShouldSwap = sys::IsLittleEndianHost != IsLittleEndianTarget;
152   const APInt Swapped = ShouldSwap ? Value.byteSwap() : Value;
153   const unsigned Size = Value.getBitWidth() / 8;
154   SmallString<10> Tmp;
155   Tmp.resize(Size);
156   StoreIntToMemory(Swapped, reinterpret_cast<uint8_t *>(Tmp.data()), Size);
157   emitBytes(Tmp.str());
158 }
159 
160 /// EmitULEB128IntValue - Special case of EmitULEB128Value that avoids the
161 /// client having to pass in a MCExpr for constant integers.
162 void MCStreamer::emitULEB128IntValue(uint64_t Value, unsigned PadTo) {
163   SmallString<128> Tmp;
164   raw_svector_ostream OSE(Tmp);
165   encodeULEB128(Value, OSE, PadTo);
166   emitBytes(OSE.str());
167 }
168 
169 /// EmitSLEB128IntValue - Special case of EmitSLEB128Value that avoids the
170 /// client having to pass in a MCExpr for constant integers.
171 void MCStreamer::emitSLEB128IntValue(int64_t Value) {
172   SmallString<128> Tmp;
173   raw_svector_ostream OSE(Tmp);
174   encodeSLEB128(Value, OSE);
175   emitBytes(OSE.str());
176 }
177 
178 void MCStreamer::emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc) {
179   emitValueImpl(Value, Size, Loc);
180 }
181 
182 void MCStreamer::emitSymbolValue(const MCSymbol *Sym, unsigned Size,
183                                  bool IsSectionRelative) {
184   assert((!IsSectionRelative || Size == 4) &&
185          "SectionRelative value requires 4-bytes");
186 
187   if (!IsSectionRelative)
188     emitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size);
189   else
190     EmitCOFFSecRel32(Sym, /*Offset=*/0);
191 }
192 
193 void MCStreamer::emitDTPRel64Value(const MCExpr *Value) {
194   report_fatal_error("unsupported directive in streamer");
195 }
196 
197 void MCStreamer::emitDTPRel32Value(const MCExpr *Value) {
198   report_fatal_error("unsupported directive in streamer");
199 }
200 
201 void MCStreamer::emitTPRel64Value(const MCExpr *Value) {
202   report_fatal_error("unsupported directive in streamer");
203 }
204 
205 void MCStreamer::emitTPRel32Value(const MCExpr *Value) {
206   report_fatal_error("unsupported directive in streamer");
207 }
208 
209 void MCStreamer::emitGPRel64Value(const MCExpr *Value) {
210   report_fatal_error("unsupported directive in streamer");
211 }
212 
213 void MCStreamer::emitGPRel32Value(const MCExpr *Value) {
214   report_fatal_error("unsupported directive in streamer");
215 }
216 
217 /// Emit NumBytes bytes worth of the value specified by FillValue.
218 /// This implements directives such as '.space'.
219 void MCStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
220   emitFill(*MCConstantExpr::create(NumBytes, getContext()), FillValue);
221 }
222 
223 void llvm::MCStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLen,
224                                 llvm::SMLoc, const MCSubtargetInfo& STI) {}
225 
226 /// The implementation in this class just redirects to emitFill.
227 void MCStreamer::emitZeros(uint64_t NumBytes) { emitFill(NumBytes, 0); }
228 
229 Expected<unsigned>
230 MCStreamer::tryEmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
231                                       StringRef Filename,
232                                       Optional<MD5::MD5Result> Checksum,
233                                       Optional<StringRef> Source,
234                                       unsigned CUID) {
235   return getContext().getDwarfFile(Directory, Filename, FileNo, Checksum,
236                                    Source, CUID);
237 }
238 
239 void MCStreamer::emitDwarfFile0Directive(StringRef Directory,
240                                          StringRef Filename,
241                                          Optional<MD5::MD5Result> Checksum,
242                                          Optional<StringRef> Source,
243                                          unsigned CUID) {
244   getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
245                                       Source);
246 }
247 
248 void MCStreamer::emitCFIBKeyFrame() {
249   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
250   if (!CurFrame)
251     return;
252   CurFrame->IsBKeyFrame = true;
253 }
254 
255 void MCStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
256                                        unsigned Column, unsigned Flags,
257                                        unsigned Isa, unsigned Discriminator,
258                                        StringRef FileName) {
259   getContext().setCurrentDwarfLoc(FileNo, Line, Column, Flags, Isa,
260                                   Discriminator);
261 }
262 
263 MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) {
264   MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
265   if (!Table.getLabel()) {
266     StringRef Prefix = Context.getAsmInfo()->getPrivateGlobalPrefix();
267     Table.setLabel(
268         Context.getOrCreateSymbol(Prefix + "line_table_start" + Twine(CUID)));
269   }
270   return Table.getLabel();
271 }
272 
273 bool MCStreamer::hasUnfinishedDwarfFrameInfo() {
274   return !DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End;
275 }
276 
277 MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() {
278   if (!hasUnfinishedDwarfFrameInfo()) {
279     getContext().reportError(getStartTokLoc(),
280                              "this directive must appear between "
281                              ".cfi_startproc and .cfi_endproc directives");
282     return nullptr;
283   }
284   return &DwarfFrameInfos.back();
285 }
286 
287 bool MCStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
288                                      ArrayRef<uint8_t> Checksum,
289                                      unsigned ChecksumKind) {
290   return getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
291                                              ChecksumKind);
292 }
293 
294 bool MCStreamer::EmitCVFuncIdDirective(unsigned FunctionId) {
295   return getContext().getCVContext().recordFunctionId(FunctionId);
296 }
297 
298 bool MCStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
299                                              unsigned IAFunc, unsigned IAFile,
300                                              unsigned IALine, unsigned IACol,
301                                              SMLoc Loc) {
302   if (getContext().getCVContext().getCVFunctionInfo(IAFunc) == nullptr) {
303     getContext().reportError(Loc, "parent function id not introduced by "
304                                   ".cv_func_id or .cv_inline_site_id");
305     return true;
306   }
307 
308   return getContext().getCVContext().recordInlinedCallSiteId(
309       FunctionId, IAFunc, IAFile, IALine, IACol);
310 }
311 
312 void MCStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
313                                     unsigned Line, unsigned Column,
314                                     bool PrologueEnd, bool IsStmt,
315                                     StringRef FileName, SMLoc Loc) {}
316 
317 bool MCStreamer::checkCVLocSection(unsigned FuncId, unsigned FileNo,
318                                    SMLoc Loc) {
319   CodeViewContext &CVC = getContext().getCVContext();
320   MCCVFunctionInfo *FI = CVC.getCVFunctionInfo(FuncId);
321   if (!FI) {
322     getContext().reportError(
323         Loc, "function id not introduced by .cv_func_id or .cv_inline_site_id");
324     return false;
325   }
326 
327   // Track the section
328   if (FI->Section == nullptr)
329     FI->Section = getCurrentSectionOnly();
330   else if (FI->Section != getCurrentSectionOnly()) {
331     getContext().reportError(
332         Loc,
333         "all .cv_loc directives for a function must be in the same section");
334     return false;
335   }
336   return true;
337 }
338 
339 void MCStreamer::emitCVLinetableDirective(unsigned FunctionId,
340                                           const MCSymbol *Begin,
341                                           const MCSymbol *End) {}
342 
343 void MCStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
344                                                 unsigned SourceFileId,
345                                                 unsigned SourceLineNum,
346                                                 const MCSymbol *FnStartSym,
347                                                 const MCSymbol *FnEndSym) {}
348 
349 /// Only call this on endian-specific types like ulittle16_t and little32_t, or
350 /// structs composed of them.
351 template <typename T>
352 static void copyBytesForDefRange(SmallString<20> &BytePrefix,
353                                  codeview::SymbolKind SymKind,
354                                  const T &DefRangeHeader) {
355   BytePrefix.resize(2 + sizeof(T));
356   codeview::ulittle16_t SymKindLE = codeview::ulittle16_t(SymKind);
357   memcpy(&BytePrefix[0], &SymKindLE, 2);
358   memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
359 }
360 
361 void MCStreamer::emitCVDefRangeDirective(
362     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
363     StringRef FixedSizePortion) {}
364 
365 void MCStreamer::emitCVDefRangeDirective(
366     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
367     codeview::DefRangeRegisterRelHeader DRHdr) {
368   SmallString<20> BytePrefix;
369   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER_REL, DRHdr);
370   emitCVDefRangeDirective(Ranges, BytePrefix);
371 }
372 
373 void MCStreamer::emitCVDefRangeDirective(
374     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
375     codeview::DefRangeSubfieldRegisterHeader DRHdr) {
376   SmallString<20> BytePrefix;
377   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_SUBFIELD_REGISTER,
378                        DRHdr);
379   emitCVDefRangeDirective(Ranges, BytePrefix);
380 }
381 
382 void MCStreamer::emitCVDefRangeDirective(
383     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
384     codeview::DefRangeRegisterHeader DRHdr) {
385   SmallString<20> BytePrefix;
386   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER, DRHdr);
387   emitCVDefRangeDirective(Ranges, BytePrefix);
388 }
389 
390 void MCStreamer::emitCVDefRangeDirective(
391     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
392     codeview::DefRangeFramePointerRelHeader DRHdr) {
393   SmallString<20> BytePrefix;
394   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_FRAMEPOINTER_REL,
395                        DRHdr);
396   emitCVDefRangeDirective(Ranges, BytePrefix);
397 }
398 
399 void MCStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
400                                      MCSymbol *EHSymbol) {
401 }
402 
403 void MCStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
404   SwitchSection(getContext().getObjectFileInfo()->getTextSection());
405 }
406 
407 void MCStreamer::AssignFragment(MCSymbol *Symbol, MCFragment *Fragment) {
408   assert(Fragment);
409   Symbol->setFragment(Fragment);
410 
411   // As we emit symbols into a section, track the order so that they can
412   // be sorted upon later. Zero is reserved to mean 'unemitted'.
413   SymbolOrdering[Symbol] = 1 + SymbolOrdering.size();
414 }
415 
416 void MCStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
417   Symbol->redefineIfPossible();
418 
419   if (!Symbol->isUndefined() || Symbol->isVariable())
420     return getContext().reportError(Loc, "symbol '" + Twine(Symbol->getName()) +
421                                              "' is already defined");
422 
423   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
424   assert(getCurrentSectionOnly() && "Cannot emit before setting section!");
425   assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
426   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
427 
428   Symbol->setFragment(&getCurrentSectionOnly()->getDummyFragment());
429 
430   MCTargetStreamer *TS = getTargetStreamer();
431   if (TS)
432     TS->emitLabel(Symbol);
433 }
434 
435 void MCStreamer::emitConditionalAssignment(MCSymbol *Symbol,
436                                            const MCExpr *Value) {}
437 
438 void MCStreamer::emitCFISections(bool EH, bool Debug) {}
439 
440 void MCStreamer::emitCFIStartProc(bool IsSimple, SMLoc Loc) {
441   if (hasUnfinishedDwarfFrameInfo())
442     return getContext().reportError(
443         Loc, "starting new .cfi frame before finishing the previous one");
444 
445   MCDwarfFrameInfo Frame;
446   Frame.IsSimple = IsSimple;
447   emitCFIStartProcImpl(Frame);
448 
449   const MCAsmInfo* MAI = Context.getAsmInfo();
450   if (MAI) {
451     for (const MCCFIInstruction& Inst : MAI->getInitialFrameState()) {
452       if (Inst.getOperation() == MCCFIInstruction::OpDefCfa ||
453           Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister ||
454           Inst.getOperation() == MCCFIInstruction::OpLLVMDefAspaceCfa) {
455         Frame.CurrentCfaRegister = Inst.getRegister();
456       }
457     }
458   }
459 
460   DwarfFrameInfos.push_back(Frame);
461 }
462 
463 void MCStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
464 }
465 
466 void MCStreamer::emitCFIEndProc() {
467   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
468   if (!CurFrame)
469     return;
470   emitCFIEndProcImpl(*CurFrame);
471 }
472 
473 void MCStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
474   // Put a dummy non-null value in Frame.End to mark that this frame has been
475   // closed.
476   Frame.End = (MCSymbol *)1;
477 }
478 
479 MCSymbol *MCStreamer::emitCFILabel() {
480   // Return a dummy non-null value so that label fields appear filled in when
481   // generating textual assembly.
482   return (MCSymbol *)1;
483 }
484 
485 void MCStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset) {
486   MCSymbol *Label = emitCFILabel();
487   MCCFIInstruction Instruction =
488       MCCFIInstruction::cfiDefCfa(Label, Register, Offset);
489   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
490   if (!CurFrame)
491     return;
492   CurFrame->Instructions.push_back(Instruction);
493   CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
494 }
495 
496 void MCStreamer::emitCFIDefCfaOffset(int64_t Offset) {
497   MCSymbol *Label = emitCFILabel();
498   MCCFIInstruction Instruction =
499       MCCFIInstruction::cfiDefCfaOffset(Label, Offset);
500   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
501   if (!CurFrame)
502     return;
503   CurFrame->Instructions.push_back(Instruction);
504 }
505 
506 void MCStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment) {
507   MCSymbol *Label = emitCFILabel();
508   MCCFIInstruction Instruction =
509     MCCFIInstruction::createAdjustCfaOffset(Label, Adjustment);
510   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
511   if (!CurFrame)
512     return;
513   CurFrame->Instructions.push_back(Instruction);
514 }
515 
516 void MCStreamer::emitCFIDefCfaRegister(int64_t Register) {
517   MCSymbol *Label = emitCFILabel();
518   MCCFIInstruction Instruction =
519     MCCFIInstruction::createDefCfaRegister(Label, Register);
520   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
521   if (!CurFrame)
522     return;
523   CurFrame->Instructions.push_back(Instruction);
524   CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
525 }
526 
527 void MCStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
528                                          int64_t AddressSpace) {
529   MCSymbol *Label = emitCFILabel();
530   MCCFIInstruction Instruction = MCCFIInstruction::createLLVMDefAspaceCfa(
531       Label, Register, Offset, AddressSpace);
532   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
533   if (!CurFrame)
534     return;
535   CurFrame->Instructions.push_back(Instruction);
536   CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
537 }
538 
539 void MCStreamer::emitCFIOffset(int64_t Register, int64_t Offset) {
540   MCSymbol *Label = emitCFILabel();
541   MCCFIInstruction Instruction =
542     MCCFIInstruction::createOffset(Label, Register, Offset);
543   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
544   if (!CurFrame)
545     return;
546   CurFrame->Instructions.push_back(Instruction);
547 }
548 
549 void MCStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset) {
550   MCSymbol *Label = emitCFILabel();
551   MCCFIInstruction Instruction =
552     MCCFIInstruction::createRelOffset(Label, Register, Offset);
553   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
554   if (!CurFrame)
555     return;
556   CurFrame->Instructions.push_back(Instruction);
557 }
558 
559 void MCStreamer::emitCFIPersonality(const MCSymbol *Sym,
560                                     unsigned Encoding) {
561   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
562   if (!CurFrame)
563     return;
564   CurFrame->Personality = Sym;
565   CurFrame->PersonalityEncoding = Encoding;
566 }
567 
568 void MCStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
569   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
570   if (!CurFrame)
571     return;
572   CurFrame->Lsda = Sym;
573   CurFrame->LsdaEncoding = Encoding;
574 }
575 
576 void MCStreamer::emitCFIRememberState() {
577   MCSymbol *Label = emitCFILabel();
578   MCCFIInstruction Instruction = MCCFIInstruction::createRememberState(Label);
579   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
580   if (!CurFrame)
581     return;
582   CurFrame->Instructions.push_back(Instruction);
583 }
584 
585 void MCStreamer::emitCFIRestoreState() {
586   // FIXME: Error if there is no matching cfi_remember_state.
587   MCSymbol *Label = emitCFILabel();
588   MCCFIInstruction Instruction = MCCFIInstruction::createRestoreState(Label);
589   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
590   if (!CurFrame)
591     return;
592   CurFrame->Instructions.push_back(Instruction);
593 }
594 
595 void MCStreamer::emitCFISameValue(int64_t Register) {
596   MCSymbol *Label = emitCFILabel();
597   MCCFIInstruction Instruction =
598     MCCFIInstruction::createSameValue(Label, Register);
599   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
600   if (!CurFrame)
601     return;
602   CurFrame->Instructions.push_back(Instruction);
603 }
604 
605 void MCStreamer::emitCFIRestore(int64_t Register) {
606   MCSymbol *Label = emitCFILabel();
607   MCCFIInstruction Instruction =
608     MCCFIInstruction::createRestore(Label, Register);
609   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
610   if (!CurFrame)
611     return;
612   CurFrame->Instructions.push_back(Instruction);
613 }
614 
615 void MCStreamer::emitCFIEscape(StringRef Values) {
616   MCSymbol *Label = emitCFILabel();
617   MCCFIInstruction Instruction = MCCFIInstruction::createEscape(Label, Values);
618   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
619   if (!CurFrame)
620     return;
621   CurFrame->Instructions.push_back(Instruction);
622 }
623 
624 void MCStreamer::emitCFIGnuArgsSize(int64_t Size) {
625   MCSymbol *Label = emitCFILabel();
626   MCCFIInstruction Instruction =
627     MCCFIInstruction::createGnuArgsSize(Label, Size);
628   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
629   if (!CurFrame)
630     return;
631   CurFrame->Instructions.push_back(Instruction);
632 }
633 
634 void MCStreamer::emitCFISignalFrame() {
635   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
636   if (!CurFrame)
637     return;
638   CurFrame->IsSignalFrame = true;
639 }
640 
641 void MCStreamer::emitCFIUndefined(int64_t Register) {
642   MCSymbol *Label = emitCFILabel();
643   MCCFIInstruction Instruction =
644     MCCFIInstruction::createUndefined(Label, Register);
645   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
646   if (!CurFrame)
647     return;
648   CurFrame->Instructions.push_back(Instruction);
649 }
650 
651 void MCStreamer::emitCFIRegister(int64_t Register1, int64_t Register2) {
652   MCSymbol *Label = emitCFILabel();
653   MCCFIInstruction Instruction =
654     MCCFIInstruction::createRegister(Label, Register1, Register2);
655   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
656   if (!CurFrame)
657     return;
658   CurFrame->Instructions.push_back(Instruction);
659 }
660 
661 void MCStreamer::emitCFIWindowSave() {
662   MCSymbol *Label = emitCFILabel();
663   MCCFIInstruction Instruction =
664     MCCFIInstruction::createWindowSave(Label);
665   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
666   if (!CurFrame)
667     return;
668   CurFrame->Instructions.push_back(Instruction);
669 }
670 
671 void MCStreamer::emitCFINegateRAState() {
672   MCSymbol *Label = emitCFILabel();
673   MCCFIInstruction Instruction = MCCFIInstruction::createNegateRAState(Label);
674   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
675   if (!CurFrame)
676     return;
677   CurFrame->Instructions.push_back(Instruction);
678 }
679 
680 void MCStreamer::emitCFIReturnColumn(int64_t Register) {
681   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
682   if (!CurFrame)
683     return;
684   CurFrame->RAReg = Register;
685 }
686 
687 WinEH::FrameInfo *MCStreamer::EnsureValidWinFrameInfo(SMLoc Loc) {
688   const MCAsmInfo *MAI = Context.getAsmInfo();
689   if (!MAI->usesWindowsCFI()) {
690     getContext().reportError(
691         Loc, ".seh_* directives are not supported on this target");
692     return nullptr;
693   }
694   if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) {
695     getContext().reportError(
696         Loc, ".seh_ directive must appear within an active frame");
697     return nullptr;
698   }
699   return CurrentWinFrameInfo;
700 }
701 
702 void MCStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
703   const MCAsmInfo *MAI = Context.getAsmInfo();
704   if (!MAI->usesWindowsCFI())
705     return getContext().reportError(
706         Loc, ".seh_* directives are not supported on this target");
707   if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End)
708     getContext().reportError(
709         Loc, "Starting a function before ending the previous one!");
710 
711   MCSymbol *StartProc = emitCFILabel();
712 
713   CurrentProcWinFrameInfoStartIndex = WinFrameInfos.size();
714   WinFrameInfos.emplace_back(
715       std::make_unique<WinEH::FrameInfo>(Symbol, StartProc));
716   CurrentWinFrameInfo = WinFrameInfos.back().get();
717   CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
718 }
719 
720 void MCStreamer::EmitWinCFIEndProc(SMLoc Loc) {
721   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
722   if (!CurFrame)
723     return;
724   if (CurFrame->ChainedParent)
725     getContext().reportError(Loc, "Not all chained regions terminated!");
726 
727   MCSymbol *Label = emitCFILabel();
728   CurFrame->End = Label;
729   if (!CurFrame->FuncletOrFuncEnd)
730     CurFrame->FuncletOrFuncEnd = CurFrame->End;
731 
732   for (size_t I = CurrentProcWinFrameInfoStartIndex, E = WinFrameInfos.size();
733        I != E; ++I)
734     EmitWindowsUnwindTables(WinFrameInfos[I].get());
735   SwitchSection(CurFrame->TextSection);
736 }
737 
738 void MCStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
739   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
740   if (!CurFrame)
741     return;
742   if (CurFrame->ChainedParent)
743     getContext().reportError(Loc, "Not all chained regions terminated!");
744 
745   MCSymbol *Label = emitCFILabel();
746   CurFrame->FuncletOrFuncEnd = Label;
747 }
748 
749 void MCStreamer::EmitWinCFIStartChained(SMLoc Loc) {
750   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
751   if (!CurFrame)
752     return;
753 
754   MCSymbol *StartProc = emitCFILabel();
755 
756   WinFrameInfos.emplace_back(std::make_unique<WinEH::FrameInfo>(
757       CurFrame->Function, StartProc, CurFrame));
758   CurrentWinFrameInfo = WinFrameInfos.back().get();
759   CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
760 }
761 
762 void MCStreamer::EmitWinCFIEndChained(SMLoc Loc) {
763   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
764   if (!CurFrame)
765     return;
766   if (!CurFrame->ChainedParent)
767     return getContext().reportError(
768         Loc, "End of a chained region outside a chained region!");
769 
770   MCSymbol *Label = emitCFILabel();
771 
772   CurFrame->End = Label;
773   CurrentWinFrameInfo = const_cast<WinEH::FrameInfo *>(CurFrame->ChainedParent);
774 }
775 
776 void MCStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
777                                   SMLoc Loc) {
778   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
779   if (!CurFrame)
780     return;
781   if (CurFrame->ChainedParent)
782     return getContext().reportError(
783         Loc, "Chained unwind areas can't have handlers!");
784   CurFrame->ExceptionHandler = Sym;
785   if (!Except && !Unwind)
786     getContext().reportError(Loc, "Don't know what kind of handler this is!");
787   if (Unwind)
788     CurFrame->HandlesUnwind = true;
789   if (Except)
790     CurFrame->HandlesExceptions = true;
791 }
792 
793 void MCStreamer::EmitWinEHHandlerData(SMLoc Loc) {
794   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
795   if (!CurFrame)
796     return;
797   if (CurFrame->ChainedParent)
798     getContext().reportError(Loc, "Chained unwind areas can't have handlers!");
799 }
800 
801 void MCStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
802                                     const MCSymbolRefExpr *To, uint64_t Count) {
803 }
804 
805 static MCSection *getWinCFISection(MCContext &Context, unsigned *NextWinCFIID,
806                                    MCSection *MainCFISec,
807                                    const MCSection *TextSec) {
808   // If this is the main .text section, use the main unwind info section.
809   if (TextSec == Context.getObjectFileInfo()->getTextSection())
810     return MainCFISec;
811 
812   const auto *TextSecCOFF = cast<MCSectionCOFF>(TextSec);
813   auto *MainCFISecCOFF = cast<MCSectionCOFF>(MainCFISec);
814   unsigned UniqueID = TextSecCOFF->getOrAssignWinCFISectionID(NextWinCFIID);
815 
816   // If this section is COMDAT, this unwind section should be COMDAT associative
817   // with its group.
818   const MCSymbol *KeySym = nullptr;
819   if (TextSecCOFF->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
820     KeySym = TextSecCOFF->getCOMDATSymbol();
821 
822     // In a GNU environment, we can't use associative comdats. Instead, do what
823     // GCC does, which is to make plain comdat selectany section named like
824     // ".[px]data$_Z3foov".
825     if (!Context.getAsmInfo()->hasCOFFAssociativeComdats()) {
826       std::string SectionName = (MainCFISecCOFF->getName() + "$" +
827                                  TextSecCOFF->getName().split('$').second)
828                                     .str();
829       return Context.getCOFFSection(
830           SectionName,
831           MainCFISecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT,
832           MainCFISecCOFF->getKind(), "", COFF::IMAGE_COMDAT_SELECT_ANY);
833     }
834   }
835 
836   return Context.getAssociativeCOFFSection(MainCFISecCOFF, KeySym, UniqueID);
837 }
838 
839 MCSection *MCStreamer::getAssociatedPDataSection(const MCSection *TextSec) {
840   return getWinCFISection(getContext(), &NextWinCFIID,
841                           getContext().getObjectFileInfo()->getPDataSection(),
842                           TextSec);
843 }
844 
845 MCSection *MCStreamer::getAssociatedXDataSection(const MCSection *TextSec) {
846   return getWinCFISection(getContext(), &NextWinCFIID,
847                           getContext().getObjectFileInfo()->getXDataSection(),
848                           TextSec);
849 }
850 
851 void MCStreamer::emitSyntaxDirective() {}
852 
853 static unsigned encodeSEHRegNum(MCContext &Ctx, MCRegister Reg) {
854   return Ctx.getRegisterInfo()->getSEHRegNum(Reg);
855 }
856 
857 void MCStreamer::EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
858   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
859   if (!CurFrame)
860     return;
861 
862   MCSymbol *Label = emitCFILabel();
863 
864   WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(
865       Label, encodeSEHRegNum(Context, Register));
866   CurFrame->Instructions.push_back(Inst);
867 }
868 
869 void MCStreamer::EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
870                                     SMLoc Loc) {
871   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
872   if (!CurFrame)
873     return;
874   if (CurFrame->LastFrameInst >= 0)
875     return getContext().reportError(
876         Loc, "frame register and offset can be set at most once");
877   if (Offset & 0x0F)
878     return getContext().reportError(Loc, "offset is not a multiple of 16");
879   if (Offset > 240)
880     return getContext().reportError(
881         Loc, "frame offset must be less than or equal to 240");
882 
883   MCSymbol *Label = emitCFILabel();
884 
885   WinEH::Instruction Inst = Win64EH::Instruction::SetFPReg(
886       Label, encodeSEHRegNum(getContext(), Register), Offset);
887   CurFrame->LastFrameInst = CurFrame->Instructions.size();
888   CurFrame->Instructions.push_back(Inst);
889 }
890 
891 void MCStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
892   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
893   if (!CurFrame)
894     return;
895   if (Size == 0)
896     return getContext().reportError(Loc,
897                                     "stack allocation size must be non-zero");
898   if (Size & 7)
899     return getContext().reportError(
900         Loc, "stack allocation size is not a multiple of 8");
901 
902   MCSymbol *Label = emitCFILabel();
903 
904   WinEH::Instruction Inst = Win64EH::Instruction::Alloc(Label, Size);
905   CurFrame->Instructions.push_back(Inst);
906 }
907 
908 void MCStreamer::EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
909                                    SMLoc Loc) {
910   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
911   if (!CurFrame)
912     return;
913 
914   if (Offset & 7)
915     return getContext().reportError(
916         Loc, "register save offset is not 8 byte aligned");
917 
918   MCSymbol *Label = emitCFILabel();
919 
920   WinEH::Instruction Inst = Win64EH::Instruction::SaveNonVol(
921       Label, encodeSEHRegNum(Context, Register), Offset);
922   CurFrame->Instructions.push_back(Inst);
923 }
924 
925 void MCStreamer::EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
926                                    SMLoc Loc) {
927   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
928   if (!CurFrame)
929     return;
930   if (Offset & 0x0F)
931     return getContext().reportError(Loc, "offset is not a multiple of 16");
932 
933   MCSymbol *Label = emitCFILabel();
934 
935   WinEH::Instruction Inst = Win64EH::Instruction::SaveXMM(
936       Label, encodeSEHRegNum(Context, Register), Offset);
937   CurFrame->Instructions.push_back(Inst);
938 }
939 
940 void MCStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
941   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
942   if (!CurFrame)
943     return;
944   if (!CurFrame->Instructions.empty())
945     return getContext().reportError(
946         Loc, "If present, PushMachFrame must be the first UOP");
947 
948   MCSymbol *Label = emitCFILabel();
949 
950   WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(Label, Code);
951   CurFrame->Instructions.push_back(Inst);
952 }
953 
954 void MCStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
955   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
956   if (!CurFrame)
957     return;
958 
959   MCSymbol *Label = emitCFILabel();
960 
961   CurFrame->PrologEnd = Label;
962 }
963 
964 void MCStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {}
965 
966 void MCStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {}
967 
968 void MCStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {}
969 
970 void MCStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {}
971 
972 void MCStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {}
973 
974 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
975 /// the specified string in the output .s file.  This capability is
976 /// indicated by the hasRawTextSupport() predicate.
977 void MCStreamer::emitRawTextImpl(StringRef String) {
978   // This is not llvm_unreachable for the sake of out of tree backend
979   // developers who may not have assembly streamers and should serve as a
980   // reminder to not accidentally call EmitRawText in the absence of such.
981   report_fatal_error("EmitRawText called on an MCStreamer that doesn't support "
982                      "it (target backend is likely missing an AsmStreamer "
983                      "implementation)");
984 }
985 
986 void MCStreamer::emitRawText(const Twine &T) {
987   SmallString<128> Str;
988   emitRawTextImpl(T.toStringRef(Str));
989 }
990 
991 void MCStreamer::EmitWindowsUnwindTables() {
992 }
993 
994 void MCStreamer::EmitWindowsUnwindTables(WinEH::FrameInfo *Frame) {
995 }
996 
997 void MCStreamer::Finish(SMLoc EndLoc) {
998   if ((!DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End) ||
999       (!WinFrameInfos.empty() && !WinFrameInfos.back()->End)) {
1000     getContext().reportError(EndLoc, "Unfinished frame!");
1001     return;
1002   }
1003 
1004   MCTargetStreamer *TS = getTargetStreamer();
1005   if (TS)
1006     TS->finish();
1007 
1008   finishImpl();
1009 }
1010 
1011 void MCStreamer::maybeEmitDwarf64Mark() {
1012   if (Context.getDwarfFormat() != dwarf::DWARF64)
1013     return;
1014   AddComment("DWARF64 Mark");
1015   emitInt32(dwarf::DW_LENGTH_DWARF64);
1016 }
1017 
1018 void MCStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
1019   assert(Context.getDwarfFormat() == dwarf::DWARF64 ||
1020          Length <= dwarf::DW_LENGTH_lo_reserved);
1021   maybeEmitDwarf64Mark();
1022   AddComment(Comment);
1023   emitIntValue(Length, dwarf::getDwarfOffsetByteSize(Context.getDwarfFormat()));
1024 }
1025 
1026 MCSymbol *MCStreamer::emitDwarfUnitLength(const Twine &Prefix,
1027                                           const Twine &Comment) {
1028   maybeEmitDwarf64Mark();
1029   AddComment(Comment);
1030   MCSymbol *Lo = Context.createTempSymbol(Prefix + "_start");
1031   MCSymbol *Hi = Context.createTempSymbol(Prefix + "_end");
1032 
1033   emitAbsoluteSymbolDiff(
1034       Hi, Lo, dwarf::getDwarfOffsetByteSize(Context.getDwarfFormat()));
1035   // emit the begin symbol after we generate the length field.
1036   emitLabel(Lo);
1037   // Return the Hi symbol to the caller.
1038   return Hi;
1039 }
1040 
1041 void MCStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
1042   // Set the value of the symbol, as we are at the start of the line table.
1043   emitLabel(StartSym);
1044 }
1045 
1046 void MCStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
1047   visitUsedExpr(*Value);
1048   Symbol->setVariableValue(Value);
1049 
1050   MCTargetStreamer *TS = getTargetStreamer();
1051   if (TS)
1052     TS->emitAssignment(Symbol, Value);
1053 }
1054 
1055 void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter,
1056                                       uint64_t Address, const MCInst &Inst,
1057                                       const MCSubtargetInfo &STI,
1058                                       raw_ostream &OS) {
1059   InstPrinter.printInst(&Inst, Address, "", STI, OS);
1060 }
1061 
1062 void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) {
1063 }
1064 
1065 void MCStreamer::visitUsedExpr(const MCExpr &Expr) {
1066   switch (Expr.getKind()) {
1067   case MCExpr::Target:
1068     cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
1069     break;
1070 
1071   case MCExpr::Constant:
1072     break;
1073 
1074   case MCExpr::Binary: {
1075     const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
1076     visitUsedExpr(*BE.getLHS());
1077     visitUsedExpr(*BE.getRHS());
1078     break;
1079   }
1080 
1081   case MCExpr::SymbolRef:
1082     visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
1083     break;
1084 
1085   case MCExpr::Unary:
1086     visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
1087     break;
1088   }
1089 }
1090 
1091 void MCStreamer::emitInstruction(const MCInst &Inst, const MCSubtargetInfo &) {
1092   // Scan for values.
1093   for (unsigned i = Inst.getNumOperands(); i--;)
1094     if (Inst.getOperand(i).isExpr())
1095       visitUsedExpr(*Inst.getOperand(i).getExpr());
1096 }
1097 
1098 void MCStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
1099                                  uint64_t Attr,
1100                                  const MCPseudoProbeInlineStack &InlineStack) {
1101   auto &Context = getContext();
1102 
1103   // Create a symbol at in the current section for use in the probe.
1104   MCSymbol *ProbeSym = Context.createTempSymbol();
1105 
1106   // Set the value of the symbol to use for the MCPseudoProbe.
1107   emitLabel(ProbeSym);
1108 
1109   // Create a (local) probe entry with the symbol.
1110   MCPseudoProbe Probe(ProbeSym, Guid, Index, Type, Attr);
1111 
1112   // Add the probe entry to this section's entries.
1113   Context.getMCPseudoProbeTable().getProbeSections().addPseudoProbe(
1114       getCurrentSectionOnly(), Probe, InlineStack);
1115 }
1116 
1117 void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
1118                                         unsigned Size) {
1119   // Get the Hi-Lo expression.
1120   const MCExpr *Diff =
1121       MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
1122                               MCSymbolRefExpr::create(Lo, Context), Context);
1123 
1124   const MCAsmInfo *MAI = Context.getAsmInfo();
1125   if (!MAI->doesSetDirectiveSuppressReloc()) {
1126     emitValue(Diff, Size);
1127     return;
1128   }
1129 
1130   // Otherwise, emit with .set (aka assignment).
1131   MCSymbol *SetLabel = Context.createTempSymbol("set");
1132   emitAssignment(SetLabel, Diff);
1133   emitSymbolValue(SetLabel, Size);
1134 }
1135 
1136 void MCStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
1137                                                  const MCSymbol *Lo) {
1138   // Get the Hi-Lo expression.
1139   const MCExpr *Diff =
1140       MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
1141                               MCSymbolRefExpr::create(Lo, Context), Context);
1142 
1143   emitULEB128Value(Diff);
1144 }
1145 
1146 void MCStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {}
1147 void MCStreamer::emitThumbFunc(MCSymbol *Func) {}
1148 void MCStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
1149 void MCStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
1150   llvm_unreachable("this directive only supported on COFF targets");
1151 }
1152 void MCStreamer::EndCOFFSymbolDef() {
1153   llvm_unreachable("this directive only supported on COFF targets");
1154 }
1155 void MCStreamer::emitFileDirective(StringRef Filename) {}
1156 void MCStreamer::emitFileDirective(StringRef Filename, StringRef CompilerVerion,
1157                                    StringRef TimeStamp, StringRef Description) {
1158 }
1159 void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
1160   llvm_unreachable("this directive only supported on COFF targets");
1161 }
1162 void MCStreamer::EmitCOFFSymbolType(int Type) {
1163   llvm_unreachable("this directive only supported on COFF targets");
1164 }
1165 void MCStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
1166                                             MCSymbol *CsectSym,
1167                                             unsigned ByteAlign) {
1168   llvm_unreachable("this directive only supported on XCOFF targets");
1169 }
1170 
1171 void MCStreamer::emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
1172                                                       MCSymbolAttr Linkage,
1173                                                       MCSymbolAttr Visibility) {
1174   llvm_unreachable("emitXCOFFSymbolLinkageWithVisibility is only supported on "
1175                    "XCOFF targets");
1176 }
1177 
1178 void MCStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
1179                                           StringRef Rename) {
1180   llvm_unreachable("emitXCOFFRenameDirective is only supported on "
1181                    "XCOFF targets");
1182 }
1183 
1184 void MCStreamer::emitXCOFFRefDirective(StringRef Name) {
1185   llvm_unreachable("emitXCOFFRefDirective is only supported on XCOFF targets");
1186 }
1187 
1188 void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
1189 void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
1190                                         StringRef Name, bool KeepOriginalSym) {}
1191 void MCStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1192                                        unsigned ByteAlignment) {}
1193 void MCStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
1194                                 uint64_t Size, unsigned ByteAlignment) {}
1195 void MCStreamer::changeSection(MCSection *, const MCExpr *) {}
1196 void MCStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
1197 void MCStreamer::emitBytes(StringRef Data) {}
1198 void MCStreamer::emitBinaryData(StringRef Data) { emitBytes(Data); }
1199 void MCStreamer::emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) {
1200   visitUsedExpr(*Value);
1201 }
1202 void MCStreamer::emitULEB128Value(const MCExpr *Value) {}
1203 void MCStreamer::emitSLEB128Value(const MCExpr *Value) {}
1204 void MCStreamer::emitFill(const MCExpr &NumBytes, uint64_t Value, SMLoc Loc) {}
1205 void MCStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
1206                           SMLoc Loc) {}
1207 void MCStreamer::emitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1208                                       unsigned ValueSize,
1209                                       unsigned MaxBytesToEmit) {}
1210 void MCStreamer::emitCodeAlignment(unsigned ByteAlignment,
1211                                    const MCSubtargetInfo *STI,
1212                                    unsigned MaxBytesToEmit) {}
1213 void MCStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value,
1214                                    SMLoc Loc) {}
1215 void MCStreamer::emitBundleAlignMode(unsigned AlignPow2) {}
1216 void MCStreamer::emitBundleLock(bool AlignToEnd) {}
1217 void MCStreamer::finishImpl() {}
1218 void MCStreamer::emitBundleUnlock() {}
1219 
1220 void MCStreamer::SwitchSection(MCSection *Section, const MCExpr *Subsection) {
1221   assert(Section && "Cannot switch to a null section!");
1222   MCSectionSubPair curSection = SectionStack.back().first;
1223   SectionStack.back().second = curSection;
1224   if (MCSectionSubPair(Section, Subsection) != curSection) {
1225     changeSection(Section, Subsection);
1226     SectionStack.back().first = MCSectionSubPair(Section, Subsection);
1227     assert(!Section->hasEnded() && "Section already ended");
1228     MCSymbol *Sym = Section->getBeginSymbol();
1229     if (Sym && !Sym->isInSection())
1230       emitLabel(Sym);
1231   }
1232 }
1233 
1234 MCSymbol *MCStreamer::endSection(MCSection *Section) {
1235   // TODO: keep track of the last subsection so that this symbol appears in the
1236   // correct place.
1237   MCSymbol *Sym = Section->getEndSymbol(Context);
1238   if (Sym->isInSection())
1239     return Sym;
1240 
1241   SwitchSection(Section);
1242   emitLabel(Sym);
1243   return Sym;
1244 }
1245 
1246 static VersionTuple
1247 targetVersionOrMinimumSupportedOSVersion(const Triple &Target,
1248                                          VersionTuple TargetVersion) {
1249   VersionTuple Min = Target.getMinimumSupportedOSVersion();
1250   return !Min.empty() && Min > TargetVersion ? Min : TargetVersion;
1251 }
1252 
1253 static MCVersionMinType
1254 getMachoVersionMinLoadCommandType(const Triple &Target) {
1255   assert(Target.isOSDarwin() && "expected a darwin OS");
1256   switch (Target.getOS()) {
1257   case Triple::MacOSX:
1258   case Triple::Darwin:
1259     return MCVM_OSXVersionMin;
1260   case Triple::IOS:
1261     assert(!Target.isMacCatalystEnvironment() &&
1262            "mac Catalyst should use LC_BUILD_VERSION");
1263     return MCVM_IOSVersionMin;
1264   case Triple::TvOS:
1265     return MCVM_TvOSVersionMin;
1266   case Triple::WatchOS:
1267     return MCVM_WatchOSVersionMin;
1268   default:
1269     break;
1270   }
1271   llvm_unreachable("unexpected OS type");
1272 }
1273 
1274 static VersionTuple getMachoBuildVersionSupportedOS(const Triple &Target) {
1275   assert(Target.isOSDarwin() && "expected a darwin OS");
1276   switch (Target.getOS()) {
1277   case Triple::MacOSX:
1278   case Triple::Darwin:
1279     return VersionTuple(10, 14);
1280   case Triple::IOS:
1281     // Mac Catalyst always uses the build version load command.
1282     if (Target.isMacCatalystEnvironment())
1283       return VersionTuple();
1284     LLVM_FALLTHROUGH;
1285   case Triple::TvOS:
1286     return VersionTuple(12);
1287   case Triple::WatchOS:
1288     return VersionTuple(5);
1289   case Triple::DriverKit:
1290     // DriverKit always uses the build version load command.
1291     return VersionTuple();
1292   default:
1293     break;
1294   }
1295   llvm_unreachable("unexpected OS type");
1296 }
1297 
1298 static MachO::PlatformType
1299 getMachoBuildVersionPlatformType(const Triple &Target) {
1300   assert(Target.isOSDarwin() && "expected a darwin OS");
1301   switch (Target.getOS()) {
1302   case Triple::MacOSX:
1303   case Triple::Darwin:
1304     return MachO::PLATFORM_MACOS;
1305   case Triple::IOS:
1306     if (Target.isMacCatalystEnvironment())
1307       return MachO::PLATFORM_MACCATALYST;
1308     return Target.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR
1309                                            : MachO::PLATFORM_IOS;
1310   case Triple::TvOS:
1311     return Target.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR
1312                                            : MachO::PLATFORM_TVOS;
1313   case Triple::WatchOS:
1314     return Target.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR
1315                                            : MachO::PLATFORM_WATCHOS;
1316   case Triple::DriverKit:
1317     return MachO::PLATFORM_DRIVERKIT;
1318   default:
1319     break;
1320   }
1321   llvm_unreachable("unexpected OS type");
1322 }
1323 
1324 void MCStreamer::emitVersionForTarget(
1325     const Triple &Target, const VersionTuple &SDKVersion,
1326     const Triple *DarwinTargetVariantTriple,
1327     const VersionTuple &DarwinTargetVariantSDKVersion) {
1328   if (!Target.isOSBinFormatMachO() || !Target.isOSDarwin())
1329     return;
1330   // Do we even know the version?
1331   if (Target.getOSMajorVersion() == 0)
1332     return;
1333 
1334   VersionTuple Version;
1335   switch (Target.getOS()) {
1336   case Triple::MacOSX:
1337   case Triple::Darwin:
1338     Target.getMacOSXVersion(Version);
1339     break;
1340   case Triple::IOS:
1341   case Triple::TvOS:
1342     Version = Target.getiOSVersion();
1343     break;
1344   case Triple::WatchOS:
1345     Version = Target.getWatchOSVersion();
1346     break;
1347   case Triple::DriverKit:
1348     Version = Target.getDriverKitVersion();
1349     break;
1350   default:
1351     llvm_unreachable("unexpected OS type");
1352   }
1353   assert(Version.getMajor() != 0 && "A non-zero major version is expected");
1354   auto LinkedTargetVersion =
1355       targetVersionOrMinimumSupportedOSVersion(Target, Version);
1356   auto BuildVersionOSVersion = getMachoBuildVersionSupportedOS(Target);
1357   bool ShouldEmitBuildVersion = false;
1358   if (BuildVersionOSVersion.empty() ||
1359       LinkedTargetVersion >= BuildVersionOSVersion) {
1360     if (Target.isMacCatalystEnvironment() && DarwinTargetVariantTriple &&
1361         DarwinTargetVariantTriple->isMacOSX()) {
1362       emitVersionForTarget(*DarwinTargetVariantTriple,
1363                            DarwinTargetVariantSDKVersion,
1364                            /*DarwinTargetVariantTriple=*/nullptr,
1365                            /*DarwinTargetVariantSDKVersion=*/VersionTuple());
1366       emitDarwinTargetVariantBuildVersion(
1367           getMachoBuildVersionPlatformType(Target),
1368           LinkedTargetVersion.getMajor(),
1369           LinkedTargetVersion.getMinor().getValueOr(0),
1370           LinkedTargetVersion.getSubminor().getValueOr(0), SDKVersion);
1371       return;
1372     }
1373     emitBuildVersion(getMachoBuildVersionPlatformType(Target),
1374                      LinkedTargetVersion.getMajor(),
1375                      LinkedTargetVersion.getMinor().getValueOr(0),
1376                      LinkedTargetVersion.getSubminor().getValueOr(0),
1377                      SDKVersion);
1378     ShouldEmitBuildVersion = true;
1379   }
1380 
1381   if (const Triple *TVT = DarwinTargetVariantTriple) {
1382     if (Target.isMacOSX() && TVT->isMacCatalystEnvironment()) {
1383       auto TVLinkedTargetVersion =
1384           targetVersionOrMinimumSupportedOSVersion(*TVT, TVT->getiOSVersion());
1385       emitDarwinTargetVariantBuildVersion(
1386           getMachoBuildVersionPlatformType(*TVT),
1387           TVLinkedTargetVersion.getMajor(),
1388           TVLinkedTargetVersion.getMinor().getValueOr(0),
1389           TVLinkedTargetVersion.getSubminor().getValueOr(0),
1390           DarwinTargetVariantSDKVersion);
1391     }
1392   }
1393 
1394   if (ShouldEmitBuildVersion)
1395     return;
1396 
1397   emitVersionMin(getMachoVersionMinLoadCommandType(Target),
1398                  LinkedTargetVersion.getMajor(),
1399                  LinkedTargetVersion.getMinor().getValueOr(0),
1400                  LinkedTargetVersion.getSubminor().getValueOr(0), SDKVersion);
1401 }
1402