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