xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCAssembler.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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/MCAssembler.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Statistic.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCAsmLayout.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCCodeView.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Alignment.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/EndianStream.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cassert>
42 #include <cstdint>
43 #include <cstring>
44 #include <tuple>
45 #include <utility>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "assembler"
50 
51 namespace {
52 namespace stats {
53 
54 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
55 STATISTIC(EmittedRelaxableFragments,
56           "Number of emitted assembler fragments - relaxable");
57 STATISTIC(EmittedDataFragments,
58           "Number of emitted assembler fragments - data");
59 STATISTIC(EmittedCompactEncodedInstFragments,
60           "Number of emitted assembler fragments - compact encoded inst");
61 STATISTIC(EmittedAlignFragments,
62           "Number of emitted assembler fragments - align");
63 STATISTIC(EmittedFillFragments,
64           "Number of emitted assembler fragments - fill");
65 STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
66 STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
67 STATISTIC(evaluateFixup, "Number of evaluated fixups");
68 STATISTIC(FragmentLayouts, "Number of fragment layouts");
69 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
70 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
71 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
72 
73 } // end namespace stats
74 } // end anonymous namespace
75 
76 // FIXME FIXME FIXME: There are number of places in this file where we convert
77 // what is a 64-bit assembler value used for computation into a value in the
78 // object file, which may truncate it. We should detect that truncation where
79 // invalid and report errors back.
80 
81 /* *** */
82 
83 MCAssembler::MCAssembler(MCContext &Context,
84                          std::unique_ptr<MCAsmBackend> Backend,
85                          std::unique_ptr<MCCodeEmitter> Emitter,
86                          std::unique_ptr<MCObjectWriter> Writer)
87     : Context(Context), Backend(std::move(Backend)),
88       Emitter(std::move(Emitter)), Writer(std::move(Writer)),
89       BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
90       IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
91   VersionInfo.Major = 0; // Major version == 0 for "none specified"
92 }
93 
94 MCAssembler::~MCAssembler() = default;
95 
96 void MCAssembler::reset() {
97   Sections.clear();
98   Symbols.clear();
99   IndirectSymbols.clear();
100   DataRegions.clear();
101   LinkerOptions.clear();
102   FileNames.clear();
103   ThumbFuncs.clear();
104   BundleAlignSize = 0;
105   RelaxAll = false;
106   SubsectionsViaSymbols = false;
107   IncrementalLinkerCompatible = false;
108   ELFHeaderEFlags = 0;
109   LOHContainer.reset();
110   VersionInfo.Major = 0;
111   VersionInfo.SDKVersion = VersionTuple();
112 
113   // reset objects owned by us
114   if (getBackendPtr())
115     getBackendPtr()->reset();
116   if (getEmitterPtr())
117     getEmitterPtr()->reset();
118   if (getWriterPtr())
119     getWriterPtr()->reset();
120   getLOHContainer().reset();
121 }
122 
123 bool MCAssembler::registerSection(MCSection &Section) {
124   if (Section.isRegistered())
125     return false;
126   Sections.push_back(&Section);
127   Section.setIsRegistered(true);
128   return true;
129 }
130 
131 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
132   if (ThumbFuncs.count(Symbol))
133     return true;
134 
135   if (!Symbol->isVariable())
136     return false;
137 
138   const MCExpr *Expr = Symbol->getVariableValue();
139 
140   MCValue V;
141   if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
142     return false;
143 
144   if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
145     return false;
146 
147   const MCSymbolRefExpr *Ref = V.getSymA();
148   if (!Ref)
149     return false;
150 
151   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
152     return false;
153 
154   const MCSymbol &Sym = Ref->getSymbol();
155   if (!isThumbFunc(&Sym))
156     return false;
157 
158   ThumbFuncs.insert(Symbol); // Cache it.
159   return true;
160 }
161 
162 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
163   // Non-temporary labels should always be visible to the linker.
164   if (!Symbol.isTemporary())
165     return true;
166 
167   if (Symbol.isUsedInReloc())
168     return true;
169 
170   return false;
171 }
172 
173 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
174   // Linker visible symbols define atoms.
175   if (isSymbolLinkerVisible(S))
176     return &S;
177 
178   // Absolute and undefined symbols have no defining atom.
179   if (!S.isInSection())
180     return nullptr;
181 
182   // Non-linker visible symbols in sections which can't be atomized have no
183   // defining atom.
184   if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
185           *S.getFragment()->getParent()))
186     return nullptr;
187 
188   // Otherwise, return the atom for the containing fragment.
189   return S.getFragment()->getAtom();
190 }
191 
192 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
193                                 const MCFixup &Fixup, const MCFragment *DF,
194                                 MCValue &Target, uint64_t &Value,
195                                 bool &WasForced) const {
196   ++stats::evaluateFixup;
197 
198   // FIXME: This code has some duplication with recordRelocation. We should
199   // probably merge the two into a single callback that tries to evaluate a
200   // fixup and records a relocation if one is needed.
201 
202   // On error claim to have completely evaluated the fixup, to prevent any
203   // further processing from being done.
204   const MCExpr *Expr = Fixup.getValue();
205   MCContext &Ctx = getContext();
206   Value = 0;
207   WasForced = false;
208   if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
209     Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
210     return true;
211   }
212   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
213     if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
214       Ctx.reportError(Fixup.getLoc(),
215                       "unsupported subtraction of qualified symbol");
216       return true;
217     }
218   }
219 
220   assert(getBackendPtr() && "Expected assembler backend");
221   bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
222                   MCFixupKindInfo::FKF_IsTarget;
223 
224   if (IsTarget)
225     return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
226                                             Value, WasForced);
227 
228   unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
229   bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
230                  MCFixupKindInfo::FKF_IsPCRel;
231 
232   bool IsResolved = false;
233   if (IsPCRel) {
234     if (Target.getSymB()) {
235       IsResolved = false;
236     } else if (!Target.getSymA()) {
237       IsResolved = false;
238     } else {
239       const MCSymbolRefExpr *A = Target.getSymA();
240       const MCSymbol &SA = A->getSymbol();
241       if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
242         IsResolved = false;
243       } else if (auto *Writer = getWriterPtr()) {
244         IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
245                      Writer->isSymbolRefDifferenceFullyResolvedImpl(
246                          *this, SA, *DF, false, true);
247       }
248     }
249   } else {
250     IsResolved = Target.isAbsolute();
251   }
252 
253   Value = Target.getConstant();
254 
255   if (const MCSymbolRefExpr *A = Target.getSymA()) {
256     const MCSymbol &Sym = A->getSymbol();
257     if (Sym.isDefined())
258       Value += Layout.getSymbolOffset(Sym);
259   }
260   if (const MCSymbolRefExpr *B = Target.getSymB()) {
261     const MCSymbol &Sym = B->getSymbol();
262     if (Sym.isDefined())
263       Value -= Layout.getSymbolOffset(Sym);
264   }
265 
266   bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
267                        MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
268   assert((ShouldAlignPC ? IsPCRel : true) &&
269     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
270 
271   if (IsPCRel) {
272     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
273 
274     // A number of ARM fixups in Thumb mode require that the effective PC
275     // address be determined as the 32-bit aligned version of the actual offset.
276     if (ShouldAlignPC) Offset &= ~0x3;
277     Value -= Offset;
278   }
279 
280   // Let the backend force a relocation if needed.
281   if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
282     IsResolved = false;
283     WasForced = true;
284   }
285 
286   return IsResolved;
287 }
288 
289 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
290                                           const MCFragment &F) const {
291   assert(getBackendPtr() && "Requires assembler backend");
292   switch (F.getKind()) {
293   case MCFragment::FT_Data:
294     return cast<MCDataFragment>(F).getContents().size();
295   case MCFragment::FT_Relaxable:
296     return cast<MCRelaxableFragment>(F).getContents().size();
297   case MCFragment::FT_CompactEncodedInst:
298     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
299   case MCFragment::FT_Fill: {
300     auto &FF = cast<MCFillFragment>(F);
301     int64_t NumValues = 0;
302     if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
303       getContext().reportError(FF.getLoc(),
304                                "expected assembly-time absolute expression");
305       return 0;
306     }
307     int64_t Size = NumValues * FF.getValueSize();
308     if (Size < 0) {
309       getContext().reportError(FF.getLoc(), "invalid number of bytes");
310       return 0;
311     }
312     return Size;
313   }
314 
315   case MCFragment::FT_Nops:
316     return cast<MCNopsFragment>(F).getNumBytes();
317 
318   case MCFragment::FT_LEB:
319     return cast<MCLEBFragment>(F).getContents().size();
320 
321   case MCFragment::FT_BoundaryAlign:
322     return cast<MCBoundaryAlignFragment>(F).getSize();
323 
324   case MCFragment::FT_SymbolId:
325     return 4;
326 
327   case MCFragment::FT_Align: {
328     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
329     unsigned Offset = Layout.getFragmentOffset(&AF);
330     unsigned Size = offsetToAlignment(Offset, Align(AF.getAlignment()));
331 
332     // Insert extra Nops for code alignment if the target define
333     // shouldInsertExtraNopBytesForCodeAlign target hook.
334     if (AF.getParent()->UseCodeAlign() && AF.hasEmitNops() &&
335         getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
336       return Size;
337 
338     // If we are padding with nops, force the padding to be larger than the
339     // minimum nop size.
340     if (Size > 0 && AF.hasEmitNops()) {
341       while (Size % getBackend().getMinimumNopSize())
342         Size += AF.getAlignment();
343     }
344     if (Size > AF.getMaxBytesToEmit())
345       return 0;
346     return Size;
347   }
348 
349   case MCFragment::FT_Org: {
350     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
351     MCValue Value;
352     if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
353       getContext().reportError(OF.getLoc(),
354                                "expected assembly-time absolute expression");
355         return 0;
356     }
357 
358     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
359     int64_t TargetLocation = Value.getConstant();
360     if (const MCSymbolRefExpr *A = Value.getSymA()) {
361       uint64_t Val;
362       if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
363         getContext().reportError(OF.getLoc(), "expected absolute expression");
364         return 0;
365       }
366       TargetLocation += Val;
367     }
368     int64_t Size = TargetLocation - FragmentOffset;
369     if (Size < 0 || Size >= 0x40000000) {
370       getContext().reportError(
371           OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
372                            "' (at offset '" + Twine(FragmentOffset) + "')");
373       return 0;
374     }
375     return Size;
376   }
377 
378   case MCFragment::FT_Dwarf:
379     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
380   case MCFragment::FT_DwarfFrame:
381     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
382   case MCFragment::FT_CVInlineLines:
383     return cast<MCCVInlineLineTableFragment>(F).getContents().size();
384   case MCFragment::FT_CVDefRange:
385     return cast<MCCVDefRangeFragment>(F).getContents().size();
386   case MCFragment::FT_PseudoProbe:
387     return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
388   case MCFragment::FT_Dummy:
389     llvm_unreachable("Should not have been added");
390   }
391 
392   llvm_unreachable("invalid fragment kind");
393 }
394 
395 void MCAsmLayout::layoutFragment(MCFragment *F) {
396   MCFragment *Prev = F->getPrevNode();
397 
398   // We should never try to recompute something which is valid.
399   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
400   // We should never try to compute the fragment layout if its predecessor
401   // isn't valid.
402   assert((!Prev || isFragmentValid(Prev)) &&
403          "Attempt to compute fragment before its predecessor!");
404 
405   assert(!F->IsBeingLaidOut && "Already being laid out!");
406   F->IsBeingLaidOut = true;
407 
408   ++stats::FragmentLayouts;
409 
410   // Compute fragment offset and size.
411   if (Prev)
412     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
413   else
414     F->Offset = 0;
415   F->IsBeingLaidOut = false;
416   LastValidFragment[F->getParent()] = F;
417 
418   // If bundling is enabled and this fragment has instructions in it, it has to
419   // obey the bundling restrictions. With padding, we'll have:
420   //
421   //
422   //        BundlePadding
423   //             |||
424   // -------------------------------------
425   //   Prev  |##########|       F        |
426   // -------------------------------------
427   //                    ^
428   //                    |
429   //                    F->Offset
430   //
431   // The fragment's offset will point to after the padding, and its computed
432   // size won't include the padding.
433   //
434   // When the -mc-relax-all flag is used, we optimize bundling by writting the
435   // padding directly into fragments when the instructions are emitted inside
436   // the streamer. When the fragment is larger than the bundle size, we need to
437   // ensure that it's bundle aligned. This means that if we end up with
438   // multiple fragments, we must emit bundle padding between fragments.
439   //
440   // ".align N" is an example of a directive that introduces multiple
441   // fragments. We could add a special case to handle ".align N" by emitting
442   // within-fragment padding (which would produce less padding when N is less
443   // than the bundle size), but for now we don't.
444   //
445   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
446     assert(isa<MCEncodedFragment>(F) &&
447            "Only MCEncodedFragment implementations have instructions");
448     MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
449     uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
450 
451     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
452       report_fatal_error("Fragment can't be larger than a bundle size");
453 
454     uint64_t RequiredBundlePadding =
455         computeBundlePadding(Assembler, EF, EF->Offset, FSize);
456     if (RequiredBundlePadding > UINT8_MAX)
457       report_fatal_error("Padding cannot exceed 255 bytes");
458     EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
459     EF->Offset += RequiredBundlePadding;
460   }
461 }
462 
463 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
464   bool New = !Symbol.isRegistered();
465   if (Created)
466     *Created = New;
467   if (New) {
468     Symbol.setIsRegistered(true);
469     Symbols.push_back(&Symbol);
470   }
471 }
472 
473 void MCAssembler::writeFragmentPadding(raw_ostream &OS,
474                                        const MCEncodedFragment &EF,
475                                        uint64_t FSize) const {
476   assert(getBackendPtr() && "Expected assembler backend");
477   // Should NOP padding be written out before this fragment?
478   unsigned BundlePadding = EF.getBundlePadding();
479   if (BundlePadding > 0) {
480     assert(isBundlingEnabled() &&
481            "Writing bundle padding with disabled bundling");
482     assert(EF.hasInstructions() &&
483            "Writing bundle padding for a fragment without instructions");
484 
485     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
486     const MCSubtargetInfo *STI = EF.getSubtargetInfo();
487     if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
488       // If the padding itself crosses a bundle boundary, it must be emitted
489       // in 2 pieces, since even nop instructions must not cross boundaries.
490       //             v--------------v   <- BundleAlignSize
491       //        v---------v             <- BundlePadding
492       // ----------------------------
493       // | Prev |####|####|    F    |
494       // ----------------------------
495       //        ^-------------------^   <- TotalLength
496       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
497       if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
498         report_fatal_error("unable to write NOP sequence of " +
499                            Twine(DistanceToBoundary) + " bytes");
500       BundlePadding -= DistanceToBoundary;
501     }
502     if (!getBackend().writeNopData(OS, BundlePadding, STI))
503       report_fatal_error("unable to write NOP sequence of " +
504                          Twine(BundlePadding) + " bytes");
505   }
506 }
507 
508 /// Write the fragment \p F to the output file.
509 static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
510                           const MCAsmLayout &Layout, const MCFragment &F) {
511   // FIXME: Embed in fragments instead?
512   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
513 
514   support::endianness Endian = Asm.getBackend().Endian;
515 
516   if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
517     Asm.writeFragmentPadding(OS, *EF, FragmentSize);
518 
519   // This variable (and its dummy usage) is to participate in the assert at
520   // the end of the function.
521   uint64_t Start = OS.tell();
522   (void) Start;
523 
524   ++stats::EmittedFragments;
525 
526   switch (F.getKind()) {
527   case MCFragment::FT_Align: {
528     ++stats::EmittedAlignFragments;
529     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
530     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
531 
532     uint64_t Count = FragmentSize / AF.getValueSize();
533 
534     // FIXME: This error shouldn't actually occur (the front end should emit
535     // multiple .align directives to enforce the semantics it wants), but is
536     // severe enough that we want to report it. How to handle this?
537     if (Count * AF.getValueSize() != FragmentSize)
538       report_fatal_error("undefined .align directive, value size '" +
539                         Twine(AF.getValueSize()) +
540                         "' is not a divisor of padding size '" +
541                         Twine(FragmentSize) + "'");
542 
543     // See if we are aligning with nops, and if so do that first to try to fill
544     // the Count bytes.  Then if that did not fill any bytes or there are any
545     // bytes left to fill use the Value and ValueSize to fill the rest.
546     // If we are aligning with nops, ask that target to emit the right data.
547     if (AF.hasEmitNops()) {
548       if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
549         report_fatal_error("unable to write nop sequence of " +
550                           Twine(Count) + " bytes");
551       break;
552     }
553 
554     // Otherwise, write out in multiples of the value size.
555     for (uint64_t i = 0; i != Count; ++i) {
556       switch (AF.getValueSize()) {
557       default: llvm_unreachable("Invalid size!");
558       case 1: OS << char(AF.getValue()); break;
559       case 2:
560         support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
561         break;
562       case 4:
563         support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
564         break;
565       case 8:
566         support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
567         break;
568       }
569     }
570     break;
571   }
572 
573   case MCFragment::FT_Data:
574     ++stats::EmittedDataFragments;
575     OS << cast<MCDataFragment>(F).getContents();
576     break;
577 
578   case MCFragment::FT_Relaxable:
579     ++stats::EmittedRelaxableFragments;
580     OS << cast<MCRelaxableFragment>(F).getContents();
581     break;
582 
583   case MCFragment::FT_CompactEncodedInst:
584     ++stats::EmittedCompactEncodedInstFragments;
585     OS << cast<MCCompactEncodedInstFragment>(F).getContents();
586     break;
587 
588   case MCFragment::FT_Fill: {
589     ++stats::EmittedFillFragments;
590     const MCFillFragment &FF = cast<MCFillFragment>(F);
591     uint64_t V = FF.getValue();
592     unsigned VSize = FF.getValueSize();
593     const unsigned MaxChunkSize = 16;
594     char Data[MaxChunkSize];
595     assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
596     // Duplicate V into Data as byte vector to reduce number of
597     // writes done. As such, do endian conversion here.
598     for (unsigned I = 0; I != VSize; ++I) {
599       unsigned index = Endian == support::little ? I : (VSize - I - 1);
600       Data[I] = uint8_t(V >> (index * 8));
601     }
602     for (unsigned I = VSize; I < MaxChunkSize; ++I)
603       Data[I] = Data[I - VSize];
604 
605     // Set to largest multiple of VSize in Data.
606     const unsigned NumPerChunk = MaxChunkSize / VSize;
607     // Set ChunkSize to largest multiple of VSize in Data
608     const unsigned ChunkSize = VSize * NumPerChunk;
609 
610     // Do copies by chunk.
611     StringRef Ref(Data, ChunkSize);
612     for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
613       OS << Ref;
614 
615     // do remainder if needed.
616     unsigned TrailingCount = FragmentSize % ChunkSize;
617     if (TrailingCount)
618       OS.write(Data, TrailingCount);
619     break;
620   }
621 
622   case MCFragment::FT_Nops: {
623     ++stats::EmittedNopsFragments;
624     const MCNopsFragment &NF = cast<MCNopsFragment>(F);
625 
626     int64_t NumBytes = NF.getNumBytes();
627     int64_t ControlledNopLength = NF.getControlledNopLength();
628     int64_t MaximumNopLength =
629         Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
630 
631     assert(NumBytes > 0 && "Expected positive NOPs fragment size");
632     assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
633 
634     if (ControlledNopLength > MaximumNopLength) {
635       Asm.getContext().reportError(NF.getLoc(),
636                                    "illegal NOP size " +
637                                        std::to_string(ControlledNopLength) +
638                                        ". (expected within [0, " +
639                                        std::to_string(MaximumNopLength) + "])");
640       // Clamp the NOP length as reportError does not stop the execution
641       // immediately.
642       ControlledNopLength = MaximumNopLength;
643     }
644 
645     // Use maximum value if the size of each NOP is not specified
646     if (!ControlledNopLength)
647       ControlledNopLength = MaximumNopLength;
648 
649     while (NumBytes) {
650       uint64_t NumBytesToEmit =
651           (uint64_t)std::min(NumBytes, ControlledNopLength);
652       assert(NumBytesToEmit && "try to emit empty NOP instruction");
653       if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
654                                          NF.getSubtargetInfo())) {
655         report_fatal_error("unable to write nop sequence of the remaining " +
656                            Twine(NumBytesToEmit) + " bytes");
657         break;
658       }
659       NumBytes -= NumBytesToEmit;
660     }
661     break;
662   }
663 
664   case MCFragment::FT_LEB: {
665     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
666     OS << LF.getContents();
667     break;
668   }
669 
670   case MCFragment::FT_BoundaryAlign: {
671     const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
672     if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
673       report_fatal_error("unable to write nop sequence of " +
674                          Twine(FragmentSize) + " bytes");
675     break;
676   }
677 
678   case MCFragment::FT_SymbolId: {
679     const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
680     support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
681     break;
682   }
683 
684   case MCFragment::FT_Org: {
685     ++stats::EmittedOrgFragments;
686     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
687 
688     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
689       OS << char(OF.getValue());
690 
691     break;
692   }
693 
694   case MCFragment::FT_Dwarf: {
695     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
696     OS << OF.getContents();
697     break;
698   }
699   case MCFragment::FT_DwarfFrame: {
700     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
701     OS << CF.getContents();
702     break;
703   }
704   case MCFragment::FT_CVInlineLines: {
705     const auto &OF = cast<MCCVInlineLineTableFragment>(F);
706     OS << OF.getContents();
707     break;
708   }
709   case MCFragment::FT_CVDefRange: {
710     const auto &DRF = cast<MCCVDefRangeFragment>(F);
711     OS << DRF.getContents();
712     break;
713   }
714   case MCFragment::FT_PseudoProbe: {
715     const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
716     OS << PF.getContents();
717     break;
718   }
719   case MCFragment::FT_Dummy:
720     llvm_unreachable("Should not have been added");
721   }
722 
723   assert(OS.tell() - Start == FragmentSize &&
724          "The stream should advance by fragment size");
725 }
726 
727 void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
728                                    const MCAsmLayout &Layout) const {
729   assert(getBackendPtr() && "Expected assembler backend");
730 
731   // Ignore virtual sections.
732   if (Sec->isVirtualSection()) {
733     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
734 
735     // Check that contents are only things legal inside a virtual section.
736     for (const MCFragment &F : *Sec) {
737       switch (F.getKind()) {
738       default: llvm_unreachable("Invalid fragment in virtual section!");
739       case MCFragment::FT_Data: {
740         // Check that we aren't trying to write a non-zero contents (or fixups)
741         // into a virtual section. This is to support clients which use standard
742         // directives to fill the contents of virtual sections.
743         const MCDataFragment &DF = cast<MCDataFragment>(F);
744         if (DF.fixup_begin() != DF.fixup_end())
745           getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
746                                                 " section '" + Sec->getName() +
747                                                 "' cannot have fixups");
748         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
749           if (DF.getContents()[i]) {
750             getContext().reportError(SMLoc(),
751                                      Sec->getVirtualSectionKind() +
752                                          " section '" + Sec->getName() +
753                                          "' cannot have non-zero initializers");
754             break;
755           }
756         break;
757       }
758       case MCFragment::FT_Align:
759         // Check that we aren't trying to write a non-zero value into a virtual
760         // section.
761         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
762                 cast<MCAlignFragment>(F).getValue() == 0) &&
763                "Invalid align in virtual section!");
764         break;
765       case MCFragment::FT_Fill:
766         assert((cast<MCFillFragment>(F).getValue() == 0) &&
767                "Invalid fill in virtual section!");
768         break;
769       case MCFragment::FT_Org:
770         break;
771       }
772     }
773 
774     return;
775   }
776 
777   uint64_t Start = OS.tell();
778   (void)Start;
779 
780   for (const MCFragment &F : *Sec)
781     writeFragment(OS, *this, Layout, F);
782 
783   assert(getContext().hadError() ||
784          OS.tell() - Start == Layout.getSectionAddressSize(Sec));
785 }
786 
787 std::tuple<MCValue, uint64_t, bool>
788 MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
789                          const MCFixup &Fixup) {
790   // Evaluate the fixup.
791   MCValue Target;
792   uint64_t FixedValue;
793   bool WasForced;
794   bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
795                                   WasForced);
796   if (!IsResolved) {
797     // The fixup was unresolved, we need a relocation. Inform the object
798     // writer of the relocation, and give it an opportunity to adjust the
799     // fixup value if need be.
800     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
801   }
802   return std::make_tuple(Target, FixedValue, IsResolved);
803 }
804 
805 void MCAssembler::layout(MCAsmLayout &Layout) {
806   assert(getBackendPtr() && "Expected assembler backend");
807   DEBUG_WITH_TYPE("mc-dump", {
808       errs() << "assembler backend - pre-layout\n--\n";
809       dump(); });
810 
811   // Create dummy fragments and assign section ordinals.
812   unsigned SectionIndex = 0;
813   for (MCSection &Sec : *this) {
814     // Create dummy fragments to eliminate any empty sections, this simplifies
815     // layout.
816     if (Sec.getFragmentList().empty())
817       new MCDataFragment(&Sec);
818 
819     Sec.setOrdinal(SectionIndex++);
820   }
821 
822   // Assign layout order indices to sections and fragments.
823   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
824     MCSection *Sec = Layout.getSectionOrder()[i];
825     Sec->setLayoutOrder(i);
826 
827     unsigned FragmentIndex = 0;
828     for (MCFragment &Frag : *Sec)
829       Frag.setLayoutOrder(FragmentIndex++);
830   }
831 
832   // Layout until everything fits.
833   while (layoutOnce(Layout)) {
834     if (getContext().hadError())
835       return;
836     // Size of fragments in one section can depend on the size of fragments in
837     // another. If any fragment has changed size, we have to re-layout (and
838     // as a result possibly further relax) all.
839     for (MCSection &Sec : *this)
840       Layout.invalidateFragmentsFrom(&*Sec.begin());
841   }
842 
843   DEBUG_WITH_TYPE("mc-dump", {
844       errs() << "assembler backend - post-relaxation\n--\n";
845       dump(); });
846 
847   // Finalize the layout, including fragment lowering.
848   finishLayout(Layout);
849 
850   DEBUG_WITH_TYPE("mc-dump", {
851       errs() << "assembler backend - final-layout\n--\n";
852       dump(); });
853 
854   // Allow the object writer a chance to perform post-layout binding (for
855   // example, to set the index fields in the symbol data).
856   getWriter().executePostLayoutBinding(*this, Layout);
857 
858   // Evaluate and apply the fixups, generating relocation entries as necessary.
859   for (MCSection &Sec : *this) {
860     for (MCFragment &Frag : Sec) {
861       ArrayRef<MCFixup> Fixups;
862       MutableArrayRef<char> Contents;
863       const MCSubtargetInfo *STI = nullptr;
864 
865       // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
866       switch (Frag.getKind()) {
867       default:
868         continue;
869       case MCFragment::FT_Align: {
870         MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
871         // Insert fixup type for code alignment if the target define
872         // shouldInsertFixupForCodeAlign target hook.
873         if (Sec.UseCodeAlign() && AF.hasEmitNops())
874           getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
875         continue;
876       }
877       case MCFragment::FT_Data: {
878         MCDataFragment &DF = cast<MCDataFragment>(Frag);
879         Fixups = DF.getFixups();
880         Contents = DF.getContents();
881         STI = DF.getSubtargetInfo();
882         assert(!DF.hasInstructions() || STI != nullptr);
883         break;
884       }
885       case MCFragment::FT_Relaxable: {
886         MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
887         Fixups = RF.getFixups();
888         Contents = RF.getContents();
889         STI = RF.getSubtargetInfo();
890         assert(!RF.hasInstructions() || STI != nullptr);
891         break;
892       }
893       case MCFragment::FT_CVDefRange: {
894         MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
895         Fixups = CF.getFixups();
896         Contents = CF.getContents();
897         break;
898       }
899       case MCFragment::FT_Dwarf: {
900         MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
901         Fixups = DF.getFixups();
902         Contents = DF.getContents();
903         break;
904       }
905       case MCFragment::FT_DwarfFrame: {
906         MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
907         Fixups = DF.getFixups();
908         Contents = DF.getContents();
909         break;
910       }
911       case MCFragment::FT_PseudoProbe: {
912         MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
913         Fixups = PF.getFixups();
914         Contents = PF.getContents();
915         break;
916       }
917       }
918       for (const MCFixup &Fixup : Fixups) {
919         uint64_t FixedValue;
920         bool IsResolved;
921         MCValue Target;
922         std::tie(Target, FixedValue, IsResolved) =
923             handleFixup(Layout, Frag, Fixup);
924         getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
925                                 IsResolved, STI);
926       }
927     }
928   }
929 }
930 
931 void MCAssembler::Finish() {
932   // Create the layout object.
933   MCAsmLayout Layout(*this);
934   layout(Layout);
935 
936   // Write the object file.
937   stats::ObjectBytes += getWriter().writeObject(*this, Layout);
938 }
939 
940 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
941                                        const MCRelaxableFragment *DF,
942                                        const MCAsmLayout &Layout) const {
943   assert(getBackendPtr() && "Expected assembler backend");
944   MCValue Target;
945   uint64_t Value;
946   bool WasForced;
947   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
948   if (Target.getSymA() &&
949       Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
950       Fixup.getKind() == FK_Data_1)
951     return false;
952   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
953                                                    Layout, WasForced);
954 }
955 
956 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
957                                           const MCAsmLayout &Layout) const {
958   assert(getBackendPtr() && "Expected assembler backend");
959   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
960   // are intentionally pushing out inst fragments, or because we relaxed a
961   // previous instruction to one that doesn't need relaxation.
962   if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
963     return false;
964 
965   for (const MCFixup &Fixup : F->getFixups())
966     if (fixupNeedsRelaxation(Fixup, F, Layout))
967       return true;
968 
969   return false;
970 }
971 
972 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
973                                    MCRelaxableFragment &F) {
974   assert(getEmitterPtr() &&
975          "Expected CodeEmitter defined for relaxInstruction");
976   if (!fragmentNeedsRelaxation(&F, Layout))
977     return false;
978 
979   ++stats::RelaxedInstructions;
980 
981   // FIXME-PERF: We could immediately lower out instructions if we can tell
982   // they are fully resolved, to avoid retesting on later passes.
983 
984   // Relax the fragment.
985 
986   MCInst Relaxed = F.getInst();
987   getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
988 
989   // Encode the new instruction.
990   //
991   // FIXME-PERF: If it matters, we could let the target do this. It can
992   // probably do so more efficiently in many cases.
993   SmallVector<MCFixup, 4> Fixups;
994   SmallString<256> Code;
995   raw_svector_ostream VecOS(Code);
996   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
997 
998   // Update the fragment.
999   F.setInst(Relaxed);
1000   F.getContents() = Code;
1001   F.getFixups() = Fixups;
1002 
1003   return true;
1004 }
1005 
1006 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1007   uint64_t OldSize = LF.getContents().size();
1008   int64_t Value;
1009   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1010   if (!Abs)
1011     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1012   SmallString<8> &Data = LF.getContents();
1013   Data.clear();
1014   raw_svector_ostream OSE(Data);
1015   // The compiler can generate EH table assembly that is impossible to assemble
1016   // without either adding padding to an LEB fragment or adding extra padding
1017   // to a later alignment fragment. To accommodate such tables, relaxation can
1018   // only increase an LEB fragment size here, not decrease it. See PR35809.
1019   if (LF.isSigned())
1020     encodeSLEB128(Value, OSE, OldSize);
1021   else
1022     encodeULEB128(Value, OSE, OldSize);
1023   return OldSize != LF.getContents().size();
1024 }
1025 
1026 /// Check if the branch crosses the boundary.
1027 ///
1028 /// \param StartAddr start address of the fused/unfused branch.
1029 /// \param Size size of the fused/unfused branch.
1030 /// \param BoundaryAlignment alignment requirement of the branch.
1031 /// \returns true if the branch cross the boundary.
1032 static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
1033                              Align BoundaryAlignment) {
1034   uint64_t EndAddr = StartAddr + Size;
1035   return (StartAddr >> Log2(BoundaryAlignment)) !=
1036          ((EndAddr - 1) >> Log2(BoundaryAlignment));
1037 }
1038 
1039 /// Check if the branch is against the boundary.
1040 ///
1041 /// \param StartAddr start address of the fused/unfused branch.
1042 /// \param Size size of the fused/unfused branch.
1043 /// \param BoundaryAlignment alignment requirement of the branch.
1044 /// \returns true if the branch is against the boundary.
1045 static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
1046                               Align BoundaryAlignment) {
1047   uint64_t EndAddr = StartAddr + Size;
1048   return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1049 }
1050 
1051 /// Check if the branch needs padding.
1052 ///
1053 /// \param StartAddr start address of the fused/unfused branch.
1054 /// \param Size size of the fused/unfused branch.
1055 /// \param BoundaryAlignment alignment requirement of the branch.
1056 /// \returns true if the branch needs padding.
1057 static bool needPadding(uint64_t StartAddr, uint64_t Size,
1058                         Align BoundaryAlignment) {
1059   return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1060          isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1061 }
1062 
1063 bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1064                                      MCBoundaryAlignFragment &BF) {
1065   // BoundaryAlignFragment that doesn't need to align any fragment should not be
1066   // relaxed.
1067   if (!BF.getLastFragment())
1068     return false;
1069 
1070   uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1071   uint64_t AlignedSize = 0;
1072   for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1073        F = F->getPrevNode())
1074     AlignedSize += computeFragmentSize(Layout, *F);
1075 
1076   Align BoundaryAlignment = BF.getAlignment();
1077   uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1078                          ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1079                          : 0U;
1080   if (NewSize == BF.getSize())
1081     return false;
1082   BF.setSize(NewSize);
1083   Layout.invalidateFragmentsFrom(&BF);
1084   return true;
1085 }
1086 
1087 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1088                                      MCDwarfLineAddrFragment &DF) {
1089 
1090   bool WasRelaxed;
1091   if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
1092     return WasRelaxed;
1093 
1094   MCContext &Context = Layout.getAssembler().getContext();
1095   uint64_t OldSize = DF.getContents().size();
1096   int64_t AddrDelta;
1097   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1098   assert(Abs && "We created a line delta with an invalid expression");
1099   (void)Abs;
1100   int64_t LineDelta;
1101   LineDelta = DF.getLineDelta();
1102   SmallVectorImpl<char> &Data = DF.getContents();
1103   Data.clear();
1104   raw_svector_ostream OSE(Data);
1105   DF.getFixups().clear();
1106 
1107   MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1108                           AddrDelta, OSE);
1109   return OldSize != Data.size();
1110 }
1111 
1112 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1113                                               MCDwarfCallFrameFragment &DF) {
1114   bool WasRelaxed;
1115   if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
1116     return WasRelaxed;
1117 
1118   MCContext &Context = Layout.getAssembler().getContext();
1119   uint64_t OldSize = DF.getContents().size();
1120   int64_t AddrDelta;
1121   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1122   assert(Abs && "We created call frame with an invalid expression");
1123   (void) Abs;
1124   SmallVectorImpl<char> &Data = DF.getContents();
1125   Data.clear();
1126   raw_svector_ostream OSE(Data);
1127   DF.getFixups().clear();
1128 
1129   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1130   return OldSize != Data.size();
1131 }
1132 
1133 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1134                                          MCCVInlineLineTableFragment &F) {
1135   unsigned OldSize = F.getContents().size();
1136   getContext().getCVContext().encodeInlineLineTable(Layout, F);
1137   return OldSize != F.getContents().size();
1138 }
1139 
1140 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1141                                   MCCVDefRangeFragment &F) {
1142   unsigned OldSize = F.getContents().size();
1143   getContext().getCVContext().encodeDefRange(Layout, F);
1144   return OldSize != F.getContents().size();
1145 }
1146 
1147 bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
1148                                        MCPseudoProbeAddrFragment &PF) {
1149   uint64_t OldSize = PF.getContents().size();
1150   int64_t AddrDelta;
1151   bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1152   assert(Abs && "We created a pseudo probe with an invalid expression");
1153   (void)Abs;
1154   SmallVectorImpl<char> &Data = PF.getContents();
1155   Data.clear();
1156   raw_svector_ostream OSE(Data);
1157   PF.getFixups().clear();
1158 
1159   // AddrDelta is a signed integer
1160   encodeSLEB128(AddrDelta, OSE, OldSize);
1161   return OldSize != Data.size();
1162 }
1163 
1164 bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1165   switch(F.getKind()) {
1166   default:
1167     return false;
1168   case MCFragment::FT_Relaxable:
1169     assert(!getRelaxAll() &&
1170            "Did not expect a MCRelaxableFragment in RelaxAll mode");
1171     return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1172   case MCFragment::FT_Dwarf:
1173     return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1174   case MCFragment::FT_DwarfFrame:
1175     return relaxDwarfCallFrameFragment(Layout,
1176                                        cast<MCDwarfCallFrameFragment>(F));
1177   case MCFragment::FT_LEB:
1178     return relaxLEB(Layout, cast<MCLEBFragment>(F));
1179   case MCFragment::FT_BoundaryAlign:
1180     return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1181   case MCFragment::FT_CVInlineLines:
1182     return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1183   case MCFragment::FT_CVDefRange:
1184     return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1185   case MCFragment::FT_PseudoProbe:
1186     return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
1187   }
1188 }
1189 
1190 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1191   // Holds the first fragment which needed relaxing during this layout. It will
1192   // remain NULL if none were relaxed.
1193   // When a fragment is relaxed, all the fragments following it should get
1194   // invalidated because their offset is going to change.
1195   MCFragment *FirstRelaxedFragment = nullptr;
1196 
1197   // Attempt to relax all the fragments in the section.
1198   for (MCFragment &Frag : Sec) {
1199     // Check if this is a fragment that needs relaxation.
1200     bool RelaxedFrag = relaxFragment(Layout, Frag);
1201     if (RelaxedFrag && !FirstRelaxedFragment)
1202       FirstRelaxedFragment = &Frag;
1203   }
1204   if (FirstRelaxedFragment) {
1205     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1206     return true;
1207   }
1208   return false;
1209 }
1210 
1211 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1212   ++stats::RelaxationSteps;
1213 
1214   bool WasRelaxed = false;
1215   for (MCSection &Sec : *this) {
1216     while (layoutSectionOnce(Layout, Sec))
1217       WasRelaxed = true;
1218   }
1219 
1220   return WasRelaxed;
1221 }
1222 
1223 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1224   assert(getBackendPtr() && "Expected assembler backend");
1225   // The layout is done. Mark every fragment as valid.
1226   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1227     MCSection &Section = *Layout.getSectionOrder()[i];
1228     Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1229     computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1230   }
1231   getBackend().finishLayout(*this, Layout);
1232 }
1233 
1234 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1235 LLVM_DUMP_METHOD void MCAssembler::dump() const{
1236   raw_ostream &OS = errs();
1237 
1238   OS << "<MCAssembler\n";
1239   OS << "  Sections:[\n    ";
1240   for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1241     if (it != begin()) OS << ",\n    ";
1242     it->dump();
1243   }
1244   OS << "],\n";
1245   OS << "  Symbols:[";
1246 
1247   for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1248     if (it != symbol_begin()) OS << ",\n           ";
1249     OS << "(";
1250     it->dump();
1251     OS << ", Index:" << it->getIndex() << ", ";
1252     OS << ")";
1253   }
1254   OS << "]>\n";
1255 }
1256 #endif
1257