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/SmallString.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/BinaryFormat/COFF.h"
14#include "llvm/BinaryFormat/MachO.h"
15#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
16#include "llvm/MC/MCAsmInfo.h"
17#include "llvm/MC/MCCodeView.h"
18#include "llvm/MC/MCContext.h"
19#include "llvm/MC/MCDwarf.h"
20#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCInst.h"
22#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCLFIRewriter.h"
24#include "llvm/MC/MCObjectFileInfo.h"
25#include "llvm/MC/MCPseudoProbe.h"
26#include "llvm/MC/MCRegister.h"
27#include "llvm/MC/MCRegisterInfo.h"
28#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCSectionCOFF.h"
30#include "llvm/MC/MCSymbol.h"
31#include "llvm/MC/MCWin64EH.h"
32#include "llvm/MC/MCWinEH.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/LEB128.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/raw_ostream.h"
38#include <cassert>
39#include <cstdint>
40#include <cstdlib>
41#include <optional>
42#include <utility>
43
44using namespace llvm;
45
46MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) {
47 S.setTargetStreamer(this);
48}
49
50// Pin the vtables to this file.
51MCTargetStreamer::~MCTargetStreamer() = default;
52
53void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {}
54
55void MCTargetStreamer::finish() {}
56
57void MCTargetStreamer::emitConstantPools() {}
58
59void MCTargetStreamer::changeSection(const MCSection *, MCSection *Sec,
60 uint32_t Subsection, raw_ostream &OS) {
61 auto &MAI = Streamer.getContext().getAsmInfo();
62 MAI.printSwitchToSection(*Sec, Subsection,
63 Streamer.getContext().getTargetTriple(), OS);
64}
65
66void MCTargetStreamer::emitDwarfFileDirective(StringRef Directive) {
67 Streamer.emitRawText(String: Directive);
68}
69
70void MCTargetStreamer::emitValue(const MCExpr *Value) {
71 SmallString<128> Str;
72 raw_svector_ostream OS(Str);
73
74 Streamer.getContext().getAsmInfo().printExpr(OS, *Value);
75 Streamer.emitRawText(String: OS.str());
76}
77
78void MCTargetStreamer::emitRawBytes(StringRef Data) {
79 const MCAsmInfo &MAI = Streamer.getContext().getAsmInfo();
80 const char *Directive = MAI.getData8bitsDirective();
81 for (const unsigned char C : Data.bytes()) {
82 SmallString<128> Str;
83 raw_svector_ostream OS(Str);
84
85 OS << Directive << (unsigned)C;
86 Streamer.emitRawText(String: OS.str());
87 }
88}
89
90void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {}
91
92MCStreamer::MCStreamer(MCContext &Ctx)
93 : Context(Ctx), CurrentWinFrameInfo(nullptr),
94 CurrentProcWinFrameInfoStartIndex(0) {
95 SectionStack.push_back(Elt: std::pair<MCSectionSubPair, MCSectionSubPair>());
96}
97
98MCStreamer::~MCStreamer() = default;
99
100void MCStreamer::setLFIRewriter(std::unique_ptr<MCLFIRewriter> Rewriter) {
101 LFIRewriter = std::move(Rewriter);
102}
103
104void MCStreamer::reset() {
105 DwarfFrameInfos.clear();
106 CurrentWinFrameInfo = nullptr;
107 WinFrameInfos.clear();
108 SectionStack.clear();
109 SectionStack.push_back(Elt: std::pair<MCSectionSubPair, MCSectionSubPair>());
110 CurFrag = nullptr;
111}
112
113raw_ostream &MCStreamer::getCommentOS() {
114 // By default, discard comments.
115 return nulls();
116}
117
118unsigned MCStreamer::getNumFrameInfos() { return DwarfFrameInfos.size(); }
119ArrayRef<MCDwarfFrameInfo> MCStreamer::getDwarfFrameInfos() const {
120 return DwarfFrameInfos;
121}
122
123void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {}
124
125void MCStreamer::addExplicitComment(const Twine &T) {}
126void MCStreamer::emitExplicitComments() {}
127
128/// EmitIntValue - Special case of EmitValue that avoids the client having to
129/// pass in a MCExpr for constant integers.
130void MCStreamer::emitIntValue(uint64_t Value, unsigned Size) {
131 assert(1 <= Size && Size <= 8 && "Invalid size");
132 assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) &&
133 "Invalid size");
134 const bool IsLittleEndian = Context.getAsmInfo().isLittleEndian();
135 uint64_t Swapped = support::endian::byte_swap(
136 value: Value, endian: IsLittleEndian ? llvm::endianness::little : llvm::endianness::big);
137 unsigned Index = IsLittleEndian ? 0 : 8 - Size;
138 emitBytes(Data: StringRef(reinterpret_cast<char *>(&Swapped) + Index, Size));
139}
140void MCStreamer::emitIntValue(const APInt &Value) {
141 if (Value.getNumWords() == 1) {
142 emitIntValue(Value: Value.getLimitedValue(), Size: Value.getBitWidth() / 8);
143 return;
144 }
145
146 const bool IsLittleEndianTarget = Context.getAsmInfo().isLittleEndian();
147 const bool ShouldSwap = sys::IsLittleEndianHost != IsLittleEndianTarget;
148 const APInt Swapped = ShouldSwap ? Value.byteSwap() : Value;
149 const unsigned Size = Value.getBitWidth() / 8;
150 SmallString<10> Tmp;
151 Tmp.resize(N: Size);
152 StoreIntToMemory(IntVal: Swapped, Dst: reinterpret_cast<uint8_t *>(Tmp.data()), StoreBytes: Size);
153 emitBytes(Data: Tmp.str());
154}
155
156/// EmitULEB128IntValue - Special case of EmitULEB128Value that avoids the
157/// client having to pass in a MCExpr for constant integers.
158unsigned MCStreamer::emitULEB128IntValue(uint64_t Value, unsigned PadTo) {
159 SmallString<128> Tmp;
160 raw_svector_ostream OSE(Tmp);
161 encodeULEB128(Value, OS&: OSE, PadTo);
162 emitBytes(Data: OSE.str());
163 return Tmp.size();
164}
165
166/// EmitSLEB128IntValue - Special case of EmitSLEB128Value that avoids the
167/// client having to pass in a MCExpr for constant integers.
168unsigned MCStreamer::emitSLEB128IntValue(int64_t Value) {
169 SmallString<128> Tmp;
170 raw_svector_ostream OSE(Tmp);
171 encodeSLEB128(Value, OS&: OSE);
172 emitBytes(Data: OSE.str());
173 return Tmp.size();
174}
175
176void MCStreamer::emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc) {
177 emitValueImpl(Value, Size, Loc);
178}
179
180void MCStreamer::emitSymbolValue(const MCSymbol *Sym, unsigned Size) {
181 emitValueImpl(Value: MCSymbolRefExpr::create(Symbol: Sym, Ctx&: getContext()), Size);
182}
183
184void MCStreamer::emitDwarfSectionOffset(const MCSymbol *Sym, uint64_t Offset,
185 unsigned Size) {
186 const MCAsmInfo &MAI = getContext().getAsmInfo();
187 if (MAI.needsDwarfSectionOffsetDirective()) {
188 emitCOFFSecRel32(Symbol: Sym, Offset);
189 if (Size > 4)
190 emitZeros(NumBytes: Size - 4);
191 return;
192 }
193
194 emitValueImpl(Value: MAI.getDwarfSectionOffsetExpr(Sym, Offset, Ctx&: getContext()), Size);
195}
196
197/// Emit NumBytes bytes worth of the value specified by FillValue.
198/// This implements directives such as '.space'.
199void MCStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
200 if (NumBytes)
201 emitFill(NumBytes: *MCConstantExpr::create(Value: NumBytes, Ctx&: getContext()), FillValue);
202}
203
204void llvm::MCStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLen,
205 llvm::SMLoc, const MCSubtargetInfo& STI) {}
206
207/// The implementation in this class just redirects to emitFill.
208void MCStreamer::emitZeros(uint64_t NumBytes) { emitFill(NumBytes, FillValue: 0); }
209
210Expected<unsigned> MCStreamer::tryEmitDwarfFileDirective(
211 unsigned FileNo, StringRef Directory, StringRef Filename,
212 std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
213 unsigned CUID) {
214 return getContext().getDwarfFile(Directory, FileName: Filename, FileNumber: FileNo, Checksum,
215 Source, CUID);
216}
217
218void MCStreamer::emitDwarfFile0Directive(StringRef Directory,
219 StringRef Filename,
220 std::optional<MD5::MD5Result> Checksum,
221 std::optional<StringRef> Source,
222 unsigned CUID) {
223 getContext().setMCLineTableRootFile(CUID, CompilationDir: Directory, Filename, Checksum,
224 Source);
225}
226
227void MCStreamer::emitCFIBKeyFrame() {
228 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
229 if (!CurFrame)
230 return;
231 CurFrame->IsBKeyFrame = true;
232}
233
234void MCStreamer::emitCFIMTETaggedFrame() {
235 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
236 if (!CurFrame)
237 return;
238 CurFrame->IsMTETaggedFrame = true;
239}
240
241void MCStreamer::emitCFINonHintPAuthFrame() {
242 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
243 if (!CurFrame)
244 return;
245 CurFrame->IsNonHintPAuthFrame = true;
246}
247
248void MCStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
249 unsigned Column, unsigned Flags,
250 unsigned Isa, unsigned Discriminator,
251 StringRef FileName, StringRef Comment) {
252 getContext().setCurrentDwarfLoc(FileNum: FileNo, Line, Column, Flags, Isa,
253 Discriminator);
254}
255
256void MCStreamer::emitDwarfLocLabelDirective(SMLoc Loc, StringRef Name) {
257 getContext()
258 .getMCDwarfLineTable(CUID: getContext().getDwarfCompileUnitID())
259 .endCurrentSeqAndEmitLineStreamLabel(MCOS: this, DefLoc: Loc, Name);
260}
261
262MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) {
263 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
264 if (!Table.getLabel()) {
265 StringRef Prefix = Context.getAsmInfo().getInternalSymbolPrefix();
266 Table.setLabel(
267 Context.getOrCreateSymbol(Name: Prefix + "line_table_start" + Twine(CUID)));
268 }
269 return Table.getLabel();
270}
271
272bool MCStreamer::hasUnfinishedDwarfFrameInfo() {
273 return !FrameInfoStack.empty();
274}
275
276MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() {
277 if (!hasUnfinishedDwarfFrameInfo()) {
278 getContext().reportError(L: getStartTokLoc(),
279 Msg: "this directive must appear between "
280 ".cfi_startproc and .cfi_endproc directives");
281 return nullptr;
282 }
283 return &DwarfFrameInfos[FrameInfoStack.back().first];
284}
285
286bool MCStreamer::emitCVFileDirective(unsigned FileNo, StringRef Filename,
287 ArrayRef<uint8_t> Checksum,
288 unsigned ChecksumKind) {
289 return getContext().getCVContext().addFile(OS&: *this, FileNumber: FileNo, Filename, ChecksumBytes: Checksum,
290 ChecksumKind);
291}
292
293bool MCStreamer::emitCVFuncIdDirective(unsigned FunctionId) {
294 return getContext().getCVContext().recordFunctionId(FuncId: FunctionId);
295}
296
297bool MCStreamer::emitCVInlineSiteIdDirective(unsigned FunctionId,
298 unsigned IAFunc, unsigned IAFile,
299 unsigned IALine, unsigned IACol,
300 SMLoc Loc) {
301 if (getContext().getCVContext().getCVFunctionInfo(FuncId: IAFunc) == nullptr) {
302 getContext().reportError(L: Loc, Msg: "parent function id not introduced by "
303 ".cv_func_id or .cv_inline_site_id");
304 return true;
305 }
306
307 return getContext().getCVContext().recordInlinedCallSiteId(
308 FuncId: FunctionId, IAFunc, IAFile, IALine, IACol);
309}
310
311void MCStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
312 unsigned Line, unsigned Column,
313 bool PrologueEnd, bool IsStmt,
314 StringRef FileName, SMLoc Loc) {}
315
316bool MCStreamer::checkCVLocSection(unsigned FuncId, SMLoc Loc) {
317 CodeViewContext &CVC = getContext().getCVContext();
318 MCCVFunctionInfo *FI = CVC.getCVFunctionInfo(FuncId);
319 if (!FI) {
320 getContext().reportError(
321 L: Loc, Msg: "function id not introduced by .cv_func_id or .cv_inline_site_id");
322 return false;
323 }
324
325 // Track the section
326 if (FI->Section == nullptr)
327 FI->Section = getCurrentSectionOnly();
328 else if (FI->Section != getCurrentSectionOnly()) {
329 getContext().reportError(
330 L: Loc,
331 Msg: "all .cv_loc directives for a function must be in the same section");
332 return false;
333 }
334 return true;
335}
336
337void MCStreamer::emitCVLinetableDirective(unsigned FunctionId,
338 const MCSymbol *Begin,
339 const MCSymbol *End) {}
340
341void MCStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
342 unsigned SourceFileId,
343 unsigned SourceLineNum,
344 const MCSymbol *FnStartSym,
345 const MCSymbol *FnEndSym) {}
346
347/// Only call this on endian-specific types like ulittle16_t and little32_t, or
348/// structs composed of them.
349template <typename T>
350static void copyBytesForDefRange(SmallString<20> &BytePrefix,
351 codeview::SymbolKind SymKind,
352 const T &DefRangeHeader) {
353 BytePrefix.resize(N: 2 + sizeof(T));
354 codeview::ulittle16_t SymKindLE = codeview::ulittle16_t(SymKind);
355 memcpy(dest: &BytePrefix[0], src: &SymKindLE, n: 2);
356 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
357}
358
359void MCStreamer::emitCVDefRangeDirective(
360 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
361 StringRef FixedSizePortion) {}
362
363void MCStreamer::emitCVDefRangeDirective(
364 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
365 codeview::DefRangeRegisterRelHeader DRHdr) {
366 SmallString<20> BytePrefix;
367 copyBytesForDefRange(BytePrefix, SymKind: codeview::S_DEFRANGE_REGISTER_REL, DefRangeHeader: DRHdr);
368 emitCVDefRangeDirective(Ranges, FixedSizePortion: BytePrefix);
369}
370
371void MCStreamer::emitCVDefRangeDirective(
372 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
373 codeview::DefRangeSubfieldRegisterHeader DRHdr) {
374 SmallString<20> BytePrefix;
375 copyBytesForDefRange(BytePrefix, SymKind: codeview::S_DEFRANGE_SUBFIELD_REGISTER,
376 DefRangeHeader: DRHdr);
377 emitCVDefRangeDirective(Ranges, FixedSizePortion: BytePrefix);
378}
379
380void MCStreamer::emitCVDefRangeDirective(
381 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
382 codeview::DefRangeRegisterHeader DRHdr) {
383 SmallString<20> BytePrefix;
384 copyBytesForDefRange(BytePrefix, SymKind: codeview::S_DEFRANGE_REGISTER, DefRangeHeader: DRHdr);
385 emitCVDefRangeDirective(Ranges, FixedSizePortion: BytePrefix);
386}
387
388void MCStreamer::emitCVDefRangeDirective(
389 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
390 codeview::DefRangeFramePointerRelHeader DRHdr) {
391 SmallString<20> BytePrefix;
392 copyBytesForDefRange(BytePrefix, SymKind: codeview::S_DEFRANGE_FRAMEPOINTER_REL,
393 DefRangeHeader: DRHdr);
394 emitCVDefRangeDirective(Ranges, FixedSizePortion: BytePrefix);
395}
396
397void MCStreamer::emitCVDefRangeDirective(
398 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
399 codeview::DefRangeRegisterRelIndirHeader DRHdr) {
400 SmallString<20> BytePrefix;
401 copyBytesForDefRange(BytePrefix, SymKind: codeview::S_DEFRANGE_REGISTER_REL_INDIR,
402 DefRangeHeader: DRHdr);
403 emitCVDefRangeDirective(Ranges, FixedSizePortion: BytePrefix);
404}
405
406void MCStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
407 MCSymbol *EHSymbol) {
408}
409
410void MCStreamer::initSections(const MCSubtargetInfo &STI) {
411 switchSectionNoPrint(Section: getContext().getObjectFileInfo()->getTextSection());
412}
413
414void MCStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
415 Symbol->redefineIfPossible();
416
417 if (!Symbol->isUndefined() || Symbol->isVariable())
418 return getContext().reportError(L: Loc, Msg: "symbol '" + Twine(Symbol->getName()) +
419 "' is already defined");
420
421 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
422 assert(getCurrentSectionOnly() && "Cannot emit before setting section!");
423 assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
424 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
425
426 Symbol->setFragment(&getCurrentSectionOnly()->getDummyFragment());
427
428 if (LFIRewriter)
429 LFIRewriter->onLabel(Symbol, Out&: *this);
430
431 MCTargetStreamer *TS = getTargetStreamer();
432 if (TS)
433 TS->emitLabel(Symbol);
434}
435
436void MCStreamer::emitConditionalAssignment(MCSymbol *Symbol,
437 const MCExpr *Value) {}
438
439void MCStreamer::emitCFISections(bool EH, bool Debug, bool SFrame) {}
440
441void MCStreamer::emitCFIStartProc(bool IsSimple, SMLoc Loc) {
442 if (!FrameInfoStack.empty() &&
443 getCurrentSectionOnly() == FrameInfoStack.back().second)
444 return getContext().reportError(
445 L: Loc, Msg: "starting new .cfi frame before finishing the previous one");
446
447 MCDwarfFrameInfo Frame;
448 Frame.IsSimple = IsSimple;
449 emitCFIStartProcImpl(Frame);
450
451 const MCAsmInfo &MAI = Context.getAsmInfo();
452 for (const MCCFIInstruction &Inst : MAI.getInitialFrameState()) {
453 if (Inst.getOperation() == MCCFIInstruction::OpDefCfa ||
454 Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister ||
455 Inst.getOperation() == MCCFIInstruction::OpLLVMDefAspaceCfa) {
456 Frame.CurrentCfaRegister = Inst.getRegister();
457 }
458 }
459
460 FrameInfoStack.emplace_back(Args: DwarfFrameInfos.size(), Args: getCurrentSectionOnly());
461 DwarfFrameInfos.push_back(Elt: std::move(Frame));
462}
463
464void MCStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
465}
466
467void MCStreamer::emitCFIEndProc() {
468 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
469 if (!CurFrame)
470 return;
471 emitCFIEndProcImpl(CurFrame&: *CurFrame);
472 FrameInfoStack.pop_back();
473}
474
475void MCStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
476 // Put a dummy non-null value in Frame.End to mark that this frame has been
477 // closed.
478 Frame.End = (MCSymbol *)1;
479}
480
481MCSymbol *MCStreamer::emitLineTableLabel() {
482 // Create a label and insert it into the line table and return this label
483 const MCDwarfLoc &DwarfLoc = getContext().getCurrentDwarfLoc();
484
485 MCSymbol *LineStreamLabel = getContext().createTempSymbol();
486 MCDwarfLineEntry LabelLineEntry(nullptr, DwarfLoc, LineStreamLabel);
487 getContext()
488 .getMCDwarfLineTable(CUID: getContext().getDwarfCompileUnitID())
489 .getMCLineSections()
490 .addLineEntry(LineEntry: LabelLineEntry, Sec: getCurrentSectionOnly() /*Section*/);
491
492 return LineStreamLabel;
493}
494
495MCSymbol *MCStreamer::emitCFILabel() {
496 // Return a dummy non-null value so that label fields appear filled in when
497 // generating textual assembly.
498 return (MCSymbol *)1;
499}
500
501void MCStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset, SMLoc Loc) {
502 MCSymbol *Label = emitCFILabel();
503 MCCFIInstruction Instruction =
504 MCCFIInstruction::cfiDefCfa(L: Label, Register, Offset, Loc);
505 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
506 if (!CurFrame)
507 return;
508 CurFrame->Instructions.push_back(x: std::move(Instruction));
509 CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
510}
511
512void MCStreamer::emitCFIDefCfaOffset(int64_t Offset, SMLoc Loc) {
513 MCSymbol *Label = emitCFILabel();
514 MCCFIInstruction Instruction =
515 MCCFIInstruction::cfiDefCfaOffset(L: Label, Offset);
516 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
517 if (!CurFrame)
518 return;
519 CurFrame->Instructions.push_back(x: std::move(Instruction));
520}
521
522void MCStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment, SMLoc Loc) {
523 MCSymbol *Label = emitCFILabel();
524 MCCFIInstruction Instruction =
525 MCCFIInstruction::createAdjustCfaOffset(L: Label, Adjustment, Loc);
526 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
527 if (!CurFrame)
528 return;
529 CurFrame->Instructions.push_back(x: std::move(Instruction));
530}
531
532void MCStreamer::emitCFIDefCfaRegister(int64_t Register, SMLoc Loc) {
533 MCSymbol *Label = emitCFILabel();
534 MCCFIInstruction Instruction =
535 MCCFIInstruction::createDefCfaRegister(L: Label, Register, Loc);
536 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
537 if (!CurFrame)
538 return;
539 CurFrame->Instructions.push_back(x: std::move(Instruction));
540 CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
541}
542
543void MCStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
544 int64_t AddressSpace, SMLoc Loc) {
545 MCSymbol *Label = emitCFILabel();
546 MCCFIInstruction Instruction = MCCFIInstruction::createLLVMDefAspaceCfa(
547 L: Label, Register, Offset, AddressSpace, Loc);
548 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
549 if (!CurFrame)
550 return;
551 CurFrame->Instructions.push_back(x: std::move(Instruction));
552 CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
553}
554
555void MCStreamer::emitCFIOffset(int64_t Register, int64_t Offset, SMLoc Loc) {
556 MCSymbol *Label = emitCFILabel();
557 MCCFIInstruction Instruction =
558 MCCFIInstruction::createOffset(L: Label, Register, Offset, Loc);
559 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
560 if (!CurFrame)
561 return;
562 CurFrame->Instructions.push_back(x: std::move(Instruction));
563}
564
565void MCStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset, SMLoc Loc) {
566 MCSymbol *Label = emitCFILabel();
567 MCCFIInstruction Instruction =
568 MCCFIInstruction::createRelOffset(L: Label, Register, Offset, Loc);
569 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
570 if (!CurFrame)
571 return;
572 CurFrame->Instructions.push_back(x: std::move(Instruction));
573}
574
575void MCStreamer::emitCFIPersonality(const MCSymbol *Sym,
576 unsigned Encoding) {
577 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
578 if (!CurFrame)
579 return;
580 CurFrame->Personality = Sym;
581 CurFrame->PersonalityEncoding = Encoding;
582}
583
584void MCStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
585 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
586 if (!CurFrame)
587 return;
588 CurFrame->Lsda = Sym;
589 CurFrame->LsdaEncoding = Encoding;
590}
591
592void MCStreamer::emitCFIRememberState(SMLoc Loc) {
593 MCSymbol *Label = emitCFILabel();
594 MCCFIInstruction Instruction =
595 MCCFIInstruction::createRememberState(L: Label, Loc);
596 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
597 if (!CurFrame)
598 return;
599 ++CurFrame->RememberStateDepth;
600 CurFrame->Instructions.push_back(x: std::move(Instruction));
601}
602
603void MCStreamer::emitCFIRestoreState(SMLoc Loc) {
604 MCSymbol *Label = emitCFILabel();
605 MCCFIInstruction Instruction =
606 MCCFIInstruction::createRestoreState(L: Label, Loc);
607 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
608 if (!CurFrame)
609 return;
610 if (!CurFrame->RememberStateDepth) {
611 getContext().reportError(L: Loc, Msg: "no matching .cfi_remember_state");
612 return;
613 }
614 --CurFrame->RememberStateDepth;
615 CurFrame->Instructions.push_back(x: std::move(Instruction));
616}
617
618void MCStreamer::emitCFISameValue(int64_t Register, SMLoc Loc) {
619 MCSymbol *Label = emitCFILabel();
620 MCCFIInstruction Instruction =
621 MCCFIInstruction::createSameValue(L: Label, Register, Loc);
622 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
623 if (!CurFrame)
624 return;
625 CurFrame->Instructions.push_back(x: std::move(Instruction));
626}
627
628void MCStreamer::emitCFIRestore(int64_t Register, SMLoc Loc) {
629 MCSymbol *Label = emitCFILabel();
630 MCCFIInstruction Instruction =
631 MCCFIInstruction::createRestore(L: Label, Register, Loc);
632 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
633 if (!CurFrame)
634 return;
635 CurFrame->Instructions.push_back(x: std::move(Instruction));
636}
637
638void MCStreamer::emitCFIEscape(StringRef Values, SMLoc Loc) {
639 MCSymbol *Label = emitCFILabel();
640 MCCFIInstruction Instruction =
641 MCCFIInstruction::createEscape(L: Label, Vals: Values, Loc, Comment: "");
642 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
643 if (!CurFrame)
644 return;
645 CurFrame->Instructions.push_back(x: std::move(Instruction));
646}
647
648void MCStreamer::emitCFIGnuArgsSize(int64_t Size, SMLoc Loc) {
649 MCSymbol *Label = emitCFILabel();
650 MCCFIInstruction Instruction =
651 MCCFIInstruction::createGnuArgsSize(L: Label, Size, Loc);
652 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
653 if (!CurFrame)
654 return;
655 CurFrame->Instructions.push_back(x: std::move(Instruction));
656}
657
658void MCStreamer::emitCFILLVMRegisterPair(int64_t Register, int64_t R1,
659 int64_t R1Size, int64_t R2,
660 int64_t R2Size, SMLoc Loc) {
661 MCSymbol *Label = emitCFILabel();
662 MCCFIInstruction Instruction = MCCFIInstruction::createLLVMRegisterPair(
663 L: Label, Register, R1, R1SizeInBits: R1Size, R2, R2SizeInBits: R2Size, Loc);
664 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
665 if (!CurFrame)
666 return;
667 CurFrame->Instructions.push_back(x: std::move(Instruction));
668}
669
670void MCStreamer::emitCFILLVMVectorRegisters(
671 int64_t Register, ArrayRef<MCCFIInstruction::VectorRegisterWithLane> VRs,
672 SMLoc Loc) {
673 MCSymbol *Label = emitCFILabel();
674 MCCFIInstruction Instruction =
675 MCCFIInstruction::createLLVMVectorRegisters(L: Label, Register, VectorRegisters: VRs, Loc);
676 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
677 if (!CurFrame)
678 return;
679 CurFrame->Instructions.push_back(x: std::move(Instruction));
680}
681
682void MCStreamer::emitCFILLVMVectorOffset(int64_t Register,
683 int64_t RegisterSizeInBits,
684 int64_t MaskRegister,
685 int64_t MaskRegisterSizeInBits,
686 int64_t Offset, SMLoc Loc) {
687 MCSymbol *Label = emitCFILabel();
688 MCCFIInstruction Instruction = MCCFIInstruction::createLLVMVectorOffset(
689 L: Label, Register, RegisterSizeInBits, MaskRegister, MaskRegisterSizeInBits,
690 Offset, Loc);
691 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
692 if (!CurFrame)
693 return;
694 CurFrame->Instructions.push_back(x: std::move(Instruction));
695}
696
697void MCStreamer::emitCFILLVMVectorRegisterMask(
698 int64_t Register, int64_t SpillRegister,
699 int64_t SpillRegisterLaneSizeInBits, int64_t MaskRegister,
700 int64_t MaskRegisterSizeInBits, SMLoc Loc) {
701
702 MCSymbol *Label = emitCFILabel();
703 MCCFIInstruction Instruction = MCCFIInstruction::createLLVMVectorRegisterMask(
704 L: Label, Register, SpillRegister, SpillRegisterLaneSizeInBits, MaskRegister,
705 MaskRegisterSizeInBits, Loc);
706 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
707 if (!CurFrame)
708 return;
709 CurFrame->Instructions.push_back(x: std::move(Instruction));
710}
711
712void MCStreamer::emitCFISignalFrame() {
713 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
714 if (!CurFrame)
715 return;
716 CurFrame->IsSignalFrame = true;
717}
718
719void MCStreamer::emitCFIUndefined(int64_t Register, SMLoc Loc) {
720 MCSymbol *Label = emitCFILabel();
721 MCCFIInstruction Instruction =
722 MCCFIInstruction::createUndefined(L: Label, Register, Loc);
723 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
724 if (!CurFrame)
725 return;
726 CurFrame->Instructions.push_back(x: std::move(Instruction));
727}
728
729void MCStreamer::emitCFIRegister(int64_t Register1, int64_t Register2,
730 SMLoc Loc) {
731 MCSymbol *Label = emitCFILabel();
732 MCCFIInstruction Instruction =
733 MCCFIInstruction::createRegister(L: Label, Register1, Register2, Loc);
734 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
735 if (!CurFrame)
736 return;
737 CurFrame->Instructions.push_back(x: std::move(Instruction));
738}
739
740void MCStreamer::emitCFIWindowSave(SMLoc Loc) {
741 MCSymbol *Label = emitCFILabel();
742 MCCFIInstruction Instruction = MCCFIInstruction::createWindowSave(L: Label, Loc);
743 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
744 if (!CurFrame)
745 return;
746 CurFrame->Instructions.push_back(x: std::move(Instruction));
747}
748
749void MCStreamer::emitCFINegateRAState(SMLoc Loc) {
750 MCSymbol *Label = emitCFILabel();
751 MCCFIInstruction Instruction =
752 MCCFIInstruction::createNegateRAState(L: Label, Loc);
753 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
754 if (!CurFrame)
755 return;
756 CurFrame->Instructions.push_back(x: std::move(Instruction));
757}
758
759void MCStreamer::emitCFINegateRAStateWithPC(SMLoc Loc) {
760 MCSymbol *Label = emitCFILabel();
761 MCCFIInstruction Instruction =
762 MCCFIInstruction::createNegateRAStateWithPC(L: Label, Loc);
763 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
764 if (!CurFrame)
765 return;
766 CurFrame->Instructions.push_back(x: std::move(Instruction));
767}
768
769void MCStreamer::emitCFILLVMSetRAState(unsigned State, MCSymbol *PACSym,
770 SMLoc Loc) {
771 MCSymbol *Label = emitCFILabel();
772 MCCFIInstruction Instruction =
773 MCCFIInstruction::createSetRAState(L: Label, State, PACSym, Loc);
774 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
775 if (!CurFrame)
776 return;
777 CurFrame->Instructions.push_back(x: std::move(Instruction));
778}
779
780void MCStreamer::emitCFILLVMSetRAState(unsigned State, int64_t Offset,
781 SMLoc Loc) {
782 MCSymbol *Label = emitCFILabel();
783 MCCFIInstruction Instruction =
784 MCCFIInstruction::createSetRAState(L: Label, State, Offset, Loc);
785 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
786 if (!CurFrame)
787 return;
788 CurFrame->Instructions.push_back(x: std::move(Instruction));
789}
790
791void MCStreamer::emitCFIReturnColumn(int64_t Register) {
792 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
793 if (!CurFrame)
794 return;
795 CurFrame->RAReg = Register;
796}
797
798void MCStreamer::emitCFILabelDirective(SMLoc Loc, StringRef Name) {
799 MCSymbol *Label = emitCFILabel();
800 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
801 if (MCDwarfFrameInfo *F = getCurrentDwarfFrameInfo())
802 F->Instructions.push_back(x: MCCFIInstruction::createLabel(L: Label, CfiLabel: Sym, Loc));
803}
804
805void MCStreamer::emitCFIValOffset(int64_t Register, int64_t Offset, SMLoc Loc) {
806 MCSymbol *Label = emitCFILabel();
807 MCCFIInstruction Instruction =
808 MCCFIInstruction::createValOffset(L: Label, Register, Offset, Loc);
809 MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
810 if (!CurFrame)
811 return;
812 CurFrame->Instructions.push_back(x: std::move(Instruction));
813}
814
815WinEH::FrameInfo *MCStreamer::EnsureValidWinFrameInfo(SMLoc Loc) {
816 const MCAsmInfo &MAI = Context.getAsmInfo();
817 if (!MAI.usesWindowsCFI()) {
818 getContext().reportError(
819 L: Loc, Msg: ".seh_* directives are not supported on this target");
820 return nullptr;
821 }
822 if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) {
823 getContext().reportError(
824 L: Loc, Msg: ".seh_ directive must appear within an active frame");
825 return nullptr;
826 }
827 return CurrentWinFrameInfo;
828}
829
830void MCStreamer::emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
831 const MCAsmInfo &MAI = Context.getAsmInfo();
832 if (!MAI.usesWindowsCFI())
833 return getContext().reportError(
834 L: Loc, Msg: ".seh_* directives are not supported on this target");
835 if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End)
836 getContext().reportError(
837 L: Loc, Msg: "Starting a function before ending the previous one!");
838
839 MCSymbol *StartProc = emitCFILabel();
840
841 CurrentProcWinFrameInfoStartIndex = WinFrameInfos.size();
842 WinFrameInfos.emplace_back(
843 args: std::make_unique<WinEH::FrameInfo>(args&: Symbol, args&: StartProc));
844 CurrentWinFrameInfo = WinFrameInfos.back().get();
845 CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
846 CurrentWinFrameInfo->FunctionLoc = Loc;
847 // Inherit the module-wide default unwind version.
848 CurrentWinFrameInfo->Version = DefaultWinCFIUnwindVersion;
849}
850
851void MCStreamer::emitWinCFIEndProc(SMLoc Loc) {
852 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
853 if (!CurFrame)
854 return;
855 CurrentWinFrameInfo = nullptr;
856
857 MCSymbol *Label = emitCFILabel();
858 CurFrame->End = Label;
859 const MCSymbol **FuncletOrFuncEndPtr =
860 CurFrame->ChainedParent ? &CurFrame->ChainedParent->FuncletOrFuncEnd
861 : &CurFrame->FuncletOrFuncEnd;
862 if (!*FuncletOrFuncEndPtr)
863 *FuncletOrFuncEndPtr = CurFrame->End;
864
865 if (CurrentWinEpilog) {
866 // Set End to... something... to prevent crashes later.
867 CurrentWinEpilog->End = emitCFILabel();
868 CurrentWinEpilog = nullptr;
869 getContext().reportError(L: Loc, Msg: "Missing .seh_endepilogue in " +
870 CurFrame->Function->getName());
871 }
872
873 for (size_t I = CurrentProcWinFrameInfoStartIndex, E = WinFrameInfos.size();
874 I != E; ++I)
875 emitWindowsUnwindTables(Frame: WinFrameInfos[I].get());
876 switchSection(Section: CurFrame->TextSection);
877}
878
879void MCStreamer::emitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
880 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
881 if (!CurFrame)
882 return;
883
884 MCSymbol *Label = emitCFILabel();
885 const MCSymbol **FuncletOrFuncEndPtr =
886 CurFrame->ChainedParent ? &CurFrame->ChainedParent->FuncletOrFuncEnd
887 : &CurFrame->FuncletOrFuncEnd;
888 *FuncletOrFuncEndPtr = Label;
889}
890
891void MCStreamer::emitWinCFISplitChained(SMLoc Loc) {
892 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
893 if (!CurFrame)
894 return;
895
896 if (!CurFrame->PrologEnd)
897 return getContext().reportError(
898 L: Loc, Msg: "can't split into a new chained region (.seh_splitchained) in the "
899 "middle of a prolog in " +
900 CurFrame->Function->getName());
901
902 MCSymbol *Label = emitCFILabel();
903
904 // Complete the current frame before starting a new, chained one.
905 CurFrame->End = Label;
906
907 // All chained frames point to the same parent.
908 WinEH::FrameInfo *ChainedParent =
909 CurFrame->ChainedParent ? CurFrame->ChainedParent : CurFrame;
910
911 WinFrameInfos.emplace_back(args: std::make_unique<WinEH::FrameInfo>(
912 args&: CurFrame->Function, args&: Label, args&: ChainedParent));
913 CurrentWinFrameInfo = WinFrameInfos.back().get();
914 CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
915}
916
917void MCStreamer::emitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
918 SMLoc Loc) {
919 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
920 if (!CurFrame)
921 return;
922
923 // Handlers are always associated with the parent frame.
924 CurFrame = CurFrame->ChainedParent ? CurFrame->ChainedParent : CurFrame;
925
926 CurFrame->ExceptionHandler = Sym;
927 if (!Except && !Unwind)
928 getContext().reportError(L: Loc, Msg: "Don't know what kind of handler this is!");
929 if (Unwind)
930 CurFrame->HandlesUnwind = true;
931 if (Except)
932 CurFrame->HandlesExceptions = true;
933}
934
935void MCStreamer::emitWinEHHandlerData(SMLoc Loc) {
936 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
937 if (!CurFrame)
938 return;
939}
940
941void MCStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
942 const MCSymbolRefExpr *To, uint64_t Count) {
943}
944
945static MCSection *getWinCFISection(MCContext &Context, unsigned *NextWinCFIID,
946 MCSection *MainCFISec,
947 const MCSection *TextSec) {
948 // If this is the main .text section, use the main unwind info section.
949 if (TextSec == Context.getObjectFileInfo()->getTextSection())
950 return MainCFISec;
951
952 const auto *TextSecCOFF = static_cast<const MCSectionCOFF *>(TextSec);
953 auto *MainCFISecCOFF = static_cast<MCSectionCOFF *>(MainCFISec);
954 unsigned UniqueID = TextSecCOFF->getOrAssignWinCFISectionID(NextID: NextWinCFIID);
955
956 // If this section is COMDAT, this unwind section should be COMDAT associative
957 // with its group.
958 const MCSymbol *KeySym = nullptr;
959 if (TextSecCOFF->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
960 KeySym = TextSecCOFF->getCOMDATSymbol();
961
962 // In a GNU environment, we can't use associative comdats. Instead, do what
963 // GCC does, which is to make plain comdat selectany section named like
964 // ".[px]data$_Z3foov".
965 if (!Context.getAsmInfo().hasCOFFAssociativeComdats()) {
966 std::string SectionName = (MainCFISecCOFF->getName() + "$" +
967 TextSecCOFF->getName().split(Separator: '$').second)
968 .str();
969 return Context.getCOFFSection(Section: SectionName,
970 Characteristics: MainCFISecCOFF->getCharacteristics() |
971 COFF::IMAGE_SCN_LNK_COMDAT,
972 COMDATSymName: "", Selection: COFF::IMAGE_COMDAT_SELECT_ANY);
973 }
974 }
975
976 return Context.getAssociativeCOFFSection(Sec: MainCFISecCOFF, KeySym, UniqueID);
977}
978
979MCSection *MCStreamer::getAssociatedPDataSection(const MCSection *TextSec) {
980 return getWinCFISection(Context&: getContext(), NextWinCFIID: &NextWinCFIID,
981 MainCFISec: getContext().getObjectFileInfo()->getPDataSection(),
982 TextSec);
983}
984
985MCSection *MCStreamer::getAssociatedXDataSection(const MCSection *TextSec) {
986 return getWinCFISection(Context&: getContext(), NextWinCFIID: &NextWinCFIID,
987 MainCFISec: getContext().getObjectFileInfo()->getXDataSection(),
988 TextSec);
989}
990
991void MCStreamer::emitSyntaxDirective(StringRef Syntax, StringRef Options) {}
992
993static unsigned encodeSEHRegNum(MCContext &Ctx, MCRegister Reg) {
994 return Ctx.getRegisterInfo()->getSEHRegNum(Reg);
995}
996
997// Unwind formats before v3 store the register operand of an unwind code in a
998// 4-bit field, so extended registers (r16-r31 / xmm16-xmm31, i.e. SEH register
999// numbers greater than 15) cannot be represented. Report an error rather than
1000// silently truncating the register number to a different register. Returns true
1001// if an error was reported.
1002static bool checkUnwindV3ExtendedReg(MCContext &Ctx,
1003 const WinEH::Instruction &Inst,
1004 uint8_t Version, SMLoc Loc,
1005 StringRef Directive) {
1006 if (Version < 3 && Inst.Register > 15) {
1007 Ctx.reportError(L: Loc, Msg: Directive +
1008 " with an extended register requires unwind v3");
1009 return true;
1010 }
1011 return false;
1012}
1013
1014void MCStreamer::emitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
1015 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1016 if (!CurFrame)
1017 return;
1018
1019 MCSymbol *Label = emitCFILabel();
1020
1021 WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(
1022 L: Label, Reg: encodeSEHRegNum(Ctx&: Context, Reg: Register));
1023 if (CurrentWinEpilog) {
1024 if (CurFrame->Version < 3)
1025 return getContext().reportError(
1026 L: Loc, Msg: ".seh_pushreg inside epilog requires unwind v3");
1027 CurrentWinEpilog->Instructions.push_back(x: Inst);
1028 } else {
1029 if (checkUnwindV3ExtendedReg(Ctx&: getContext(), Inst, Version: CurFrame->Version, Loc,
1030 Directive: ".seh_pushreg"))
1031 return;
1032 CurFrame->Instructions.push_back(x: Inst);
1033 }
1034}
1035
1036void MCStreamer::emitWinCFIPush2Regs(MCRegister Reg1, MCRegister Reg2,
1037 SMLoc Loc) {
1038 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1039 if (!CurFrame)
1040 return;
1041
1042 // UOP_Push2 is V3-only - reject for V1/V2.
1043 if (CurFrame->Version < 3)
1044 return getContext().reportError(
1045 L: Loc, Msg: ".seh_push2regs is only supported for unwind v3");
1046
1047 MCSymbol *Label = emitCFILabel();
1048
1049 WinEH::Instruction Inst = Win64EH::Instruction::Push2(
1050 L: Label, Reg1: encodeSEHRegNum(Ctx&: Context, Reg: Reg1), Reg2: encodeSEHRegNum(Ctx&: Context, Reg: Reg2));
1051 if (CurrentWinEpilog)
1052 CurrentWinEpilog->Instructions.push_back(x: Inst);
1053 else
1054 CurFrame->Instructions.push_back(x: Inst);
1055}
1056
1057void MCStreamer::emitWinCFISetFrame(MCRegister Register, unsigned Offset,
1058 SMLoc Loc) {
1059 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1060 if (!CurFrame)
1061 return;
1062 if (!CurrentWinEpilog && CurFrame->LastFrameInst >= 0)
1063 return getContext().reportError(
1064 L: Loc, Msg: "frame register and offset can be set at most once");
1065 if (Offset & 0x0F)
1066 return getContext().reportError(L: Loc, Msg: "offset is not a multiple of 16");
1067 if (Offset > 240)
1068 return getContext().reportError(
1069 L: Loc, Msg: "frame offset must be less than or equal to 240");
1070
1071 MCSymbol *Label = emitCFILabel();
1072
1073 WinEH::Instruction Inst = Win64EH::Instruction::SetFPReg(
1074 L: Label, Reg: encodeSEHRegNum(Ctx&: getContext(), Reg: Register), Off: Offset);
1075 if (CurrentWinEpilog) {
1076 if (CurFrame->Version < 3)
1077 return getContext().reportError(
1078 L: Loc, Msg: ".seh_setframe inside epilog requires unwind v3");
1079 CurrentWinEpilog->Instructions.push_back(x: Inst);
1080 } else {
1081 if (checkUnwindV3ExtendedReg(Ctx&: getContext(), Inst, Version: CurFrame->Version, Loc,
1082 Directive: ".seh_setframe"))
1083 return;
1084 CurFrame->LastFrameInst = CurFrame->Instructions.size();
1085 CurFrame->Instructions.push_back(x: Inst);
1086 }
1087}
1088
1089void MCStreamer::emitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1090 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1091 if (!CurFrame)
1092 return;
1093 if (Size == 0)
1094 return getContext().reportError(L: Loc,
1095 Msg: "stack allocation size must be non-zero");
1096 if (Size & 7)
1097 return getContext().reportError(
1098 L: Loc, Msg: "stack allocation size is not a multiple of 8");
1099
1100 MCSymbol *Label = emitCFILabel();
1101
1102 WinEH::Instruction Inst = Win64EH::Instruction::Alloc(L: Label, Size);
1103 if (CurrentWinEpilog) {
1104 if (CurFrame->Version < 3)
1105 return getContext().reportError(
1106 L: Loc, Msg: ".seh_stackalloc inside epilog requires unwind v3");
1107 CurrentWinEpilog->Instructions.push_back(x: Inst);
1108 } else {
1109 CurFrame->Instructions.push_back(x: Inst);
1110 }
1111}
1112
1113void MCStreamer::emitWinCFISaveReg(MCRegister Register, unsigned Offset,
1114 SMLoc Loc) {
1115 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1116 if (!CurFrame)
1117 return;
1118
1119 if (Offset & 7)
1120 return getContext().reportError(
1121 L: Loc, Msg: "register save offset is not 8 byte aligned");
1122
1123 MCSymbol *Label = emitCFILabel();
1124
1125 WinEH::Instruction Inst = Win64EH::Instruction::SaveNonVol(
1126 L: Label, Reg: encodeSEHRegNum(Ctx&: Context, Reg: Register), Offset);
1127 if (CurrentWinEpilog) {
1128 if (CurFrame->Version < 3)
1129 return getContext().reportError(
1130 L: Loc, Msg: ".seh_savereg inside epilog requires unwind v3");
1131 CurrentWinEpilog->Instructions.push_back(x: Inst);
1132 } else {
1133 if (checkUnwindV3ExtendedReg(Ctx&: getContext(), Inst, Version: CurFrame->Version, Loc,
1134 Directive: ".seh_savereg"))
1135 return;
1136 CurFrame->Instructions.push_back(x: Inst);
1137 }
1138}
1139
1140void MCStreamer::emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
1141 SMLoc Loc) {
1142 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1143 if (!CurFrame)
1144 return;
1145 if (Offset & 0x0F)
1146 return getContext().reportError(L: Loc, Msg: "offset is not a multiple of 16");
1147
1148 MCSymbol *Label = emitCFILabel();
1149
1150 WinEH::Instruction Inst = Win64EH::Instruction::SaveXMM(
1151 L: Label, Reg: encodeSEHRegNum(Ctx&: Context, Reg: Register), Offset);
1152 if (CurrentWinEpilog) {
1153 if (CurFrame->Version < 3)
1154 return getContext().reportError(
1155 L: Loc, Msg: ".seh_savexmm inside epilog requires unwind v3");
1156 CurrentWinEpilog->Instructions.push_back(x: Inst);
1157 } else {
1158 if (checkUnwindV3ExtendedReg(Ctx&: getContext(), Inst, Version: CurFrame->Version, Loc,
1159 Directive: ".seh_savexmm"))
1160 return;
1161 CurFrame->Instructions.push_back(x: Inst);
1162 }
1163}
1164
1165void MCStreamer::emitWinCFIPushFrame(bool Code, SMLoc Loc) {
1166 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1167 if (!CurFrame)
1168 return;
1169 if (CurrentWinEpilog) {
1170 if (CurFrame->Version < 3)
1171 return getContext().reportError(
1172 L: Loc, Msg: ".seh_pushframe inside epilog requires unwind v3");
1173 MCSymbol *Label = emitCFILabel();
1174 WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(L: Label, Code);
1175 CurrentWinEpilog->Instructions.push_back(x: Inst);
1176 return;
1177 }
1178 if (!CurFrame->Instructions.empty())
1179 return getContext().reportError(
1180 L: Loc, Msg: "If present, PushMachFrame must be the first UOP");
1181
1182 MCSymbol *Label = emitCFILabel();
1183
1184 WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(L: Label, Code);
1185 CurFrame->Instructions.push_back(x: Inst);
1186}
1187
1188void MCStreamer::emitWinCFIEndProlog(SMLoc Loc) {
1189 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1190 if (!CurFrame)
1191 return;
1192
1193 MCSymbol *Label = emitCFILabel();
1194
1195 CurFrame->PrologEnd = Label;
1196}
1197
1198void MCStreamer::emitWinCFIBeginEpilogue(SMLoc Loc) {
1199 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1200 if (!CurFrame)
1201 return;
1202
1203 MCSymbol *Label = emitCFILabel();
1204
1205 if (!CurFrame->PrologEnd) {
1206 CurFrame->PrologEnd = Label;
1207 getContext().reportError(
1208 L: Loc, Msg: "starting epilogue (.seh_startepilogue) before prologue has ended "
1209 "(.seh_endprologue) in " +
1210 CurFrame->Function->getName());
1211 }
1212 CurrentWinEpilog =
1213 &CurFrame->EpilogMap.insert_or_assign(Key: Label, Val: WinEH::FrameInfo::Epilog())
1214 .first->second;
1215 CurrentWinEpilog->Start = Label;
1216 CurrentWinEpilog->Loc = Loc;
1217}
1218
1219void MCStreamer::emitWinCFIEndEpilogue(SMLoc Loc) {
1220 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1221 if (!CurFrame)
1222 return;
1223
1224 if (!CurrentWinEpilog)
1225 return getContext().reportError(L: Loc, Msg: "Stray .seh_endepilogue in " +
1226 CurFrame->Function->getName());
1227
1228 if ((CurFrame->Version == 2) && !CurrentWinEpilog->UnwindV2Start) {
1229 // Set UnwindV2Start to... something... to prevent crashes later.
1230 CurrentWinEpilog->UnwindV2Start = CurrentWinEpilog->Start;
1231 getContext().reportError(L: Loc, Msg: "Missing .seh_unwindv2start in " +
1232 CurFrame->Function->getName());
1233 }
1234
1235 CurrentWinEpilog->End = emitCFILabel();
1236 CurrentWinEpilog = nullptr;
1237}
1238
1239void MCStreamer::emitWinCFIUnwindV2Start(SMLoc Loc) {
1240 WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
1241 if (!CurFrame)
1242 return;
1243
1244 if (!CurrentWinEpilog)
1245 return getContext().reportError(L: Loc, Msg: "Stray .seh_unwindv2start in " +
1246 CurFrame->Function->getName());
1247
1248 if (CurrentWinEpilog->UnwindV2Start)
1249 return getContext().reportError(L: Loc, Msg: "Duplicate .seh_unwindv2start in " +
1250 CurFrame->Function->getName());
1251
1252 MCSymbol *Label = emitCFILabel();
1253 CurrentWinEpilog->UnwindV2Start = Label;
1254}
1255
1256void MCStreamer::emitWinCFIUnwindVersion(uint8_t Version, SMLoc Loc) {
1257 bool SupportedVersion = (Version >= 1 && Version <= 3);
1258
1259 // If called outside a proc, set the module-level default.
1260 if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) {
1261 if (!SupportedVersion)
1262 return getContext().reportError(
1263 L: Loc, Msg: "Unsupported version for .seh_unwindversion");
1264 setDefaultWinCFIUnwindVersion(Version);
1265 return;
1266 }
1267
1268 // Per-function override (existing behaviour).
1269 WinEH::FrameInfo *CurFrame = CurrentWinFrameInfo;
1270
1271 if (CurFrame->Version != DefaultWinCFIUnwindVersion &&
1272 CurFrame->Version != WinEH::FrameInfo::DefaultVersion)
1273 return getContext().reportError(L: Loc, Msg: "Duplicate .seh_unwindversion in " +
1274 CurFrame->Function->getName());
1275
1276 if (!SupportedVersion)
1277 return getContext().reportError(
1278 L: Loc, Msg: "Unsupported version specified in .seh_unwindversion in " +
1279 CurFrame->Function->getName());
1280
1281 CurFrame->Version = Version;
1282}
1283
1284void MCStreamer::emitCOFFSafeSEH(MCSymbol const *Symbol) {}
1285
1286void MCStreamer::emitCOFFSymbolIndex(MCSymbol const *Symbol) {}
1287
1288void MCStreamer::emitCOFFSectionIndex(MCSymbol const *Symbol) {}
1289
1290void MCStreamer::emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {}
1291
1292void MCStreamer::emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {}
1293
1294void MCStreamer::emitCOFFSecNumber(MCSymbol const *Symbol) {}
1295
1296void MCStreamer::emitCOFFSecOffset(MCSymbol const *Symbol) {}
1297
1298/// EmitRawText - If this file is backed by an assembly streamer, this dumps
1299/// the specified string in the output .s file. This capability is
1300/// indicated by the hasRawTextSupport() predicate.
1301void MCStreamer::emitRawTextImpl(StringRef String) {
1302 // This is not llvm_unreachable for the sake of out of tree backend
1303 // developers who may not have assembly streamers and should serve as a
1304 // reminder to not accidentally call EmitRawText in the absence of such.
1305 report_fatal_error(reason: "EmitRawText called on an MCStreamer that doesn't support "
1306 "it (target backend is likely missing an AsmStreamer "
1307 "implementation)");
1308}
1309
1310void MCStreamer::emitRawText(const Twine &T) {
1311 SmallString<128> Str;
1312 emitRawTextImpl(String: T.toStringRef(Out&: Str));
1313}
1314
1315void MCStreamer::emitWindowsUnwindTables() {}
1316
1317void MCStreamer::emitWindowsUnwindTables(WinEH::FrameInfo *Frame) {}
1318
1319void MCStreamer::finish(SMLoc EndLoc) {
1320 if (hasUnfinishedDwarfFrameInfo() ||
1321 (!WinFrameInfos.empty() && !WinFrameInfos.back()->End)) {
1322 getContext().reportError(L: EndLoc, Msg: "Unfinished frame!");
1323 return;
1324 }
1325
1326 if (LFIRewriter)
1327 LFIRewriter->finish(Out&: *this);
1328
1329 MCTargetStreamer *TS = getTargetStreamer();
1330 if (TS)
1331 TS->finish();
1332
1333 finishImpl();
1334}
1335
1336void MCStreamer::maybeEmitDwarf64Mark() {
1337 if (Context.getDwarfFormat() != dwarf::DWARF64)
1338 return;
1339 AddComment(T: "DWARF64 Mark");
1340 emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
1341}
1342
1343void MCStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
1344 assert(Context.getDwarfFormat() == dwarf::DWARF64 ||
1345 Length <= dwarf::DW_LENGTH_lo_reserved);
1346 maybeEmitDwarf64Mark();
1347 AddComment(T: Comment);
1348 emitIntValue(Value: Length, Size: dwarf::getDwarfOffsetByteSize(Format: Context.getDwarfFormat()));
1349}
1350
1351MCSymbol *MCStreamer::emitDwarfUnitLength(const Twine &Prefix,
1352 const Twine &Comment) {
1353 maybeEmitDwarf64Mark();
1354 AddComment(T: Comment);
1355 MCSymbol *Lo = Context.createTempSymbol(Name: Prefix + "_start");
1356 MCSymbol *Hi = Context.createTempSymbol(Name: Prefix + "_end");
1357
1358 emitAbsoluteSymbolDiff(
1359 Hi, Lo, Size: dwarf::getDwarfOffsetByteSize(Format: Context.getDwarfFormat()));
1360 // emit the begin symbol after we generate the length field.
1361 emitLabel(Symbol: Lo);
1362 // Return the Hi symbol to the caller.
1363 return Hi;
1364}
1365
1366void MCStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
1367 // Set the value of the symbol, as we are at the start of the line table.
1368 emitLabel(Symbol: StartSym);
1369}
1370
1371void MCStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
1372 visitUsedExpr(Expr: *Value);
1373 Symbol->setVariableValue(Value);
1374
1375 MCTargetStreamer *TS = getTargetStreamer();
1376 if (TS)
1377 TS->emitAssignment(Symbol, Value);
1378}
1379
1380void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter,
1381 uint64_t Address, const MCInst &Inst,
1382 const MCSubtargetInfo &STI,
1383 raw_ostream &OS) {
1384 InstPrinter.printInst(MI: &Inst, Address, Annot: "", STI, OS);
1385}
1386
1387void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) {
1388}
1389
1390void MCStreamer::visitUsedExpr(const MCExpr &Expr) {
1391 switch (Expr.getKind()) {
1392 case MCExpr::Target:
1393 cast<MCTargetExpr>(Val: Expr).visitUsedExpr(Streamer&: *this);
1394 break;
1395
1396 case MCExpr::Constant:
1397 break;
1398
1399 case MCExpr::Binary: {
1400 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Val: Expr);
1401 visitUsedExpr(Expr: *BE.getLHS());
1402 visitUsedExpr(Expr: *BE.getRHS());
1403 break;
1404 }
1405
1406 case MCExpr::SymbolRef:
1407 visitUsedSymbol(Sym: cast<MCSymbolRefExpr>(Val: Expr).getSymbol());
1408 break;
1409
1410 case MCExpr::Unary:
1411 visitUsedExpr(Expr: *cast<MCUnaryExpr>(Val: Expr).getSubExpr());
1412 break;
1413
1414 case MCExpr::Specifier:
1415 visitUsedExpr(Expr: *cast<MCSpecifierExpr>(Val: Expr).getSubExpr());
1416 break;
1417 }
1418}
1419
1420void MCStreamer::emitInstruction(const MCInst &Inst, const MCSubtargetInfo &) {
1421 // Scan for values.
1422 for (unsigned i = Inst.getNumOperands(); i--;)
1423 if (Inst.getOperand(i).isExpr())
1424 visitUsedExpr(Expr: *Inst.getOperand(i).getExpr());
1425}
1426
1427void MCStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
1428 uint64_t Attr, uint64_t Discriminator,
1429 const MCPseudoProbeInlineStack &InlineStack,
1430 MCSymbol *FnSym) {
1431 auto &Context = getContext();
1432
1433 // Create a symbol at in the current section for use in the probe.
1434 MCSymbol *ProbeSym = Context.createTempSymbol();
1435
1436 // Set the value of the symbol to use for the MCPseudoProbe.
1437 emitLabel(Symbol: ProbeSym);
1438
1439 // Create a (local) probe entry with the symbol.
1440 MCPseudoProbe Probe(ProbeSym, Guid, Index, Type, Attr, Discriminator);
1441
1442 // Add the probe entry to this section's entries.
1443 Context.getMCPseudoProbeTable().getProbeSections().addPseudoProbe(
1444 FuncSym: FnSym, Probe, InlineStack);
1445}
1446
1447void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
1448 unsigned Size) {
1449 // Get the Hi-Lo expression.
1450 const MCExpr *Diff =
1451 MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: Hi, Ctx&: Context),
1452 RHS: MCSymbolRefExpr::create(Symbol: Lo, Ctx&: Context), Ctx&: Context);
1453
1454 const MCAsmInfo &MAI = Context.getAsmInfo();
1455 if (!MAI.doesSetDirectiveSuppressReloc()) {
1456 emitValue(Value: Diff, Size);
1457 return;
1458 }
1459
1460 // Otherwise, emit with .set (aka assignment).
1461 MCSymbol *SetLabel = Context.createTempSymbol(Name: "set");
1462 emitAssignment(Symbol: SetLabel, Value: Diff);
1463 emitSymbolValue(Sym: SetLabel, Size);
1464}
1465
1466void MCStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
1467 const MCSymbol *Lo) {
1468 // Get the Hi-Lo expression.
1469 const MCExpr *Diff =
1470 MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: Hi, Ctx&: Context),
1471 RHS: MCSymbolRefExpr::create(Symbol: Lo, Ctx&: Context), Ctx&: Context);
1472
1473 emitULEB128Value(Value: Diff);
1474}
1475
1476void MCStreamer::emitSubsectionsViaSymbols() {
1477 llvm_unreachable(
1478 "emitSubsectionsViaSymbols only supported on Mach-O targets");
1479}
1480void MCStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
1481void MCStreamer::beginCOFFSymbolDef(const MCSymbol *Symbol) {
1482 llvm_unreachable("this directive only supported on COFF targets");
1483}
1484void MCStreamer::endCOFFSymbolDef() {
1485 llvm_unreachable("this directive only supported on COFF targets");
1486}
1487void MCStreamer::emitFileDirective(StringRef Filename) {}
1488void MCStreamer::emitFileDirective(StringRef Filename,
1489 StringRef CompilerVersion,
1490 StringRef TimeStamp, StringRef Description) {
1491}
1492void MCStreamer::emitCOFFSymbolStorageClass(int StorageClass) {
1493 llvm_unreachable("this directive only supported on COFF targets");
1494}
1495void MCStreamer::emitCOFFSymbolType(int Type) {
1496 llvm_unreachable("this directive only supported on COFF targets");
1497}
1498void MCStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
1499 MCSymbol *CsectSym,
1500 Align Alignment) {
1501 llvm_unreachable("this directive only supported on XCOFF targets");
1502}
1503
1504void MCStreamer::emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
1505 MCSymbolAttr Linkage,
1506 MCSymbolAttr Visibility) {
1507 llvm_unreachable("emitXCOFFSymbolLinkageWithVisibility is only supported on "
1508 "XCOFF targets");
1509}
1510
1511void MCStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
1512 StringRef Rename) {}
1513
1514void MCStreamer::emitXCOFFRefDirective(const MCSymbol *Symbol) {
1515 llvm_unreachable("emitXCOFFRefDirective is only supported on XCOFF targets");
1516}
1517
1518void MCStreamer::emitXCOFFExceptDirective(const MCSymbol *Symbol,
1519 const MCSymbol *Trap,
1520 unsigned Lang, unsigned Reason,
1521 unsigned FunctionSize,
1522 bool hasDebug) {
1523 report_fatal_error(reason: "emitXCOFFExceptDirective is only supported on "
1524 "XCOFF targets");
1525}
1526
1527void MCStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
1528 llvm_unreachable("emitXCOFFCInfoSym is only supported on"
1529 "XCOFF targets");
1530}
1531
1532void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
1533void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
1534 StringRef Name, bool KeepOriginalSym) {}
1535void MCStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1536 Align ByteAlignment) {}
1537void MCStreamer::emitZerofill(MCSection *, MCSymbol *, uint64_t, Align, SMLoc) {
1538}
1539void MCStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
1540 uint64_t Size, Align ByteAlignment) {}
1541
1542void MCStreamer::changeSection(MCSection *Sec, uint32_t) {
1543 CurFrag = &Sec->getDummyFragment();
1544 auto *Sym = Sec->getBeginSymbol();
1545 if (!Sym || !Sym->isUndefined())
1546 return;
1547 // In Mach-O, DWARF sections use Begin as a temporary label, requiring a label
1548 // definition, unlike section symbols in other file formats.
1549 if (getContext().getObjectFileType() == MCContext::IsMachO)
1550 emitLabel(Symbol: Sym);
1551 else
1552 Sym->setFragment(CurFrag);
1553}
1554
1555void MCStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
1556void MCStreamer::emitBytes(StringRef Data) {}
1557void MCStreamer::emitBinaryData(StringRef Data) { emitBytes(Data); }
1558void MCStreamer::emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) {
1559 visitUsedExpr(Expr: *Value);
1560}
1561void MCStreamer::emitULEB128Value(const MCExpr *Value) {}
1562void MCStreamer::emitSLEB128Value(const MCExpr *Value) {}
1563void MCStreamer::emitFill(const MCExpr &NumBytes, uint64_t Value, SMLoc Loc) {}
1564void MCStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
1565 SMLoc Loc) {}
1566void MCStreamer::emitValueToAlignment(Align, int64_t, uint8_t, unsigned) {}
1567void MCStreamer::emitPrefAlign(Align A, const MCSymbol &End, bool EmitNops,
1568 uint8_t Fill, const MCSubtargetInfo &STI) {}
1569void MCStreamer::emitCodeAlignment(Align Alignment, const MCSubtargetInfo &STI,
1570 unsigned MaxBytesToEmit) {}
1571void MCStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value,
1572 SMLoc Loc) {}
1573static void reportBundlingUnsupported(MCStreamer &S) {
1574 S.getContext().reportError(
1575 L: S.getStartTokLoc(),
1576 Msg: "aligned bundling is not supported by this object file format");
1577}
1578void MCStreamer::emitBundleAlignMode(Align) {
1579 reportBundlingUnsupported(S&: *this);
1580}
1581void MCStreamer::emitBundleLock(bool, const MCSubtargetInfo &) {
1582 reportBundlingUnsupported(S&: *this);
1583}
1584void MCStreamer::emitBundleUnlock(const MCSubtargetInfo &) {
1585 reportBundlingUnsupported(S&: *this);
1586}
1587void MCStreamer::finishImpl() {}
1588
1589bool MCStreamer::popSection() {
1590 if (SectionStack.size() <= 1)
1591 return false;
1592 auto I = SectionStack.end();
1593 --I;
1594 MCSectionSubPair OldSec = I->first;
1595 --I;
1596 MCSectionSubPair NewSec = I->first;
1597
1598 if (NewSec.first && OldSec != NewSec)
1599 changeSection(Sec: NewSec.first, NewSec.second);
1600 SectionStack.pop_back();
1601 return true;
1602}
1603
1604void MCStreamer::switchSection(MCSection *Section, uint32_t Subsection) {
1605 assert(Section && "Cannot switch to a null section!");
1606 MCSectionSubPair curSection = SectionStack.back().first;
1607 SectionStack.back().second = curSection;
1608 if (MCSectionSubPair(Section, Subsection) != curSection) {
1609 changeSection(Sec: Section, Subsection);
1610 SectionStack.back().first = MCSectionSubPair(Section, Subsection);
1611 assert(!Section->hasEnded() && "Section already ended");
1612 }
1613}
1614
1615bool MCStreamer::switchSection(MCSection *Section, const MCExpr *SubsecExpr) {
1616 int64_t Subsec = 0;
1617 if (SubsecExpr) {
1618 if (!SubsecExpr->evaluateAsAbsolute(Res&: Subsec, Asm: getAssemblerPtr())) {
1619 getContext().reportError(L: SubsecExpr->getLoc(),
1620 Msg: "cannot evaluate subsection number");
1621 return true;
1622 }
1623 if (!isUInt<31>(x: Subsec)) {
1624 getContext().reportError(L: SubsecExpr->getLoc(),
1625 Msg: "subsection number " + Twine(Subsec) +
1626 " is not within [0,2147483647]");
1627 return true;
1628 }
1629 }
1630 switchSection(Section, Subsection: Subsec);
1631 return false;
1632}
1633
1634void MCStreamer::switchSectionNoPrint(MCSection *Section) {
1635 SectionStack.back().second = SectionStack.back().first;
1636 SectionStack.back().first = MCSectionSubPair(Section, 0);
1637 changeSection(Sec: Section, 0);
1638}
1639
1640MCSymbol *MCStreamer::endSection(MCSection *Section) {
1641 // TODO: keep track of the last subsection so that this symbol appears in the
1642 // correct place.
1643 MCSymbol *Sym = Section->getEndSymbol(Ctx&: Context);
1644 if (Sym->isInSection())
1645 return Sym;
1646
1647 switchSection(Section);
1648 emitLabel(Symbol: Sym);
1649 return Sym;
1650}
1651
1652void MCStreamer::addFragment(MCFragment *F) {
1653 auto *Sec = CurFrag->getParent();
1654 F->setParent(Sec);
1655 F->setLayoutOrder(CurFrag->getLayoutOrder() + 1);
1656 CurFrag->Next = F;
1657 CurFrag = F;
1658 Sec->curFragList()->Tail = F;
1659}
1660
1661static VersionTuple
1662targetVersionOrMinimumSupportedOSVersion(const Triple &Target,
1663 VersionTuple TargetVersion) {
1664 VersionTuple Min = Target.getMinimumSupportedOSVersion();
1665 return !Min.empty() && Min > TargetVersion ? Min : TargetVersion;
1666}
1667
1668static MCVersionMinType
1669getMachoVersionMinLoadCommandType(const Triple &Target) {
1670 assert(Target.isOSDarwin() && "expected a darwin OS");
1671 switch (Target.getOS()) {
1672 case Triple::MacOSX:
1673 case Triple::Darwin:
1674 return MCVM_OSXVersionMin;
1675 case Triple::IOS:
1676 assert(!Target.isMacCatalystEnvironment() &&
1677 "mac Catalyst should use LC_BUILD_VERSION");
1678 return MCVM_IOSVersionMin;
1679 case Triple::TvOS:
1680 return MCVM_TvOSVersionMin;
1681 case Triple::WatchOS:
1682 return MCVM_WatchOSVersionMin;
1683 default:
1684 break;
1685 }
1686 llvm_unreachable("unexpected OS type");
1687}
1688
1689static VersionTuple getMachoBuildVersionSupportedOS(const Triple &Target) {
1690 assert(Target.isOSDarwin() && "expected a darwin OS");
1691 switch (Target.getOS()) {
1692 case Triple::MacOSX:
1693 case Triple::Darwin:
1694 return VersionTuple(10, 14);
1695 case Triple::IOS:
1696 // Mac Catalyst always uses the build version load command.
1697 if (Target.isMacCatalystEnvironment())
1698 return VersionTuple();
1699 [[fallthrough]];
1700 case Triple::TvOS:
1701 return VersionTuple(12);
1702 case Triple::WatchOS:
1703 return VersionTuple(5);
1704 case Triple::DriverKit:
1705 case Triple::BridgeOS:
1706 case Triple::XROS:
1707 // DriverKit/BridgeOS/XROS always use the build version load command.
1708 return VersionTuple();
1709 default:
1710 break;
1711 }
1712 llvm_unreachable("unexpected OS type");
1713}
1714
1715static MachO::PlatformType
1716getMachoBuildVersionPlatformType(const Triple &Target) {
1717 assert(Target.isOSDarwin() && "expected a darwin OS");
1718 switch (Target.getOS()) {
1719 case Triple::MacOSX:
1720 case Triple::Darwin:
1721 return MachO::PLATFORM_MACOS;
1722 case Triple::IOS:
1723 if (Target.isMacCatalystEnvironment())
1724 return MachO::PLATFORM_MACCATALYST;
1725 return Target.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR
1726 : MachO::PLATFORM_IOS;
1727 case Triple::TvOS:
1728 return Target.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR
1729 : MachO::PLATFORM_TVOS;
1730 case Triple::WatchOS:
1731 return Target.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR
1732 : MachO::PLATFORM_WATCHOS;
1733 case Triple::DriverKit:
1734 return MachO::PLATFORM_DRIVERKIT;
1735 case Triple::XROS:
1736 return Target.isSimulatorEnvironment() ? MachO::PLATFORM_XROS_SIMULATOR
1737 : MachO::PLATFORM_XROS;
1738 case Triple::BridgeOS:
1739 return MachO::PLATFORM_BRIDGEOS;
1740 default:
1741 break;
1742 }
1743 llvm_unreachable("unexpected OS type");
1744}
1745
1746void MCStreamer::emitVersionForTarget(
1747 const Triple &Target, const VersionTuple &SDKVersion,
1748 const Triple *DarwinTargetVariantTriple,
1749 const VersionTuple &DarwinTargetVariantSDKVersion) {
1750 if (!Target.isOSBinFormatMachO() || !Target.isOSDarwin())
1751 return;
1752 // Do we even know the version?
1753 if (Target.getOSMajorVersion() == 0)
1754 return;
1755
1756 VersionTuple Version;
1757 switch (Target.getOS()) {
1758 case Triple::MacOSX:
1759 case Triple::Darwin:
1760 Target.getMacOSXVersion(Version);
1761 break;
1762 case Triple::IOS:
1763 case Triple::TvOS:
1764 Version = Target.getiOSVersion();
1765 break;
1766 case Triple::WatchOS:
1767 Version = Target.getWatchOSVersion();
1768 break;
1769 case Triple::DriverKit:
1770 Version = Target.getDriverKitVersion();
1771 break;
1772 case Triple::XROS:
1773 case Triple::BridgeOS:
1774 Version = Target.getOSVersion();
1775 break;
1776 default:
1777 llvm_unreachable("unexpected OS type");
1778 }
1779 assert(Version.getMajor() != 0 && "A non-zero major version is expected");
1780 auto LinkedTargetVersion =
1781 targetVersionOrMinimumSupportedOSVersion(Target, TargetVersion: Version);
1782 auto BuildVersionOSVersion = getMachoBuildVersionSupportedOS(Target);
1783 bool ShouldEmitBuildVersion = false;
1784 if (BuildVersionOSVersion.empty() ||
1785 LinkedTargetVersion >= BuildVersionOSVersion) {
1786 if (Target.isMacCatalystEnvironment() && DarwinTargetVariantTriple &&
1787 DarwinTargetVariantTriple->isMacOSX()) {
1788 emitVersionForTarget(Target: *DarwinTargetVariantTriple,
1789 SDKVersion: DarwinTargetVariantSDKVersion,
1790 /*DarwinTargetVariantTriple=*/nullptr,
1791 /*DarwinTargetVariantSDKVersion=*/VersionTuple());
1792 emitDarwinTargetVariantBuildVersion(
1793 Platform: getMachoBuildVersionPlatformType(Target),
1794 Major: LinkedTargetVersion.getMajor(),
1795 Minor: LinkedTargetVersion.getMinor().value_or(u: 0),
1796 Update: LinkedTargetVersion.getSubminor().value_or(u: 0), SDKVersion);
1797 return;
1798 }
1799 emitBuildVersion(Platform: getMachoBuildVersionPlatformType(Target),
1800 Major: LinkedTargetVersion.getMajor(),
1801 Minor: LinkedTargetVersion.getMinor().value_or(u: 0),
1802 Update: LinkedTargetVersion.getSubminor().value_or(u: 0), SDKVersion);
1803 ShouldEmitBuildVersion = true;
1804 }
1805
1806 if (const Triple *TVT = DarwinTargetVariantTriple) {
1807 if (Target.isMacOSX() && TVT->isMacCatalystEnvironment()) {
1808 auto TVLinkedTargetVersion =
1809 targetVersionOrMinimumSupportedOSVersion(Target: *TVT, TargetVersion: TVT->getiOSVersion());
1810 emitDarwinTargetVariantBuildVersion(
1811 Platform: getMachoBuildVersionPlatformType(Target: *TVT),
1812 Major: TVLinkedTargetVersion.getMajor(),
1813 Minor: TVLinkedTargetVersion.getMinor().value_or(u: 0),
1814 Update: TVLinkedTargetVersion.getSubminor().value_or(u: 0),
1815 SDKVersion: DarwinTargetVariantSDKVersion);
1816 }
1817 }
1818
1819 if (ShouldEmitBuildVersion)
1820 return;
1821
1822 emitVersionMin(Type: getMachoVersionMinLoadCommandType(Target),
1823 Major: LinkedTargetVersion.getMajor(),
1824 Minor: LinkedTargetVersion.getMinor().value_or(u: 0),
1825 Update: LinkedTargetVersion.getSubminor().value_or(u: 0), SDKVersion);
1826}
1827