]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/MC/MCAssembler.cpp
Merge ^/head r311812 through r311939.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / MC / MCAssembler.cpp
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       getContext().reportError(OF.getLoc(),
283                                "expected assembly-time absolute expression");
284         return 0;
285     }
286
287     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
288     int64_t TargetLocation = Value.getConstant();
289     if (const MCSymbolRefExpr *A = Value.getSymA()) {
290       uint64_t Val;
291       if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
292         getContext().reportError(OF.getLoc(), "expected absolute expression");
293         return 0;
294       }
295       TargetLocation += Val;
296     }
297     int64_t Size = TargetLocation - FragmentOffset;
298     if (Size < 0 || Size >= 0x40000000) {
299       getContext().reportError(
300           OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
301                            "' (at offset '" + Twine(FragmentOffset) + "')");
302       return 0;
303     }
304     return Size;
305   }
306
307   case MCFragment::FT_Dwarf:
308     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
309   case MCFragment::FT_DwarfFrame:
310     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
311   case MCFragment::FT_CVInlineLines:
312     return cast<MCCVInlineLineTableFragment>(F).getContents().size();
313   case MCFragment::FT_CVDefRange:
314     return cast<MCCVDefRangeFragment>(F).getContents().size();
315   case MCFragment::FT_Dummy:
316     llvm_unreachable("Should not have been added");
317   }
318
319   llvm_unreachable("invalid fragment kind");
320 }
321
322 void MCAsmLayout::layoutFragment(MCFragment *F) {
323   MCFragment *Prev = F->getPrevNode();
324
325   // We should never try to recompute something which is valid.
326   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
327   // We should never try to compute the fragment layout if its predecessor
328   // isn't valid.
329   assert((!Prev || isFragmentValid(Prev)) &&
330          "Attempt to compute fragment before its predecessor!");
331
332   ++stats::FragmentLayouts;
333
334   // Compute fragment offset and size.
335   if (Prev)
336     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
337   else
338     F->Offset = 0;
339   LastValidFragment[F->getParent()] = F;
340
341   // If bundling is enabled and this fragment has instructions in it, it has to
342   // obey the bundling restrictions. With padding, we'll have:
343   //
344   //
345   //        BundlePadding
346   //             |||
347   // -------------------------------------
348   //   Prev  |##########|       F        |
349   // -------------------------------------
350   //                    ^
351   //                    |
352   //                    F->Offset
353   //
354   // The fragment's offset will point to after the padding, and its computed
355   // size won't include the padding.
356   //
357   // When the -mc-relax-all flag is used, we optimize bundling by writting the
358   // padding directly into fragments when the instructions are emitted inside
359   // the streamer. When the fragment is larger than the bundle size, we need to
360   // ensure that it's bundle aligned. This means that if we end up with
361   // multiple fragments, we must emit bundle padding between fragments.
362   //
363   // ".align N" is an example of a directive that introduces multiple
364   // fragments. We could add a special case to handle ".align N" by emitting
365   // within-fragment padding (which would produce less padding when N is less
366   // than the bundle size), but for now we don't.
367   //
368   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
369     assert(isa<MCEncodedFragment>(F) &&
370            "Only MCEncodedFragment implementations have instructions");
371     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
372
373     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
374       report_fatal_error("Fragment can't be larger than a bundle size");
375
376     uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
377                                                           F->Offset, FSize);
378     if (RequiredBundlePadding > UINT8_MAX)
379       report_fatal_error("Padding cannot exceed 255 bytes");
380     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
381     F->Offset += RequiredBundlePadding;
382   }
383 }
384
385 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
386   bool New = !Symbol.isRegistered();
387   if (Created)
388     *Created = New;
389   if (New) {
390     Symbol.setIsRegistered(true);
391     Symbols.push_back(&Symbol);
392   }
393 }
394
395 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
396                                        MCObjectWriter *OW) const {
397   // Should NOP padding be written out before this fragment?
398   unsigned BundlePadding = F.getBundlePadding();
399   if (BundlePadding > 0) {
400     assert(isBundlingEnabled() &&
401            "Writing bundle padding with disabled bundling");
402     assert(F.hasInstructions() &&
403            "Writing bundle padding for a fragment without instructions");
404
405     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
406     if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
407       // If the padding itself crosses a bundle boundary, it must be emitted
408       // in 2 pieces, since even nop instructions must not cross boundaries.
409       //             v--------------v   <- BundleAlignSize
410       //        v---------v             <- BundlePadding
411       // ----------------------------
412       // | Prev |####|####|    F    |
413       // ----------------------------
414       //        ^-------------------^   <- TotalLength
415       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
416       if (!getBackend().writeNopData(DistanceToBoundary, OW))
417           report_fatal_error("unable to write NOP sequence of " +
418                              Twine(DistanceToBoundary) + " bytes");
419       BundlePadding -= DistanceToBoundary;
420     }
421     if (!getBackend().writeNopData(BundlePadding, OW))
422       report_fatal_error("unable to write NOP sequence of " +
423                          Twine(BundlePadding) + " bytes");
424   }
425 }
426
427 /// \brief Write the fragment \p F to the output file.
428 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
429                           const MCFragment &F) {
430   MCObjectWriter *OW = &Asm.getWriter();
431
432   // FIXME: Embed in fragments instead?
433   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
434
435   Asm.writeFragmentPadding(F, FragmentSize, OW);
436
437   // This variable (and its dummy usage) is to participate in the assert at
438   // the end of the function.
439   uint64_t Start = OW->getStream().tell();
440   (void) Start;
441
442   ++stats::EmittedFragments;
443
444   switch (F.getKind()) {
445   case MCFragment::FT_Align: {
446     ++stats::EmittedAlignFragments;
447     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
448     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
449
450     uint64_t Count = FragmentSize / AF.getValueSize();
451
452     // FIXME: This error shouldn't actually occur (the front end should emit
453     // multiple .align directives to enforce the semantics it wants), but is
454     // severe enough that we want to report it. How to handle this?
455     if (Count * AF.getValueSize() != FragmentSize)
456       report_fatal_error("undefined .align directive, value size '" +
457                         Twine(AF.getValueSize()) +
458                         "' is not a divisor of padding size '" +
459                         Twine(FragmentSize) + "'");
460
461     // See if we are aligning with nops, and if so do that first to try to fill
462     // the Count bytes.  Then if that did not fill any bytes or there are any
463     // bytes left to fill use the Value and ValueSize to fill the rest.
464     // If we are aligning with nops, ask that target to emit the right data.
465     if (AF.hasEmitNops()) {
466       if (!Asm.getBackend().writeNopData(Count, OW))
467         report_fatal_error("unable to write nop sequence of " +
468                           Twine(Count) + " bytes");
469       break;
470     }
471
472     // Otherwise, write out in multiples of the value size.
473     for (uint64_t i = 0; i != Count; ++i) {
474       switch (AF.getValueSize()) {
475       default: llvm_unreachable("Invalid size!");
476       case 1: OW->write8 (uint8_t (AF.getValue())); break;
477       case 2: OW->write16(uint16_t(AF.getValue())); break;
478       case 4: OW->write32(uint32_t(AF.getValue())); break;
479       case 8: OW->write64(uint64_t(AF.getValue())); break;
480       }
481     }
482     break;
483   }
484
485   case MCFragment::FT_Data: 
486     ++stats::EmittedDataFragments;
487     OW->writeBytes(cast<MCDataFragment>(F).getContents());
488     break;
489
490   case MCFragment::FT_Relaxable:
491     ++stats::EmittedRelaxableFragments;
492     OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
493     break;
494
495   case MCFragment::FT_CompactEncodedInst:
496     ++stats::EmittedCompactEncodedInstFragments;
497     OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
498     break;
499
500   case MCFragment::FT_Fill: {
501     ++stats::EmittedFillFragments;
502     const MCFillFragment &FF = cast<MCFillFragment>(F);
503     uint8_t V = FF.getValue();
504     const unsigned MaxChunkSize = 16;
505     char Data[MaxChunkSize];
506     memcpy(Data, &V, 1);
507     for (unsigned I = 1; I < MaxChunkSize; ++I)
508       Data[I] = Data[0];
509
510     uint64_t Size = FF.getSize();
511     for (unsigned ChunkSize = MaxChunkSize; ChunkSize; ChunkSize /= 2) {
512       StringRef Ref(Data, ChunkSize);
513       for (uint64_t I = 0, E = Size / ChunkSize; I != E; ++I)
514         OW->writeBytes(Ref);
515       Size = Size % ChunkSize;
516     }
517     break;
518   }
519
520   case MCFragment::FT_LEB: {
521     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
522     OW->writeBytes(LF.getContents());
523     break;
524   }
525
526   case MCFragment::FT_SafeSEH: {
527     const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
528     OW->write32(SF.getSymbol()->getIndex());
529     break;
530   }
531
532   case MCFragment::FT_Org: {
533     ++stats::EmittedOrgFragments;
534     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
535
536     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
537       OW->write8(uint8_t(OF.getValue()));
538
539     break;
540   }
541
542   case MCFragment::FT_Dwarf: {
543     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
544     OW->writeBytes(OF.getContents());
545     break;
546   }
547   case MCFragment::FT_DwarfFrame: {
548     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
549     OW->writeBytes(CF.getContents());
550     break;
551   }
552   case MCFragment::FT_CVInlineLines: {
553     const auto &OF = cast<MCCVInlineLineTableFragment>(F);
554     OW->writeBytes(OF.getContents());
555     break;
556   }
557   case MCFragment::FT_CVDefRange: {
558     const auto &DRF = cast<MCCVDefRangeFragment>(F);
559     OW->writeBytes(DRF.getContents());
560     break;
561   }
562   case MCFragment::FT_Dummy:
563     llvm_unreachable("Should not have been added");
564   }
565
566   assert(OW->getStream().tell() - Start == FragmentSize &&
567          "The stream should advance by fragment size");
568 }
569
570 void MCAssembler::writeSectionData(const MCSection *Sec,
571                                    const MCAsmLayout &Layout) const {
572   // Ignore virtual sections.
573   if (Sec->isVirtualSection()) {
574     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
575
576     // Check that contents are only things legal inside a virtual section.
577     for (const MCFragment &F : *Sec) {
578       switch (F.getKind()) {
579       default: llvm_unreachable("Invalid fragment in virtual section!");
580       case MCFragment::FT_Data: {
581         // Check that we aren't trying to write a non-zero contents (or fixups)
582         // into a virtual section. This is to support clients which use standard
583         // directives to fill the contents of virtual sections.
584         const MCDataFragment &DF = cast<MCDataFragment>(F);
585         if (DF.fixup_begin() != DF.fixup_end())
586           report_fatal_error("cannot have fixups in virtual section!");
587         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
588           if (DF.getContents()[i]) {
589             if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
590               report_fatal_error("non-zero initializer found in section '" +
591                   ELFSec->getSectionName() + "'");
592             else
593               report_fatal_error("non-zero initializer found in virtual section");
594           }
595         break;
596       }
597       case MCFragment::FT_Align:
598         // Check that we aren't trying to write a non-zero value into a virtual
599         // section.
600         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
601                 cast<MCAlignFragment>(F).getValue() == 0) &&
602                "Invalid align in virtual section!");
603         break;
604       case MCFragment::FT_Fill:
605         assert((cast<MCFillFragment>(F).getValue() == 0) &&
606                "Invalid fill in virtual section!");
607         break;
608       }
609     }
610
611     return;
612   }
613
614   uint64_t Start = getWriter().getStream().tell();
615   (void)Start;
616
617   for (const MCFragment &F : *Sec)
618     writeFragment(*this, Layout, F);
619
620   assert(getWriter().getStream().tell() - Start ==
621          Layout.getSectionAddressSize(Sec));
622 }
623
624 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
625                                                    MCFragment &F,
626                                                    const MCFixup &Fixup) {
627   // Evaluate the fixup.
628   MCValue Target;
629   uint64_t FixedValue;
630   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
631                  MCFixupKindInfo::FKF_IsPCRel;
632   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
633     // The fixup was unresolved, we need a relocation. Inform the object
634     // writer of the relocation, and give it an opportunity to adjust the
635     // fixup value if need be.
636     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
637                                  FixedValue);
638   }
639   return std::make_pair(FixedValue, IsPCRel);
640 }
641
642 void MCAssembler::layout(MCAsmLayout &Layout) {
643   DEBUG_WITH_TYPE("mc-dump", {
644       llvm::errs() << "assembler backend - pre-layout\n--\n";
645       dump(); });
646
647   // Create dummy fragments and assign section ordinals.
648   unsigned SectionIndex = 0;
649   for (MCSection &Sec : *this) {
650     // Create dummy fragments to eliminate any empty sections, this simplifies
651     // layout.
652     if (Sec.getFragmentList().empty())
653       new MCDataFragment(&Sec);
654
655     Sec.setOrdinal(SectionIndex++);
656   }
657
658   // Assign layout order indices to sections and fragments.
659   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
660     MCSection *Sec = Layout.getSectionOrder()[i];
661     Sec->setLayoutOrder(i);
662
663     unsigned FragmentIndex = 0;
664     for (MCFragment &Frag : *Sec)
665       Frag.setLayoutOrder(FragmentIndex++);
666   }
667
668   // Layout until everything fits.
669   while (layoutOnce(Layout))
670     if (getContext().hadError())
671       return;
672
673   DEBUG_WITH_TYPE("mc-dump", {
674       llvm::errs() << "assembler backend - post-relaxation\n--\n";
675       dump(); });
676
677   // Finalize the layout, including fragment lowering.
678   finishLayout(Layout);
679
680   DEBUG_WITH_TYPE("mc-dump", {
681       llvm::errs() << "assembler backend - final-layout\n--\n";
682       dump(); });
683
684   // Allow the object writer a chance to perform post-layout binding (for
685   // example, to set the index fields in the symbol data).
686   getWriter().executePostLayoutBinding(*this, Layout);
687
688   // Evaluate and apply the fixups, generating relocation entries as necessary.
689   for (MCSection &Sec : *this) {
690     for (MCFragment &Frag : Sec) {
691       // Data and relaxable fragments both have fixups.  So only process
692       // those here.
693       // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
694       // being templated makes this tricky.
695       if (isa<MCEncodedFragment>(&Frag) &&
696           isa<MCCompactEncodedInstFragment>(&Frag))
697         continue;
698       if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag))
699         continue;
700       ArrayRef<MCFixup> Fixups;
701       MutableArrayRef<char> Contents;
702       if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) {
703         Fixups = FragWithFixups->getFixups();
704         Contents = FragWithFixups->getContents();
705       } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(&Frag)) {
706         Fixups = FragWithFixups->getFixups();
707         Contents = FragWithFixups->getContents();
708       } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) {
709         Fixups = FragWithFixups->getFixups();
710         Contents = FragWithFixups->getContents();
711       } else
712         llvm_unreachable("Unknown fragment with fixups!");
713       for (const MCFixup &Fixup : Fixups) {
714         uint64_t FixedValue;
715         bool IsPCRel;
716         std::tie(FixedValue, IsPCRel) = handleFixup(Layout, Frag, Fixup);
717         getBackend().applyFixup(Fixup, Contents.data(),
718                                 Contents.size(), FixedValue, IsPCRel);
719       }
720     }
721   }
722 }
723
724 void MCAssembler::Finish() {
725   // Create the layout object.
726   MCAsmLayout Layout(*this);
727   layout(Layout);
728
729   raw_ostream &OS = getWriter().getStream();
730   uint64_t StartOffset = OS.tell();
731
732   // Write the object file.
733   getWriter().writeObject(*this, Layout);
734
735   stats::ObjectBytes += OS.tell() - StartOffset;
736 }
737
738 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
739                                        const MCRelaxableFragment *DF,
740                                        const MCAsmLayout &Layout) const {
741   MCValue Target;
742   uint64_t Value;
743   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
744   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
745                                                    Layout);
746 }
747
748 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
749                                           const MCAsmLayout &Layout) const {
750   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
751   // are intentionally pushing out inst fragments, or because we relaxed a
752   // previous instruction to one that doesn't need relaxation.
753   if (!getBackend().mayNeedRelaxation(F->getInst()))
754     return false;
755
756   for (const MCFixup &Fixup : F->getFixups())
757     if (fixupNeedsRelaxation(Fixup, F, Layout))
758       return true;
759
760   return false;
761 }
762
763 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
764                                    MCRelaxableFragment &F) {
765   if (!fragmentNeedsRelaxation(&F, Layout))
766     return false;
767
768   ++stats::RelaxedInstructions;
769
770   // FIXME-PERF: We could immediately lower out instructions if we can tell
771   // they are fully resolved, to avoid retesting on later passes.
772
773   // Relax the fragment.
774
775   MCInst Relaxed;
776   getBackend().relaxInstruction(F.getInst(), F.getSubtargetInfo(), Relaxed);
777
778   // Encode the new instruction.
779   //
780   // FIXME-PERF: If it matters, we could let the target do this. It can
781   // probably do so more efficiently in many cases.
782   SmallVector<MCFixup, 4> Fixups;
783   SmallString<256> Code;
784   raw_svector_ostream VecOS(Code);
785   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
786
787   // Update the fragment.
788   F.setInst(Relaxed);
789   F.getContents() = Code;
790   F.getFixups() = Fixups;
791
792   return true;
793 }
794
795 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
796   uint64_t OldSize = LF.getContents().size();
797   int64_t Value;
798   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
799   if (!Abs)
800     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
801   SmallString<8> &Data = LF.getContents();
802   Data.clear();
803   raw_svector_ostream OSE(Data);
804   if (LF.isSigned())
805     encodeSLEB128(Value, OSE);
806   else
807     encodeULEB128(Value, OSE);
808   return OldSize != LF.getContents().size();
809 }
810
811 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
812                                      MCDwarfLineAddrFragment &DF) {
813   MCContext &Context = Layout.getAssembler().getContext();
814   uint64_t OldSize = DF.getContents().size();
815   int64_t AddrDelta;
816   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
817   assert(Abs && "We created a line delta with an invalid expression");
818   (void) Abs;
819   int64_t LineDelta;
820   LineDelta = DF.getLineDelta();
821   SmallString<8> &Data = DF.getContents();
822   Data.clear();
823   raw_svector_ostream OSE(Data);
824   MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
825                           AddrDelta, OSE);
826   return OldSize != Data.size();
827 }
828
829 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
830                                               MCDwarfCallFrameFragment &DF) {
831   MCContext &Context = Layout.getAssembler().getContext();
832   uint64_t OldSize = DF.getContents().size();
833   int64_t AddrDelta;
834   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
835   assert(Abs && "We created call frame with an invalid expression");
836   (void) Abs;
837   SmallString<8> &Data = DF.getContents();
838   Data.clear();
839   raw_svector_ostream OSE(Data);
840   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
841   return OldSize != Data.size();
842 }
843
844 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
845                                          MCCVInlineLineTableFragment &F) {
846   unsigned OldSize = F.getContents().size();
847   getContext().getCVContext().encodeInlineLineTable(Layout, F);
848   return OldSize != F.getContents().size();
849 }
850
851 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
852                                   MCCVDefRangeFragment &F) {
853   unsigned OldSize = F.getContents().size();
854   getContext().getCVContext().encodeDefRange(Layout, F);
855   return OldSize != F.getContents().size();
856 }
857
858 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
859   // Holds the first fragment which needed relaxing during this layout. It will
860   // remain NULL if none were relaxed.
861   // When a fragment is relaxed, all the fragments following it should get
862   // invalidated because their offset is going to change.
863   MCFragment *FirstRelaxedFragment = nullptr;
864
865   // Attempt to relax all the fragments in the section.
866   for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
867     // Check if this is a fragment that needs relaxation.
868     bool RelaxedFrag = false;
869     switch(I->getKind()) {
870     default:
871       break;
872     case MCFragment::FT_Relaxable:
873       assert(!getRelaxAll() &&
874              "Did not expect a MCRelaxableFragment in RelaxAll mode");
875       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
876       break;
877     case MCFragment::FT_Dwarf:
878       RelaxedFrag = relaxDwarfLineAddr(Layout,
879                                        *cast<MCDwarfLineAddrFragment>(I));
880       break;
881     case MCFragment::FT_DwarfFrame:
882       RelaxedFrag =
883         relaxDwarfCallFrameFragment(Layout,
884                                     *cast<MCDwarfCallFrameFragment>(I));
885       break;
886     case MCFragment::FT_LEB:
887       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
888       break;
889     case MCFragment::FT_CVInlineLines:
890       RelaxedFrag =
891           relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
892       break;
893     case MCFragment::FT_CVDefRange:
894       RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
895       break;
896     }
897     if (RelaxedFrag && !FirstRelaxedFragment)
898       FirstRelaxedFragment = &*I;
899   }
900   if (FirstRelaxedFragment) {
901     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
902     return true;
903   }
904   return false;
905 }
906
907 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
908   ++stats::RelaxationSteps;
909
910   bool WasRelaxed = false;
911   for (iterator it = begin(), ie = end(); it != ie; ++it) {
912     MCSection &Sec = *it;
913     while (layoutSectionOnce(Layout, Sec))
914       WasRelaxed = true;
915   }
916
917   return WasRelaxed;
918 }
919
920 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
921   // The layout is done. Mark every fragment as valid.
922   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
923     MCSection &Section = *Layout.getSectionOrder()[i];
924     Layout.getFragmentOffset(&*Section.rbegin());
925     computeFragmentSize(Layout, *Section.rbegin());
926   }
927   getBackend().finishLayout(*this, Layout);
928 }