xref: /llvm-project/llvm/lib/MC/MCObjectStreamer.cpp (revision 4684d0c0073669c1833be7bb127a149b1f7a5e65)
1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
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/MCObjectStreamer.h"
10 #include "llvm/MC/MCAsmBackend.h"
11 #include "llvm/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCCodeView.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCDwarf.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectFileInfo.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/SourceMgr.h"
25 using namespace llvm;
26 
27 MCObjectStreamer::MCObjectStreamer(MCContext &Context,
28                                    std::unique_ptr<MCAsmBackend> TAB,
29                                    std::unique_ptr<MCObjectWriter> OW,
30                                    std::unique_ptr<MCCodeEmitter> Emitter)
31     : MCStreamer(Context),
32       Assembler(std::make_unique<MCAssembler>(
33           Context, std::move(TAB), std::move(Emitter), std::move(OW))),
34       EmitEHFrame(true), EmitDebugFrame(false) {
35   if (Assembler->getBackendPtr())
36     setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
37   if (Context.getTargetOptions() && Context.getTargetOptions()->MCRelaxAll)
38     Assembler->setRelaxAll(true);
39 }
40 
41 MCObjectStreamer::~MCObjectStreamer() = default;
42 
43 MCAssembler *MCObjectStreamer::getAssemblerPtr() {
44   if (getUseAssemblerInfoForParsing())
45     return Assembler.get();
46   return nullptr;
47 }
48 
49 void MCObjectStreamer::addPendingLabel(MCSymbol* S) {
50   MCSection *CurSection = getCurrentSectionOnly();
51   if (CurSection) {
52     // Register labels that have not yet been assigned to a Section.
53     if (!PendingLabels.empty()) {
54       for (MCSymbol* Sym : PendingLabels)
55         CurSection->addPendingLabel(Sym);
56       PendingLabels.clear();
57     }
58 
59     // Add this label to the current Section / Subsection.
60     CurSection->addPendingLabel(S, CurSubsectionIdx);
61 
62     // Add this Section to the list of PendingLabelSections.
63     PendingLabelSections.insert(CurSection);
64   } else
65     // There is no Section / Subsection for this label yet.
66     PendingLabels.push_back(S);
67 }
68 
69 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
70   assert(F);
71   MCSection *CurSection = getCurrentSectionOnly();
72   if (!CurSection) {
73     assert(PendingLabels.empty());
74     return;
75   }
76   // Register labels that have not yet been assigned to a Section.
77   if (!PendingLabels.empty()) {
78     for (MCSymbol* Sym : PendingLabels)
79       CurSection->addPendingLabel(Sym, CurSubsectionIdx);
80     PendingLabels.clear();
81   }
82 
83   // Associate the labels with F.
84   CurSection->flushPendingLabels(F, CurSubsectionIdx);
85 }
86 
87 void MCObjectStreamer::flushPendingLabels() {
88   // Register labels that have not yet been assigned to a Section.
89   if (!PendingLabels.empty()) {
90     MCSection *CurSection = getCurrentSectionOnly();
91     assert(CurSection);
92     for (MCSymbol* Sym : PendingLabels)
93       CurSection->addPendingLabel(Sym, CurSubsectionIdx);
94     PendingLabels.clear();
95   }
96 
97   // Assign an empty data fragment to all remaining pending labels.
98   for (MCSection* Section : PendingLabelSections)
99     Section->flushPendingLabels();
100 }
101 
102 // When fixup's offset is a forward declared label, e.g.:
103 //
104 //   .reloc 1f, R_MIPS_JALR, foo
105 // 1: nop
106 //
107 // postpone adding it to Fixups vector until the label is defined and its offset
108 // is known.
109 void MCObjectStreamer::resolvePendingFixups() {
110   for (PendingMCFixup &PendingFixup : PendingFixups) {
111     if (!PendingFixup.Sym || PendingFixup.Sym->isUndefined ()) {
112       getContext().reportError(PendingFixup.Fixup.getLoc(),
113                                "unresolved relocation offset");
114       continue;
115     }
116     flushPendingLabels(PendingFixup.DF, PendingFixup.DF->getContents().size());
117     PendingFixup.Fixup.setOffset(PendingFixup.Sym->getOffset() +
118                                  PendingFixup.Fixup.getOffset());
119 
120     // If the location symbol to relocate is in MCEncodedFragmentWithFixups,
121     // put the Fixup into location symbol's fragment. Otherwise
122     // put into PendingFixup.DF
123     MCFragment *SymFragment = PendingFixup.Sym->getFragment();
124     switch (SymFragment->getKind()) {
125     case MCFragment::FT_Relaxable:
126     case MCFragment::FT_Dwarf:
127     case MCFragment::FT_PseudoProbe:
128       cast<MCEncodedFragmentWithFixups<8, 1>>(SymFragment)
129           ->getFixups()
130           .push_back(PendingFixup.Fixup);
131       break;
132     case MCFragment::FT_Data:
133     case MCFragment::FT_CVDefRange:
134       cast<MCEncodedFragmentWithFixups<32, 4>>(SymFragment)
135           ->getFixups()
136           .push_back(PendingFixup.Fixup);
137       break;
138     default:
139       PendingFixup.DF->getFixups().push_back(PendingFixup.Fixup);
140       break;
141     }
142   }
143   PendingFixups.clear();
144 }
145 
146 // As a compile-time optimization, avoid allocating and evaluating an MCExpr
147 // tree for (Hi - Lo) when Hi and Lo are offsets into the same fragment.
148 static std::optional<uint64_t> absoluteSymbolDiff(const MCSymbol *Hi,
149                                                   const MCSymbol *Lo) {
150   assert(Hi && Lo);
151   if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
152       Hi->isVariable() || Lo->isVariable())
153     return std::nullopt;
154 
155   return Hi->getOffset() - Lo->getOffset();
156 }
157 
158 void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
159                                               const MCSymbol *Lo,
160                                               unsigned Size) {
161   if (!getAssembler().getContext().getTargetTriple().isRISCV())
162     if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo))
163       return emitIntValue(*Diff, Size);
164   MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
165 }
166 
167 void MCObjectStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
168                                                        const MCSymbol *Lo) {
169   if (!getAssembler().getContext().getTargetTriple().isRISCV())
170     if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo)) {
171       emitULEB128IntValue(*Diff);
172       return;
173     }
174   MCStreamer::emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
175 }
176 
177 void MCObjectStreamer::reset() {
178   if (Assembler) {
179     Assembler->reset();
180     if (getContext().getTargetOptions())
181       Assembler->setRelaxAll(getContext().getTargetOptions()->MCRelaxAll);
182   }
183   EmitEHFrame = true;
184   EmitDebugFrame = false;
185   PendingLabels.clear();
186   PendingLabelSections.clear();
187   MCStreamer::reset();
188 }
189 
190 void MCObjectStreamer::emitFrames(MCAsmBackend *MAB) {
191   if (!getNumFrameInfos())
192     return;
193 
194   if (EmitEHFrame)
195     MCDwarfFrameEmitter::Emit(*this, MAB, true);
196 
197   if (EmitDebugFrame)
198     MCDwarfFrameEmitter::Emit(*this, MAB, false);
199 }
200 
201 MCFragment *MCObjectStreamer::getCurrentFragment() const {
202   return getCurrentSectionOnly()->curFragList()->Tail;
203 }
204 
205 static bool canReuseDataFragment(const MCDataFragment &F,
206                                  const MCAssembler &Assembler,
207                                  const MCSubtargetInfo *STI) {
208   if (!F.hasInstructions())
209     return true;
210   // Do not add data after a linker-relaxable instruction. The difference
211   // between a new label and a label at or before the linker-relaxable
212   // instruction cannot be resolved at assemble-time.
213   if (F.isLinkerRelaxable())
214     return false;
215   // When bundling is enabled, we don't want to add data to a fragment that
216   // already has instructions (see MCELFStreamer::emitInstToData for details)
217   if (Assembler.isBundlingEnabled())
218     return false;
219   // If the subtarget is changed mid fragment we start a new fragment to record
220   // the new STI.
221   return !STI || F.getSubtargetInfo() == STI;
222 }
223 
224 MCDataFragment *
225 MCObjectStreamer::getOrCreateDataFragment(const MCSubtargetInfo *STI) {
226   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
227   if (!F || !canReuseDataFragment(*F, *Assembler, STI)) {
228     F = getContext().allocFragment<MCDataFragment>();
229     insert(F);
230   }
231   return F;
232 }
233 
234 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
235   Assembler->registerSymbol(Sym);
236 }
237 
238 void MCObjectStreamer::emitCFISections(bool EH, bool Debug) {
239   MCStreamer::emitCFISections(EH, Debug);
240   EmitEHFrame = EH;
241   EmitDebugFrame = Debug;
242 }
243 
244 void MCObjectStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
245                                      SMLoc Loc) {
246   MCStreamer::emitValueImpl(Value, Size, Loc);
247   MCDataFragment *DF = getOrCreateDataFragment();
248   flushPendingLabels(DF, DF->getContents().size());
249 
250   MCDwarfLineEntry::make(this, getCurrentSectionOnly());
251 
252   // Avoid fixups when possible.
253   int64_t AbsValue;
254   if (Value->evaluateAsAbsolute(AbsValue, getAssemblerPtr())) {
255     if (!isUIntN(8 * Size, AbsValue) && !isIntN(8 * Size, AbsValue)) {
256       getContext().reportError(
257           Loc, "value evaluated as " + Twine(AbsValue) + " is out of range.");
258       return;
259     }
260     emitIntValue(AbsValue, Size);
261     return;
262   }
263   DF->getFixups().push_back(
264       MCFixup::create(DF->getContents().size(), Value,
265                       MCFixup::getKindForSize(Size, false), Loc));
266   DF->getContents().resize(DF->getContents().size() + Size, 0);
267 }
268 
269 MCSymbol *MCObjectStreamer::emitCFILabel() {
270   MCSymbol *Label = getContext().createTempSymbol("cfi");
271   emitLabel(Label);
272   return Label;
273 }
274 
275 void MCObjectStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
276   // We need to create a local symbol to avoid relocations.
277   Frame.Begin = getContext().createTempSymbol();
278   emitLabel(Frame.Begin);
279 }
280 
281 void MCObjectStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
282   Frame.End = getContext().createTempSymbol();
283   emitLabel(Frame.End);
284 }
285 
286 void MCObjectStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
287   MCStreamer::emitLabel(Symbol, Loc);
288 
289   getAssembler().registerSymbol(*Symbol);
290 
291   // If there is a current fragment, mark the symbol as pointing into it.
292   // Otherwise queue the label and set its fragment pointer when we emit the
293   // next fragment.
294   auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
295   if (F) {
296     Symbol->setFragment(F);
297     Symbol->setOffset(F->getContents().size());
298   } else {
299     // Assign all pending labels to offset 0 within the dummy "pending"
300     // fragment. (They will all be reassigned to a real fragment in
301     // flushPendingLabels())
302     Symbol->setOffset(0);
303     addPendingLabel(Symbol);
304   }
305 
306   emitPendingAssignments(Symbol);
307 }
308 
309 void MCObjectStreamer::emitPendingAssignments(MCSymbol *Symbol) {
310   auto Assignments = pendingAssignments.find(Symbol);
311   if (Assignments != pendingAssignments.end()) {
312     for (const PendingAssignment &A : Assignments->second)
313       emitAssignment(A.Symbol, A.Value);
314 
315     pendingAssignments.erase(Assignments);
316   }
317 }
318 
319 // Emit a label at a previously emitted fragment/offset position. This must be
320 // within the currently-active section.
321 void MCObjectStreamer::emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc,
322                                       MCDataFragment &F, uint64_t Offset) {
323   assert(F.getParent() == getCurrentSectionOnly());
324   MCStreamer::emitLabel(Symbol, Loc);
325   getAssembler().registerSymbol(*Symbol);
326   Symbol->setFragment(&F);
327   Symbol->setOffset(Offset);
328 }
329 
330 void MCObjectStreamer::emitULEB128Value(const MCExpr *Value) {
331   int64_t IntValue;
332   if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) {
333     emitULEB128IntValue(IntValue);
334     return;
335   }
336   insert(getContext().allocFragment<MCLEBFragment>(*Value, false));
337 }
338 
339 void MCObjectStreamer::emitSLEB128Value(const MCExpr *Value) {
340   int64_t IntValue;
341   if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) {
342     emitSLEB128IntValue(IntValue);
343     return;
344   }
345   insert(getContext().allocFragment<MCLEBFragment>(*Value, true));
346 }
347 
348 void MCObjectStreamer::emitWeakReference(MCSymbol *Alias,
349                                          const MCSymbol *Symbol) {
350   report_fatal_error("This file format doesn't support weak aliases.");
351 }
352 
353 void MCObjectStreamer::changeSection(MCSection *Section,
354                                      const MCExpr *Subsection) {
355   changeSectionImpl(Section, Subsection);
356 }
357 
358 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
359                                          const MCExpr *Subsection) {
360   assert(Section && "Cannot switch to a null section!");
361   getContext().clearDwarfLocSeen();
362 
363   bool Created = getAssembler().registerSection(*Section);
364 
365   int64_t IntSubsection = 0;
366   if (Subsection &&
367       !Subsection->evaluateAsAbsolute(IntSubsection, getAssemblerPtr())) {
368     getContext().reportError(Subsection->getLoc(),
369                              "cannot evaluate subsection number");
370   }
371   if (!isUInt<31>(IntSubsection)) {
372     getContext().reportError(Subsection->getLoc(),
373                              "subsection number " + Twine(IntSubsection) +
374                                  " is not within [0,2147483647]");
375   }
376 
377   CurSubsectionIdx = unsigned(IntSubsection);
378   Section->switchSubsection(CurSubsectionIdx);
379   return Created;
380 }
381 
382 void MCObjectStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
383   getAssembler().registerSymbol(*Symbol);
384   MCStreamer::emitAssignment(Symbol, Value);
385   emitPendingAssignments(Symbol);
386 }
387 
388 void MCObjectStreamer::emitConditionalAssignment(MCSymbol *Symbol,
389                                                  const MCExpr *Value) {
390   const MCSymbol *Target = &cast<MCSymbolRefExpr>(*Value).getSymbol();
391 
392   // If the symbol already exists, emit the assignment. Otherwise, emit it
393   // later only if the symbol is also emitted.
394   if (Target->isRegistered())
395     emitAssignment(Symbol, Value);
396   else
397     pendingAssignments[Target].push_back({Symbol, Value});
398 }
399 
400 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
401   return Sec.hasInstructions();
402 }
403 
404 void MCObjectStreamer::emitInstruction(const MCInst &Inst,
405                                        const MCSubtargetInfo &STI) {
406   const MCSection &Sec = *getCurrentSectionOnly();
407   if (Sec.isVirtualSection()) {
408     getContext().reportError(Inst.getLoc(), Twine(Sec.getVirtualSectionKind()) +
409                                                 " section '" + Sec.getName() +
410                                                 "' cannot have instructions");
411     return;
412   }
413   getAssembler().getBackend().emitInstructionBegin(*this, Inst, STI);
414   emitInstructionImpl(Inst, STI);
415   getAssembler().getBackend().emitInstructionEnd(*this, Inst);
416 }
417 
418 void MCObjectStreamer::emitInstructionImpl(const MCInst &Inst,
419                                            const MCSubtargetInfo &STI) {
420   MCStreamer::emitInstruction(Inst, STI);
421 
422   MCSection *Sec = getCurrentSectionOnly();
423   Sec->setHasInstructions(true);
424 
425   // Now that a machine instruction has been assembled into this section, make
426   // a line entry for any .loc directive that has been seen.
427   MCDwarfLineEntry::make(this, getCurrentSectionOnly());
428 
429   // If this instruction doesn't need relaxation, just emit it as data.
430   MCAssembler &Assembler = getAssembler();
431   MCAsmBackend &Backend = Assembler.getBackend();
432   if (!(Backend.mayNeedRelaxation(Inst, STI) ||
433         Backend.allowEnhancedRelaxation())) {
434     emitInstToData(Inst, STI);
435     return;
436   }
437 
438   // Otherwise, relax and emit it as data if either:
439   // - The RelaxAll flag was passed
440   // - Bundling is enabled and this instruction is inside a bundle-locked
441   //   group. We want to emit all such instructions into the same data
442   //   fragment.
443   if (Assembler.getRelaxAll() ||
444       (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
445     MCInst Relaxed = Inst;
446     while (Backend.mayNeedRelaxation(Relaxed, STI))
447       Backend.relaxInstruction(Relaxed, STI);
448     emitInstToData(Relaxed, STI);
449     return;
450   }
451 
452   // Otherwise emit to a separate fragment.
453   emitInstToFragment(Inst, STI);
454 }
455 
456 void MCObjectStreamer::emitInstToFragment(const MCInst &Inst,
457                                           const MCSubtargetInfo &STI) {
458   // Always create a new, separate fragment here, because its size can change
459   // during relaxation.
460   MCRelaxableFragment *IF =
461       getContext().allocFragment<MCRelaxableFragment>(Inst, STI);
462   insert(IF);
463 
464   SmallString<128> Code;
465   getAssembler().getEmitter().encodeInstruction(Inst, Code, IF->getFixups(),
466                                                 STI);
467   IF->getContents().append(Code.begin(), Code.end());
468 }
469 
470 #ifndef NDEBUG
471 static const char *const BundlingNotImplementedMsg =
472   "Aligned bundling is not implemented for this object format";
473 #endif
474 
475 void MCObjectStreamer::emitBundleAlignMode(Align Alignment) {
476   llvm_unreachable(BundlingNotImplementedMsg);
477 }
478 
479 void MCObjectStreamer::emitBundleLock(bool AlignToEnd) {
480   llvm_unreachable(BundlingNotImplementedMsg);
481 }
482 
483 void MCObjectStreamer::emitBundleUnlock() {
484   llvm_unreachable(BundlingNotImplementedMsg);
485 }
486 
487 void MCObjectStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
488                                              unsigned Column, unsigned Flags,
489                                              unsigned Isa,
490                                              unsigned Discriminator,
491                                              StringRef FileName) {
492   // In case we see two .loc directives in a row, make sure the
493   // first one gets a line entry.
494   MCDwarfLineEntry::make(this, getCurrentSectionOnly());
495 
496   this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
497                                           Discriminator, FileName);
498 }
499 
500 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
501                                      const MCSymbol *B, SMLoc Loc) {
502   MCContext &Context = OS.getContext();
503   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
504   const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
505   const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
506   const MCExpr *AddrDelta =
507       MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context, Loc);
508   return AddrDelta;
509 }
510 
511 static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
512                                  MCDwarfLineTableParams Params,
513                                  int64_t LineDelta, const MCSymbol *Label,
514                                  int PointerSize) {
515   // emit the sequence to set the address
516   OS.emitIntValue(dwarf::DW_LNS_extended_op, 1);
517   OS.emitULEB128IntValue(PointerSize + 1);
518   OS.emitIntValue(dwarf::DW_LNE_set_address, 1);
519   OS.emitSymbolValue(Label, PointerSize);
520 
521   // emit the sequence for the LineDelta (from 1) and a zero address delta.
522   MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
523 }
524 
525 void MCObjectStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
526                                                 const MCSymbol *LastLabel,
527                                                 const MCSymbol *Label,
528                                                 unsigned PointerSize) {
529   if (!LastLabel) {
530     emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
531                          Label, PointerSize);
532     return;
533   }
534   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel, SMLoc());
535   insert(getContext().allocFragment<MCDwarfLineAddrFragment>(LineDelta,
536                                                              *AddrDelta));
537 }
538 
539 void MCObjectStreamer::emitDwarfLineEndEntry(MCSection *Section,
540                                              MCSymbol *LastLabel) {
541   // Emit a DW_LNE_end_sequence for the end of the section.
542   // Use the section end label to compute the address delta and use INT64_MAX
543   // as the line delta which is the signal that this is actually a
544   // DW_LNE_end_sequence.
545   MCSymbol *SectionEnd = endSection(Section);
546 
547   // Switch back the dwarf line section, in case endSection had to switch the
548   // section.
549   MCContext &Ctx = getContext();
550   switchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
551 
552   const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
553   emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
554                            AsmInfo->getCodePointerSize());
555 }
556 
557 void MCObjectStreamer::emitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
558                                                  const MCSymbol *Label,
559                                                  SMLoc Loc) {
560   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel, Loc);
561   insert(getContext().allocFragment<MCDwarfCallFrameFragment>(*AddrDelta));
562 }
563 
564 void MCObjectStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
565                                           unsigned Line, unsigned Column,
566                                           bool PrologueEnd, bool IsStmt,
567                                           StringRef FileName, SMLoc Loc) {
568   // Validate the directive.
569   if (!checkCVLocSection(FunctionId, FileNo, Loc))
570     return;
571 
572   // Emit a label at the current position and record it in the CodeViewContext.
573   MCSymbol *LineSym = getContext().createTempSymbol();
574   emitLabel(LineSym);
575   getContext().getCVContext().recordCVLoc(getContext(), LineSym, FunctionId,
576                                           FileNo, Line, Column, PrologueEnd,
577                                           IsStmt);
578 }
579 
580 void MCObjectStreamer::emitCVLinetableDirective(unsigned FunctionId,
581                                                 const MCSymbol *Begin,
582                                                 const MCSymbol *End) {
583   getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin,
584                                                        End);
585   this->MCStreamer::emitCVLinetableDirective(FunctionId, Begin, End);
586 }
587 
588 void MCObjectStreamer::emitCVInlineLinetableDirective(
589     unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum,
590     const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) {
591   getContext().getCVContext().emitInlineLineTableForFunction(
592       *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym,
593       FnEndSym);
594   this->MCStreamer::emitCVInlineLinetableDirective(
595       PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
596 }
597 
598 void MCObjectStreamer::emitCVDefRangeDirective(
599     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
600     StringRef FixedSizePortion) {
601   MCFragment *Frag =
602       getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion);
603   // Attach labels that were pending before we created the defrange fragment to
604   // the beginning of the new fragment.
605   flushPendingLabels(Frag, 0);
606   this->MCStreamer::emitCVDefRangeDirective(Ranges, FixedSizePortion);
607 }
608 
609 void MCObjectStreamer::emitCVStringTableDirective() {
610   getContext().getCVContext().emitStringTable(*this);
611 }
612 void MCObjectStreamer::emitCVFileChecksumsDirective() {
613   getContext().getCVContext().emitFileChecksums(*this);
614 }
615 
616 void MCObjectStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
617   getContext().getCVContext().emitFileChecksumOffset(*this, FileNo);
618 }
619 
620 void MCObjectStreamer::emitBytes(StringRef Data) {
621   MCDwarfLineEntry::make(this, getCurrentSectionOnly());
622   MCDataFragment *DF = getOrCreateDataFragment();
623   flushPendingLabels(DF, DF->getContents().size());
624   DF->getContents().append(Data.begin(), Data.end());
625 }
626 
627 void MCObjectStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
628                                             unsigned ValueSize,
629                                             unsigned MaxBytesToEmit) {
630   if (MaxBytesToEmit == 0)
631     MaxBytesToEmit = Alignment.value();
632   insert(getContext().allocFragment<MCAlignFragment>(
633       Alignment, Value, ValueSize, MaxBytesToEmit));
634 
635   // Update the maximum alignment on the current section if necessary.
636   MCSection *CurSec = getCurrentSectionOnly();
637   CurSec->ensureMinAlignment(Alignment);
638 }
639 
640 void MCObjectStreamer::emitCodeAlignment(Align Alignment,
641                                          const MCSubtargetInfo *STI,
642                                          unsigned MaxBytesToEmit) {
643   emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
644   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true, STI);
645 }
646 
647 void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
648                                          unsigned char Value,
649                                          SMLoc Loc) {
650   insert(getContext().allocFragment<MCOrgFragment>(*Offset, Value, Loc));
651 }
652 
653 // Associate DTPRel32 fixup with data and resize data area
654 void MCObjectStreamer::emitDTPRel32Value(const MCExpr *Value) {
655   MCDataFragment *DF = getOrCreateDataFragment();
656   flushPendingLabels(DF, DF->getContents().size());
657 
658   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
659                                             Value, FK_DTPRel_4));
660   DF->getContents().resize(DF->getContents().size() + 4, 0);
661 }
662 
663 // Associate DTPRel64 fixup with data and resize data area
664 void MCObjectStreamer::emitDTPRel64Value(const MCExpr *Value) {
665   MCDataFragment *DF = getOrCreateDataFragment();
666   flushPendingLabels(DF, DF->getContents().size());
667 
668   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
669                                             Value, FK_DTPRel_8));
670   DF->getContents().resize(DF->getContents().size() + 8, 0);
671 }
672 
673 // Associate TPRel32 fixup with data and resize data area
674 void MCObjectStreamer::emitTPRel32Value(const MCExpr *Value) {
675   MCDataFragment *DF = getOrCreateDataFragment();
676   flushPendingLabels(DF, DF->getContents().size());
677 
678   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
679                                             Value, FK_TPRel_4));
680   DF->getContents().resize(DF->getContents().size() + 4, 0);
681 }
682 
683 // Associate TPRel64 fixup with data and resize data area
684 void MCObjectStreamer::emitTPRel64Value(const MCExpr *Value) {
685   MCDataFragment *DF = getOrCreateDataFragment();
686   flushPendingLabels(DF, DF->getContents().size());
687 
688   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
689                                             Value, FK_TPRel_8));
690   DF->getContents().resize(DF->getContents().size() + 8, 0);
691 }
692 
693 // Associate GPRel32 fixup with data and resize data area
694 void MCObjectStreamer::emitGPRel32Value(const MCExpr *Value) {
695   MCDataFragment *DF = getOrCreateDataFragment();
696   flushPendingLabels(DF, DF->getContents().size());
697 
698   DF->getFixups().push_back(
699       MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4));
700   DF->getContents().resize(DF->getContents().size() + 4, 0);
701 }
702 
703 // Associate GPRel64 fixup with data and resize data area
704 void MCObjectStreamer::emitGPRel64Value(const MCExpr *Value) {
705   MCDataFragment *DF = getOrCreateDataFragment();
706   flushPendingLabels(DF, DF->getContents().size());
707 
708   DF->getFixups().push_back(
709       MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4));
710   DF->getContents().resize(DF->getContents().size() + 8, 0);
711 }
712 
713 static std::optional<std::pair<bool, std::string>>
714 getOffsetAndDataFragment(const MCSymbol &Symbol, uint32_t &RelocOffset,
715                          MCDataFragment *&DF) {
716   if (Symbol.isVariable()) {
717     const MCExpr *SymbolExpr = Symbol.getVariableValue();
718     MCValue OffsetVal;
719     if(!SymbolExpr->evaluateAsRelocatable(OffsetVal, nullptr, nullptr))
720       return std::make_pair(false,
721                             std::string("symbol in .reloc offset is not "
722                                         "relocatable"));
723     if (OffsetVal.isAbsolute()) {
724       RelocOffset = OffsetVal.getConstant();
725       MCFragment *Fragment = Symbol.getFragment();
726       // FIXME Support symbols with no DF. For example:
727       // .reloc .data, ENUM_VALUE, <some expr>
728       if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
729         return std::make_pair(false,
730                               std::string("symbol in offset has no data "
731                                           "fragment"));
732       DF = cast<MCDataFragment>(Fragment);
733       return std::nullopt;
734     }
735 
736     if (OffsetVal.getSymB())
737       return std::make_pair(false,
738                             std::string(".reloc symbol offset is not "
739                                         "representable"));
740 
741     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA());
742     if (!SRE.getSymbol().isDefined())
743       return std::make_pair(false,
744                             std::string("symbol used in the .reloc offset is "
745                                         "not defined"));
746 
747     if (SRE.getSymbol().isVariable())
748       return std::make_pair(false,
749                             std::string("symbol used in the .reloc offset is "
750                                         "variable"));
751 
752     MCFragment *Fragment = SRE.getSymbol().getFragment();
753     // FIXME Support symbols with no DF. For example:
754     // .reloc .data, ENUM_VALUE, <some expr>
755     if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
756       return std::make_pair(false,
757                             std::string("symbol in offset has no data "
758                                         "fragment"));
759     RelocOffset = SRE.getSymbol().getOffset() + OffsetVal.getConstant();
760     DF = cast<MCDataFragment>(Fragment);
761   } else {
762     RelocOffset = Symbol.getOffset();
763     MCFragment *Fragment = Symbol.getFragment();
764     // FIXME Support symbols with no DF. For example:
765     // .reloc .data, ENUM_VALUE, <some expr>
766     if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
767       return std::make_pair(false,
768                             std::string("symbol in offset has no data "
769                                         "fragment"));
770     DF = cast<MCDataFragment>(Fragment);
771   }
772   return std::nullopt;
773 }
774 
775 std::optional<std::pair<bool, std::string>>
776 MCObjectStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
777                                      const MCExpr *Expr, SMLoc Loc,
778                                      const MCSubtargetInfo &STI) {
779   std::optional<MCFixupKind> MaybeKind =
780       Assembler->getBackend().getFixupKind(Name);
781   if (!MaybeKind)
782     return std::make_pair(true, std::string("unknown relocation name"));
783 
784   MCFixupKind Kind = *MaybeKind;
785   if (Expr)
786     visitUsedExpr(*Expr);
787   else
788     Expr =
789         MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
790 
791   MCDataFragment *DF = getOrCreateDataFragment(&STI);
792   flushPendingLabels(DF, DF->getContents().size());
793 
794   MCValue OffsetVal;
795   if (!Offset.evaluateAsRelocatable(OffsetVal, nullptr, nullptr))
796     return std::make_pair(false,
797                           std::string(".reloc offset is not relocatable"));
798   if (OffsetVal.isAbsolute()) {
799     if (OffsetVal.getConstant() < 0)
800       return std::make_pair(false, std::string(".reloc offset is negative"));
801     DF->getFixups().push_back(
802         MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc));
803     return std::nullopt;
804   }
805   if (OffsetVal.getSymB())
806     return std::make_pair(false,
807                           std::string(".reloc offset is not representable"));
808 
809   const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA());
810   const MCSymbol &Symbol = SRE.getSymbol();
811   if (Symbol.isDefined()) {
812     uint32_t SymbolOffset = 0;
813     std::optional<std::pair<bool, std::string>> Error =
814         getOffsetAndDataFragment(Symbol, SymbolOffset, DF);
815 
816     if (Error != std::nullopt)
817       return Error;
818 
819     DF->getFixups().push_back(
820         MCFixup::create(SymbolOffset + OffsetVal.getConstant(),
821                         Expr, Kind, Loc));
822     return std::nullopt;
823   }
824 
825   PendingFixups.emplace_back(
826       &SRE.getSymbol(), DF,
827       MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc));
828   return std::nullopt;
829 }
830 
831 void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
832                                 SMLoc Loc) {
833   MCDataFragment *DF = getOrCreateDataFragment();
834   flushPendingLabels(DF, DF->getContents().size());
835 
836   assert(getCurrentSectionOnly() && "need a section");
837   insert(
838       getContext().allocFragment<MCFillFragment>(FillValue, 1, NumBytes, Loc));
839 }
840 
841 void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
842                                 int64_t Expr, SMLoc Loc) {
843   int64_t IntNumValues;
844   // Do additional checking now if we can resolve the value.
845   if (NumValues.evaluateAsAbsolute(IntNumValues, getAssemblerPtr())) {
846     if (IntNumValues < 0) {
847       getContext().getSourceManager()->PrintMessage(
848           Loc, SourceMgr::DK_Warning,
849           "'.fill' directive with negative repeat count has no effect");
850       return;
851     }
852     // Emit now if we can for better errors.
853     int64_t NonZeroSize = Size > 4 ? 4 : Size;
854     Expr &= ~0ULL >> (64 - NonZeroSize * 8);
855     for (uint64_t i = 0, e = IntNumValues; i != e; ++i) {
856       emitIntValue(Expr, NonZeroSize);
857       if (NonZeroSize < Size)
858         emitIntValue(0, Size - NonZeroSize);
859     }
860     return;
861   }
862 
863   // Otherwise emit as fragment.
864   MCDataFragment *DF = getOrCreateDataFragment();
865   flushPendingLabels(DF, DF->getContents().size());
866 
867   assert(getCurrentSectionOnly() && "need a section");
868   insert(
869       getContext().allocFragment<MCFillFragment>(Expr, Size, NumValues, Loc));
870 }
871 
872 void MCObjectStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLength,
873                                 SMLoc Loc, const MCSubtargetInfo &STI) {
874   // Emit an NOP fragment.
875   MCDataFragment *DF = getOrCreateDataFragment();
876   flushPendingLabels(DF, DF->getContents().size());
877 
878   assert(getCurrentSectionOnly() && "need a section");
879 
880   insert(getContext().allocFragment<MCNopsFragment>(
881       NumBytes, ControlledNopLength, Loc, STI));
882 }
883 
884 void MCObjectStreamer::emitFileDirective(StringRef Filename) {
885   getAssembler().addFileName(Filename);
886 }
887 
888 void MCObjectStreamer::emitFileDirective(StringRef Filename,
889                                          StringRef CompilerVersion,
890                                          StringRef TimeStamp,
891                                          StringRef Description) {
892   getAssembler().addFileName(Filename);
893   getAssembler().setCompilerVersion(CompilerVersion.str());
894   // TODO: add TimeStamp and Description to .file symbol table entry
895   // with the integrated assembler.
896 }
897 
898 void MCObjectStreamer::emitAddrsig() {
899   getAssembler().getWriter().emitAddrsigSection();
900 }
901 
902 void MCObjectStreamer::emitAddrsigSym(const MCSymbol *Sym) {
903   getAssembler().getWriter().addAddrsigSymbol(Sym);
904 }
905 
906 void MCObjectStreamer::finishImpl() {
907   getContext().RemapDebugPaths();
908 
909   // If we are generating dwarf for assembly source files dump out the sections.
910   if (getContext().getGenDwarfForAssembly())
911     MCGenDwarfInfo::Emit(this);
912 
913   // Dump out the dwarf file & directory tables and line tables.
914   MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams());
915 
916   // Emit pseudo probes for the current module.
917   MCPseudoProbeTable::emit(this);
918 
919   // Update any remaining pending labels with empty data fragments.
920   flushPendingLabels();
921 
922   resolvePendingFixups();
923   getAssembler().Finish();
924 }
925