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