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