Home | History | Annotate | Download | only in MC
      1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "llvm/MC/MCAssembler.h"
     11 #include "llvm/ADT/Statistic.h"
     12 #include "llvm/ADT/StringExtras.h"
     13 #include "llvm/ADT/Twine.h"
     14 #include "llvm/MC/MCAsmBackend.h"
     15 #include "llvm/MC/MCAsmInfo.h"
     16 #include "llvm/MC/MCAsmLayout.h"
     17 #include "llvm/MC/MCCodeEmitter.h"
     18 #include "llvm/MC/MCCodeView.h"
     19 #include "llvm/MC/MCContext.h"
     20 #include "llvm/MC/MCDwarf.h"
     21 #include "llvm/MC/MCExpr.h"
     22 #include "llvm/MC/MCFixupKindInfo.h"
     23 #include "llvm/MC/MCObjectWriter.h"
     24 #include "llvm/MC/MCSection.h"
     25 #include "llvm/MC/MCSectionELF.h"
     26 #include "llvm/MC/MCSymbol.h"
     27 #include "llvm/MC/MCValue.h"
     28 #include "llvm/Support/Debug.h"
     29 #include "llvm/Support/ErrorHandling.h"
     30 #include "llvm/Support/LEB128.h"
     31 #include "llvm/Support/TargetRegistry.h"
     32 #include "llvm/Support/raw_ostream.h"
     33 #include <tuple>
     34 using namespace llvm;
     35 
     36 #define DEBUG_TYPE "assembler"
     37 
     38 namespace {
     39 namespace stats {
     40 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
     41 STATISTIC(EmittedRelaxableFragments,
     42           "Number of emitted assembler fragments - relaxable");
     43 STATISTIC(EmittedDataFragments,
     44           "Number of emitted assembler fragments - data");
     45 STATISTIC(EmittedCompactEncodedInstFragments,
     46           "Number of emitted assembler fragments - compact encoded inst");
     47 STATISTIC(EmittedAlignFragments,
     48           "Number of emitted assembler fragments - align");
     49 STATISTIC(EmittedFillFragments,
     50           "Number of emitted assembler fragments - fill");
     51 STATISTIC(EmittedOrgFragments,
     52           "Number of emitted assembler fragments - org");
     53 STATISTIC(evaluateFixup, "Number of evaluated fixups");
     54 STATISTIC(FragmentLayouts, "Number of fragment layouts");
     55 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
     56 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
     57 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
     58 }
     59 }
     60 
     61 // FIXME FIXME FIXME: There are number of places in this file where we convert
     62 // what is a 64-bit assembler value used for computation into a value in the
     63 // object file, which may truncate it. We should detect that truncation where
     64 // invalid and report errors back.
     65 
     66 /* *** */
     67 
     68 MCAssembler::MCAssembler(MCContext &Context, MCAsmBackend &Backend,
     69                          MCCodeEmitter &Emitter, MCObjectWriter &Writer)
     70     : Context(Context), Backend(Backend), Emitter(Emitter), Writer(Writer),
     71       BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
     72       IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
     73   VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
     74 }
     75 
     76 MCAssembler::~MCAssembler() {
     77 }
     78 
     79 void MCAssembler::reset() {
     80   Sections.clear();
     81   Symbols.clear();
     82   IndirectSymbols.clear();
     83   DataRegions.clear();
     84   LinkerOptions.clear();
     85   FileNames.clear();
     86   ThumbFuncs.clear();
     87   BundleAlignSize = 0;
     88   RelaxAll = false;
     89   SubsectionsViaSymbols = false;
     90   IncrementalLinkerCompatible = false;
     91   ELFHeaderEFlags = 0;
     92   LOHContainer.reset();
     93   VersionMinInfo.Major = 0;
     94 
     95   // reset objects owned by us
     96   getBackend().reset();
     97   getEmitter().reset();
     98   getWriter().reset();
     99   getLOHContainer().reset();
    100 }
    101 
    102 bool MCAssembler::registerSection(MCSection &Section) {
    103   if (Section.isRegistered())
    104     return false;
    105   Sections.push_back(&Section);
    106   Section.setIsRegistered(true);
    107   return true;
    108 }
    109 
    110 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
    111   if (ThumbFuncs.count(Symbol))
    112     return true;
    113 
    114   if (!Symbol->isVariable())
    115     return false;
    116 
    117   // FIXME: It looks like gas supports some cases of the form "foo + 2". It
    118   // is not clear if that is a bug or a feature.
    119   const MCExpr *Expr = Symbol->getVariableValue();
    120   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
    121   if (!Ref)
    122     return false;
    123 
    124   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
    125     return false;
    126 
    127   const MCSymbol &Sym = Ref->getSymbol();
    128   if (!isThumbFunc(&Sym))
    129     return false;
    130 
    131   ThumbFuncs.insert(Symbol); // Cache it.
    132   return true;
    133 }
    134 
    135 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
    136   // Non-temporary labels should always be visible to the linker.
    137   if (!Symbol.isTemporary())
    138     return true;
    139 
    140   // Absolute temporary labels are never visible.
    141   if (!Symbol.isInSection())
    142     return false;
    143 
    144   if (Symbol.isUsedInReloc())
    145     return true;
    146 
    147   return false;
    148 }
    149 
    150 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
    151   // Linker visible symbols define atoms.
    152   if (isSymbolLinkerVisible(S))
    153     return &S;
    154 
    155   // Absolute and undefined symbols have no defining atom.
    156   if (!S.isInSection())
    157     return nullptr;
    158 
    159   // Non-linker visible symbols in sections which can't be atomized have no
    160   // defining atom.
    161   if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
    162           *S.getFragment()->getParent()))
    163     return nullptr;
    164 
    165   // Otherwise, return the atom for the containing fragment.
    166   return S.getFragment()->getAtom();
    167 }
    168 
    169 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
    170                                 const MCFixup &Fixup, const MCFragment *DF,
    171                                 MCValue &Target, uint64_t &Value) const {
    172   ++stats::evaluateFixup;
    173 
    174   // FIXME: This code has some duplication with recordRelocation. We should
    175   // probably merge the two into a single callback that tries to evaluate a
    176   // fixup and records a relocation if one is needed.
    177   const MCExpr *Expr = Fixup.getValue();
    178   if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
    179     getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
    180     // Claim to have completely evaluated the fixup, to prevent any further
    181     // processing from being done.
    182     Value = 0;
    183     return true;
    184   }
    185 
    186   bool IsPCRel = Backend.getFixupKindInfo(
    187     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
    188 
    189   bool IsResolved;
    190   if (IsPCRel) {
    191     if (Target.getSymB()) {
    192       IsResolved = false;
    193     } else if (!Target.getSymA()) {
    194       IsResolved = false;
    195     } else {
    196       const MCSymbolRefExpr *A = Target.getSymA();
    197       const MCSymbol &SA = A->getSymbol();
    198       if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
    199         IsResolved = false;
    200       } else {
    201         IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
    202             *this, SA, *DF, false, true);
    203       }
    204     }
    205   } else {
    206     IsResolved = Target.isAbsolute();
    207   }
    208 
    209   Value = Target.getConstant();
    210 
    211   if (const MCSymbolRefExpr *A = Target.getSymA()) {
    212     const MCSymbol &Sym = A->getSymbol();
    213     if (Sym.isDefined())
    214       Value += Layout.getSymbolOffset(Sym);
    215   }
    216   if (const MCSymbolRefExpr *B = Target.getSymB()) {
    217     const MCSymbol &Sym = B->getSymbol();
    218     if (Sym.isDefined())
    219       Value -= Layout.getSymbolOffset(Sym);
    220   }
    221 
    222 
    223   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
    224                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
    225   assert((ShouldAlignPC ? IsPCRel : true) &&
    226     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
    227 
    228   if (IsPCRel) {
    229     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
    230 
    231     // A number of ARM fixups in Thumb mode require that the effective PC
    232     // address be determined as the 32-bit aligned version of the actual offset.
    233     if (ShouldAlignPC) Offset &= ~0x3;
    234     Value -= Offset;
    235   }
    236 
    237   // Let the backend adjust the fixup value if necessary, including whether
    238   // we need a relocation.
    239   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
    240                             IsResolved);
    241 
    242   return IsResolved;
    243 }
    244 
    245 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
    246                                           const MCFragment &F) const {
    247   switch (F.getKind()) {
    248   case MCFragment::FT_Data:
    249     return cast<MCDataFragment>(F).getContents().size();
    250   case MCFragment::FT_Relaxable:
    251     return cast<MCRelaxableFragment>(F).getContents().size();
    252   case MCFragment::FT_CompactEncodedInst:
    253     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
    254   case MCFragment::FT_Fill:
    255     return cast<MCFillFragment>(F).getSize();
    256 
    257   case MCFragment::FT_LEB:
    258     return cast<MCLEBFragment>(F).getContents().size();
    259 
    260   case MCFragment::FT_SafeSEH:
    261     return 4;
    262 
    263   case MCFragment::FT_Align: {
    264     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
    265     unsigned Offset = Layout.getFragmentOffset(&AF);
    266     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
    267     // If we are padding with nops, force the padding to be larger than the
    268     // minimum nop size.
    269     if (Size > 0 && AF.hasEmitNops()) {
    270       while (Size % getBackend().getMinimumNopSize())
    271         Size += AF.getAlignment();
    272     }
    273     if (Size > AF.getMaxBytesToEmit())
    274       return 0;
    275     return Size;
    276   }
    277 
    278   case MCFragment::FT_Org: {
    279     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
    280     MCValue Value;
    281     if (!OF.getOffset().evaluateAsValue(Value, Layout))
    282       report_fatal_error("expected assembly-time absolute expression");
    283 
    284     // FIXME: We need a way to communicate this error.
    285     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
    286     int64_t TargetLocation = Value.getConstant();
    287     if (const MCSymbolRefExpr *A = Value.getSymA()) {
    288       uint64_t Val;
    289       if (!Layout.getSymbolOffset(A->getSymbol(), Val))
    290         report_fatal_error("expected absolute expression");
    291       TargetLocation += Val;
    292     }
    293     int64_t Size = TargetLocation - FragmentOffset;
    294     if (Size < 0 || Size >= 0x40000000)
    295       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
    296                          "' (at offset '" + Twine(FragmentOffset) + "')");
    297     return Size;
    298   }
    299 
    300   case MCFragment::FT_Dwarf:
    301     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
    302   case MCFragment::FT_DwarfFrame:
    303     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
    304   case MCFragment::FT_CVInlineLines:
    305     return cast<MCCVInlineLineTableFragment>(F).getContents().size();
    306   case MCFragment::FT_CVDefRange:
    307     return cast<MCCVDefRangeFragment>(F).getContents().size();
    308   case MCFragment::FT_Dummy:
    309     llvm_unreachable("Should not have been added");
    310   }
    311 
    312   llvm_unreachable("invalid fragment kind");
    313 }
    314 
    315 void MCAsmLayout::layoutFragment(MCFragment *F) {
    316   MCFragment *Prev = F->getPrevNode();
    317 
    318   // We should never try to recompute something which is valid.
    319   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
    320   // We should never try to compute the fragment layout if its predecessor
    321   // isn't valid.
    322   assert((!Prev || isFragmentValid(Prev)) &&
    323          "Attempt to compute fragment before its predecessor!");
    324 
    325   ++stats::FragmentLayouts;
    326 
    327   // Compute fragment offset and size.
    328   if (Prev)
    329     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
    330   else
    331     F->Offset = 0;
    332   LastValidFragment[F->getParent()] = F;
    333 
    334   // If bundling is enabled and this fragment has instructions in it, it has to
    335   // obey the bundling restrictions. With padding, we'll have:
    336   //
    337   //
    338   //        BundlePadding
    339   //             |||
    340   // -------------------------------------
    341   //   Prev  |##########|       F        |
    342   // -------------------------------------
    343   //                    ^
    344   //                    |
    345   //                    F->Offset
    346   //
    347   // The fragment's offset will point to after the padding, and its computed
    348   // size won't include the padding.
    349   //
    350   // When the -mc-relax-all flag is used, we optimize bundling by writting the
    351   // padding directly into fragments when the instructions are emitted inside
    352   // the streamer. When the fragment is larger than the bundle size, we need to
    353   // ensure that it's bundle aligned. This means that if we end up with
    354   // multiple fragments, we must emit bundle padding between fragments.
    355   //
    356   // ".align N" is an example of a directive that introduces multiple
    357   // fragments. We could add a special case to handle ".align N" by emitting
    358   // within-fragment padding (which would produce less padding when N is less
    359   // than the bundle size), but for now we don't.
    360   //
    361   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
    362     assert(isa<MCEncodedFragment>(F) &&
    363            "Only MCEncodedFragment implementations have instructions");
    364     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
    365 
    366     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
    367       report_fatal_error("Fragment can't be larger than a bundle size");
    368 
    369     uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
    370                                                           F->Offset, FSize);
    371     if (RequiredBundlePadding > UINT8_MAX)
    372       report_fatal_error("Padding cannot exceed 255 bytes");
    373     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
    374     F->Offset += RequiredBundlePadding;
    375   }
    376 }
    377 
    378 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
    379   bool New = !Symbol.isRegistered();
    380   if (Created)
    381     *Created = New;
    382   if (New) {
    383     Symbol.setIsRegistered(true);
    384     Symbols.push_back(&Symbol);
    385   }
    386 }
    387 
    388 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
    389                                        MCObjectWriter *OW) const {
    390   // Should NOP padding be written out before this fragment?
    391   unsigned BundlePadding = F.getBundlePadding();
    392   if (BundlePadding > 0) {
    393     assert(isBundlingEnabled() &&
    394            "Writing bundle padding with disabled bundling");
    395     assert(F.hasInstructions() &&
    396            "Writing bundle padding for a fragment without instructions");
    397 
    398     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
    399     if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
    400       // If the padding itself crosses a bundle boundary, it must be emitted
    401       // in 2 pieces, since even nop instructions must not cross boundaries.
    402       //             v--------------v   <- BundleAlignSize
    403       //        v---------v             <- BundlePadding
    404       // ----------------------------
    405       // | Prev |####|####|    F    |
    406       // ----------------------------
    407       //        ^-------------------^   <- TotalLength
    408       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
    409       if (!getBackend().writeNopData(DistanceToBoundary, OW))
    410           report_fatal_error("unable to write NOP sequence of " +
    411                              Twine(DistanceToBoundary) + " bytes");
    412       BundlePadding -= DistanceToBoundary;
    413     }
    414     if (!getBackend().writeNopData(BundlePadding, OW))
    415       report_fatal_error("unable to write NOP sequence of " +
    416                          Twine(BundlePadding) + " bytes");
    417   }
    418 }
    419 
    420 /// \brief Write the fragment \p F to the output file.
    421 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
    422                           const MCFragment &F) {
    423   MCObjectWriter *OW = &Asm.getWriter();
    424 
    425   // FIXME: Embed in fragments instead?
    426   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
    427 
    428   Asm.writeFragmentPadding(F, FragmentSize, OW);
    429 
    430   // This variable (and its dummy usage) is to participate in the assert at
    431   // the end of the function.
    432   uint64_t Start = OW->getStream().tell();
    433   (void) Start;
    434 
    435   ++stats::EmittedFragments;
    436 
    437   switch (F.getKind()) {
    438   case MCFragment::FT_Align: {
    439     ++stats::EmittedAlignFragments;
    440     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
    441     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
    442 
    443     uint64_t Count = FragmentSize / AF.getValueSize();
    444 
    445     // FIXME: This error shouldn't actually occur (the front end should emit
    446     // multiple .align directives to enforce the semantics it wants), but is
    447     // severe enough that we want to report it. How to handle this?
    448     if (Count * AF.getValueSize() != FragmentSize)
    449       report_fatal_error("undefined .align directive, value size '" +
    450                         Twine(AF.getValueSize()) +
    451                         "' is not a divisor of padding size '" +
    452                         Twine(FragmentSize) + "'");
    453 
    454     // See if we are aligning with nops, and if so do that first to try to fill
    455     // the Count bytes.  Then if that did not fill any bytes or there are any
    456     // bytes left to fill use the Value and ValueSize to fill the rest.
    457     // If we are aligning with nops, ask that target to emit the right data.
    458     if (AF.hasEmitNops()) {
    459       if (!Asm.getBackend().writeNopData(Count, OW))
    460         report_fatal_error("unable to write nop sequence of " +
    461                           Twine(Count) + " bytes");
    462       break;
    463     }
    464 
    465     // Otherwise, write out in multiples of the value size.
    466     for (uint64_t i = 0; i != Count; ++i) {
    467       switch (AF.getValueSize()) {
    468       default: llvm_unreachable("Invalid size!");
    469       case 1: OW->write8 (uint8_t (AF.getValue())); break;
    470       case 2: OW->write16(uint16_t(AF.getValue())); break;
    471       case 4: OW->write32(uint32_t(AF.getValue())); break;
    472       case 8: OW->write64(uint64_t(AF.getValue())); break;
    473       }
    474     }
    475     break;
    476   }
    477 
    478   case MCFragment::FT_Data:
    479     ++stats::EmittedDataFragments;
    480     OW->writeBytes(cast<MCDataFragment>(F).getContents());
    481     break;
    482 
    483   case MCFragment::FT_Relaxable:
    484     ++stats::EmittedRelaxableFragments;
    485     OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
    486     break;
    487 
    488   case MCFragment::FT_CompactEncodedInst:
    489     ++stats::EmittedCompactEncodedInstFragments;
    490     OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
    491     break;
    492 
    493   case MCFragment::FT_Fill: {
    494     ++stats::EmittedFillFragments;
    495     const MCFillFragment &FF = cast<MCFillFragment>(F);
    496     uint8_t V = FF.getValue();
    497     const unsigned MaxChunkSize = 16;
    498     char Data[MaxChunkSize];
    499     memcpy(Data, &V, 1);
    500     for (unsigned I = 1; I < MaxChunkSize; ++I)
    501       Data[I] = Data[0];
    502 
    503     uint64_t Size = FF.getSize();
    504     for (unsigned ChunkSize = MaxChunkSize; ChunkSize; ChunkSize /= 2) {
    505       StringRef Ref(Data, ChunkSize);
    506       for (uint64_t I = 0, E = Size / ChunkSize; I != E; ++I)
    507         OW->writeBytes(Ref);
    508       Size = Size % ChunkSize;
    509     }
    510     break;
    511   }
    512 
    513   case MCFragment::FT_LEB: {
    514     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
    515     OW->writeBytes(LF.getContents());
    516     break;
    517   }
    518 
    519   case MCFragment::FT_SafeSEH: {
    520     const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
    521     OW->write32(SF.getSymbol()->getIndex());
    522     break;
    523   }
    524 
    525   case MCFragment::FT_Org: {
    526     ++stats::EmittedOrgFragments;
    527     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
    528 
    529     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
    530       OW->write8(uint8_t(OF.getValue()));
    531 
    532     break;
    533   }
    534 
    535   case MCFragment::FT_Dwarf: {
    536     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
    537     OW->writeBytes(OF.getContents());
    538     break;
    539   }
    540   case MCFragment::FT_DwarfFrame: {
    541     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
    542     OW->writeBytes(CF.getContents());
    543     break;
    544   }
    545   case MCFragment::FT_CVInlineLines: {
    546     const auto &OF = cast<MCCVInlineLineTableFragment>(F);
    547     OW->writeBytes(OF.getContents());
    548     break;
    549   }
    550   case MCFragment::FT_CVDefRange: {
    551     const auto &DRF = cast<MCCVDefRangeFragment>(F);
    552     OW->writeBytes(DRF.getContents());
    553     break;
    554   }
    555   case MCFragment::FT_Dummy:
    556     llvm_unreachable("Should not have been added");
    557   }
    558 
    559   assert(OW->getStream().tell() - Start == FragmentSize &&
    560          "The stream should advance by fragment size");
    561 }
    562 
    563 void MCAssembler::writeSectionData(const MCSection *Sec,
    564                                    const MCAsmLayout &Layout) const {
    565   // Ignore virtual sections.
    566   if (Sec->isVirtualSection()) {
    567     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
    568 
    569     // Check that contents are only things legal inside a virtual section.
    570     for (const MCFragment &F : *Sec) {
    571       switch (F.getKind()) {
    572       default: llvm_unreachable("Invalid fragment in virtual section!");
    573       case MCFragment::FT_Data: {
    574         // Check that we aren't trying to write a non-zero contents (or fixups)
    575         // into a virtual section. This is to support clients which use standard
    576         // directives to fill the contents of virtual sections.
    577         const MCDataFragment &DF = cast<MCDataFragment>(F);
    578         assert(DF.fixup_begin() == DF.fixup_end() &&
    579                "Cannot have fixups in virtual section!");
    580         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
    581           if (DF.getContents()[i]) {
    582             if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
    583               report_fatal_error("non-zero initializer found in section '" +
    584                   ELFSec->getSectionName() + "'");
    585             else
    586               report_fatal_error("non-zero initializer found in virtual section");
    587           }
    588         break;
    589       }
    590       case MCFragment::FT_Align:
    591         // Check that we aren't trying to write a non-zero value into a virtual
    592         // section.
    593         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
    594                 cast<MCAlignFragment>(F).getValue() == 0) &&
    595                "Invalid align in virtual section!");
    596         break;
    597       case MCFragment::FT_Fill:
    598         assert((cast<MCFillFragment>(F).getValue() == 0) &&
    599                "Invalid fill in virtual section!");
    600         break;
    601       }
    602     }
    603 
    604     return;
    605   }
    606 
    607   uint64_t Start = getWriter().getStream().tell();
    608   (void)Start;
    609 
    610   for (const MCFragment &F : *Sec)
    611     writeFragment(*this, Layout, F);
    612 
    613   assert(getWriter().getStream().tell() - Start ==
    614          Layout.getSectionAddressSize(Sec));
    615 }
    616 
    617 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
    618                                                    MCFragment &F,
    619                                                    const MCFixup &Fixup) {
    620   // Evaluate the fixup.
    621   MCValue Target;
    622   uint64_t FixedValue;
    623   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
    624                  MCFixupKindInfo::FKF_IsPCRel;
    625   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
    626     // The fixup was unresolved, we need a relocation. Inform the object
    627     // writer of the relocation, and give it an opportunity to adjust the
    628     // fixup value if need be.
    629     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
    630                                  FixedValue);
    631   }
    632   return std::make_pair(FixedValue, IsPCRel);
    633 }
    634 
    635 void MCAssembler::layout(MCAsmLayout &Layout) {
    636   DEBUG_WITH_TYPE("mc-dump", {
    637       llvm::errs() << "assembler backend - pre-layout\n--\n";
    638       dump(); });
    639 
    640   // Create dummy fragments and assign section ordinals.
    641   unsigned SectionIndex = 0;
    642   for (MCSection &Sec : *this) {
    643     // Create dummy fragments to eliminate any empty sections, this simplifies
    644     // layout.
    645     if (Sec.getFragmentList().empty())
    646       new MCDataFragment(&Sec);
    647 
    648     Sec.setOrdinal(SectionIndex++);
    649   }
    650 
    651   // Assign layout order indices to sections and fragments.
    652   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
    653     MCSection *Sec = Layout.getSectionOrder()[i];
    654     Sec->setLayoutOrder(i);
    655 
    656     unsigned FragmentIndex = 0;
    657     for (MCFragment &Frag : *Sec)
    658       Frag.setLayoutOrder(FragmentIndex++);
    659   }
    660 
    661   // Layout until everything fits.
    662   while (layoutOnce(Layout))
    663     continue;
    664 
    665   DEBUG_WITH_TYPE("mc-dump", {
    666       llvm::errs() << "assembler backend - post-relaxation\n--\n";
    667       dump(); });
    668 
    669   // Finalize the layout, including fragment lowering.
    670   finishLayout(Layout);
    671 
    672   DEBUG_WITH_TYPE("mc-dump", {
    673       llvm::errs() << "assembler backend - final-layout\n--\n";
    674       dump(); });
    675 
    676   // Allow the object writer a chance to perform post-layout binding (for
    677   // example, to set the index fields in the symbol data).
    678   getWriter().executePostLayoutBinding(*this, Layout);
    679 
    680   // Evaluate and apply the fixups, generating relocation entries as necessary.
    681   for (MCSection &Sec : *this) {
    682     for (MCFragment &Frag : Sec) {
    683       // Data and relaxable fragments both have fixups.  So only process
    684       // those here.
    685       // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
    686       // being templated makes this tricky.
    687       if (isa<MCEncodedFragment>(&Frag) &&
    688           isa<MCCompactEncodedInstFragment>(&Frag))
    689         continue;
    690       if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag))
    691         continue;
    692       ArrayRef<MCFixup> Fixups;
    693       MutableArrayRef<char> Contents;
    694       if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) {
    695         Fixups = FragWithFixups->getFixups();
    696         Contents = FragWithFixups->getContents();
    697       } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(&Frag)) {
    698         Fixups = FragWithFixups->getFixups();
    699         Contents = FragWithFixups->getContents();
    700       } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) {
    701         Fixups = FragWithFixups->getFixups();
    702         Contents = FragWithFixups->getContents();
    703       } else
    704         llvm_unreachable("Unknown fragment with fixups!");
    705       for (const MCFixup &Fixup : Fixups) {
    706         uint64_t FixedValue;
    707         bool IsPCRel;
    708         std::tie(FixedValue, IsPCRel) = handleFixup(Layout, Frag, Fixup);
    709         getBackend().applyFixup(Fixup, Contents.data(),
    710                                 Contents.size(), FixedValue, IsPCRel);
    711       }
    712     }
    713   }
    714 }
    715 
    716 void MCAssembler::Finish() {
    717   // Create the layout object.
    718   MCAsmLayout Layout(*this);
    719   layout(Layout);
    720 
    721   raw_ostream &OS = getWriter().getStream();
    722   uint64_t StartOffset = OS.tell();
    723 
    724   // Write the object file.
    725   getWriter().writeObject(*this, Layout);
    726 
    727   stats::ObjectBytes += OS.tell() - StartOffset;
    728 }
    729 
    730 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
    731                                        const MCRelaxableFragment *DF,
    732                                        const MCAsmLayout &Layout) const {
    733   MCValue Target;
    734   uint64_t Value;
    735   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
    736   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
    737                                                    Layout);
    738 }
    739 
    740 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
    741                                           const MCAsmLayout &Layout) const {
    742   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
    743   // are intentionally pushing out inst fragments, or because we relaxed a
    744   // previous instruction to one that doesn't need relaxation.
    745   if (!getBackend().mayNeedRelaxation(F->getInst()))
    746     return false;
    747 
    748   for (const MCFixup &Fixup : F->getFixups())
    749     if (fixupNeedsRelaxation(Fixup, F, Layout))
    750       return true;
    751 
    752   return false;
    753 }
    754 
    755 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
    756                                    MCRelaxableFragment &F) {
    757   if (!fragmentNeedsRelaxation(&F, Layout))
    758     return false;
    759 
    760   ++stats::RelaxedInstructions;
    761 
    762   // FIXME-PERF: We could immediately lower out instructions if we can tell
    763   // they are fully resolved, to avoid retesting on later passes.
    764 
    765   // Relax the fragment.
    766 
    767   MCInst Relaxed;
    768   getBackend().relaxInstruction(F.getInst(), F.getSubtargetInfo(), Relaxed);
    769 
    770   // Encode the new instruction.
    771   //
    772   // FIXME-PERF: If it matters, we could let the target do this. It can
    773   // probably do so more efficiently in many cases.
    774   SmallVector<MCFixup, 4> Fixups;
    775   SmallString<256> Code;
    776   raw_svector_ostream VecOS(Code);
    777   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
    778 
    779   // Update the fragment.
    780   F.setInst(Relaxed);
    781   F.getContents() = Code;
    782   F.getFixups() = Fixups;
    783 
    784   return true;
    785 }
    786 
    787 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
    788   uint64_t OldSize = LF.getContents().size();
    789   int64_t Value;
    790   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
    791   if (!Abs)
    792     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
    793   SmallString<8> &Data = LF.getContents();
    794   Data.clear();
    795   raw_svector_ostream OSE(Data);
    796   if (LF.isSigned())
    797     encodeSLEB128(Value, OSE);
    798   else
    799     encodeULEB128(Value, OSE);
    800   return OldSize != LF.getContents().size();
    801 }
    802 
    803 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
    804                                      MCDwarfLineAddrFragment &DF) {
    805   MCContext &Context = Layout.getAssembler().getContext();
    806   uint64_t OldSize = DF.getContents().size();
    807   int64_t AddrDelta;
    808   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
    809   assert(Abs && "We created a line delta with an invalid expression");
    810   (void) Abs;
    811   int64_t LineDelta;
    812   LineDelta = DF.getLineDelta();
    813   SmallString<8> &Data = DF.getContents();
    814   Data.clear();
    815   raw_svector_ostream OSE(Data);
    816   MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
    817                           AddrDelta, OSE);
    818   return OldSize != Data.size();
    819 }
    820 
    821 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
    822                                               MCDwarfCallFrameFragment &DF) {
    823   MCContext &Context = Layout.getAssembler().getContext();
    824   uint64_t OldSize = DF.getContents().size();
    825   int64_t AddrDelta;
    826   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
    827   assert(Abs && "We created call frame with an invalid expression");
    828   (void) Abs;
    829   SmallString<8> &Data = DF.getContents();
    830   Data.clear();
    831   raw_svector_ostream OSE(Data);
    832   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
    833   return OldSize != Data.size();
    834 }
    835 
    836 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
    837                                          MCCVInlineLineTableFragment &F) {
    838   unsigned OldSize = F.getContents().size();
    839   getContext().getCVContext().encodeInlineLineTable(Layout, F);
    840   return OldSize != F.getContents().size();
    841 }
    842 
    843 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
    844                                   MCCVDefRangeFragment &F) {
    845   unsigned OldSize = F.getContents().size();
    846   getContext().getCVContext().encodeDefRange(Layout, F);
    847   return OldSize != F.getContents().size();
    848 }
    849 
    850 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
    851   // Holds the first fragment which needed relaxing during this layout. It will
    852   // remain NULL if none were relaxed.
    853   // When a fragment is relaxed, all the fragments following it should get
    854   // invalidated because their offset is going to change.
    855   MCFragment *FirstRelaxedFragment = nullptr;
    856 
    857   // Attempt to relax all the fragments in the section.
    858   for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
    859     // Check if this is a fragment that needs relaxation.
    860     bool RelaxedFrag = false;
    861     switch(I->getKind()) {
    862     default:
    863       break;
    864     case MCFragment::FT_Relaxable:
    865       assert(!getRelaxAll() &&
    866              "Did not expect a MCRelaxableFragment in RelaxAll mode");
    867       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
    868       break;
    869     case MCFragment::FT_Dwarf:
    870       RelaxedFrag = relaxDwarfLineAddr(Layout,
    871                                        *cast<MCDwarfLineAddrFragment>(I));
    872       break;
    873     case MCFragment::FT_DwarfFrame:
    874       RelaxedFrag =
    875         relaxDwarfCallFrameFragment(Layout,
    876                                     *cast<MCDwarfCallFrameFragment>(I));
    877       break;
    878     case MCFragment::FT_LEB:
    879       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
    880       break;
    881     case MCFragment::FT_CVInlineLines:
    882       RelaxedFrag =
    883           relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
    884       break;
    885     case MCFragment::FT_CVDefRange:
    886       RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
    887       break;
    888     }
    889     if (RelaxedFrag && !FirstRelaxedFragment)
    890       FirstRelaxedFragment = &*I;
    891   }
    892   if (FirstRelaxedFragment) {
    893     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
    894     return true;
    895   }
    896   return false;
    897 }
    898 
    899 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
    900   ++stats::RelaxationSteps;
    901 
    902   bool WasRelaxed = false;
    903   for (iterator it = begin(), ie = end(); it != ie; ++it) {
    904     MCSection &Sec = *it;
    905     while (layoutSectionOnce(Layout, Sec))
    906       WasRelaxed = true;
    907   }
    908 
    909   return WasRelaxed;
    910 }
    911 
    912 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
    913   // The layout is done. Mark every fragment as valid.
    914   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
    915     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
    916   }
    917   getBackend().finishLayout(*this, Layout);
    918 }
    919