1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
36 #define DEBUG_TYPE "assembler"
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");
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.
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"
76 MCAssembler::~MCAssembler() {
79 void MCAssembler::reset() {
82 IndirectSymbols.clear();
84 LinkerOptions.clear();
89 SubsectionsViaSymbols = false;
90 IncrementalLinkerCompatible = false;
93 VersionMinInfo.Major = 0;
95 // reset objects owned by us
99 getLOHContainer().reset();
102 bool MCAssembler::registerSection(MCSection &Section) {
103 if (Section.isRegistered())
105 Sections.push_back(&Section);
106 Section.setIsRegistered(true);
110 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
111 if (ThumbFuncs.count(Symbol))
114 if (!Symbol->isVariable())
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);
124 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
127 const MCSymbol &Sym = Ref->getSymbol();
128 if (!isThumbFunc(&Sym))
131 ThumbFuncs.insert(Symbol); // Cache it.
135 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
136 // Non-temporary labels should always be visible to the linker.
137 if (!Symbol.isTemporary())
140 // Absolute temporary labels are never visible.
141 if (!Symbol.isInSection())
144 if (Symbol.isUsedInReloc())
150 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
151 // Linker visible symbols define atoms.
152 if (isSymbolLinkerVisible(S))
155 // Absolute and undefined symbols have no defining atom.
156 if (!S.isInSection())
159 // Non-linker visible symbols in sections which can't be atomized have no
161 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
162 *S.getFragment()->getParent()))
165 // Otherwise, return the atom for the containing fragment.
166 return S.getFragment()->getAtom();
169 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
170 const MCFixup &Fixup, const MCFragment *DF,
171 MCValue &Target, uint64_t &Value) const {
172 ++stats::evaluateFixup;
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.
186 bool IsPCRel = Backend.getFixupKindInfo(
187 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
191 if (Target.getSymB()) {
193 } else if (!Target.getSymA()) {
196 const MCSymbolRefExpr *A = Target.getSymA();
197 const MCSymbol &SA = A->getSymbol();
198 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
201 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
202 *this, SA, *DF, false, true);
206 IsResolved = Target.isAbsolute();
209 Value = Target.getConstant();
211 if (const MCSymbolRefExpr *A = Target.getSymA()) {
212 const MCSymbol &Sym = A->getSymbol();
214 Value += Layout.getSymbolOffset(Sym);
216 if (const MCSymbolRefExpr *B = Target.getSymB()) {
217 const MCSymbol &Sym = B->getSymbol();
219 Value -= Layout.getSymbolOffset(Sym);
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!");
229 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
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;
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,
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();
257 case MCFragment::FT_LEB:
258 return cast<MCLEBFragment>(F).getContents().size();
260 case MCFragment::FT_SafeSEH:
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
269 if (Size > 0 && AF.hasEmitNops()) {
270 while (Size % getBackend().getMinimumNopSize())
271 Size += AF.getAlignment();
273 if (Size > AF.getMaxBytesToEmit())
278 case MCFragment::FT_Org: {
279 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
281 if (!OF.getOffset().evaluateAsValue(Value, Layout))
282 report_fatal_error("expected assembly-time absolute expression");
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()) {
289 if (!Layout.getSymbolOffset(A->getSymbol(), Val))
290 report_fatal_error("expected absolute expression");
291 TargetLocation += Val;
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) + "')");
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");
312 llvm_unreachable("invalid fragment kind");
315 void MCAsmLayout::layoutFragment(MCFragment *F) {
316 MCFragment *Prev = F->getPrevNode();
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
322 assert((!Prev || isFragmentValid(Prev)) &&
323 "Attempt to compute fragment before its predecessor!");
325 ++stats::FragmentLayouts;
327 // Compute fragment offset and size.
329 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
332 LastValidFragment[F->getParent()] = F;
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:
340 // -------------------------------------
341 // Prev |##########| F |
342 // -------------------------------------
347 // The fragment's offset will point to after the padding, and its computed
348 // size won't include the padding.
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.
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.
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);
366 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
367 report_fatal_error("Fragment can't be larger than a bundle size");
369 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
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;
378 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
379 bool New = !Symbol.isRegistered();
383 Symbol.setIsRegistered(true);
384 Symbols.push_back(&Symbol);
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");
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;
414 if (!getBackend().writeNopData(BundlePadding, OW))
415 report_fatal_error("unable to write NOP sequence of " +
416 Twine(BundlePadding) + " bytes");
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();
425 // FIXME: Embed in fragments instead?
426 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
428 Asm.writeFragmentPadding(F, FragmentSize, OW);
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();
435 ++stats::EmittedFragments;
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!");
443 uint64_t Count = FragmentSize / AF.getValueSize();
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) + "'");
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");
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;
478 case MCFragment::FT_Data:
479 ++stats::EmittedDataFragments;
480 OW->writeBytes(cast<MCDataFragment>(F).getContents());
483 case MCFragment::FT_Relaxable:
484 ++stats::EmittedRelaxableFragments;
485 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
488 case MCFragment::FT_CompactEncodedInst:
489 ++stats::EmittedCompactEncodedInstFragments;
490 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
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];
500 for (unsigned I = 1; I < MaxChunkSize; ++I)
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)
508 Size = Size % ChunkSize;
513 case MCFragment::FT_LEB: {
514 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
515 OW->writeBytes(LF.getContents());
519 case MCFragment::FT_SafeSEH: {
520 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
521 OW->write32(SF.getSymbol()->getIndex());
525 case MCFragment::FT_Org: {
526 ++stats::EmittedOrgFragments;
527 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
529 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
530 OW->write8(uint8_t(OF.getValue()));
535 case MCFragment::FT_Dwarf: {
536 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
537 OW->writeBytes(OF.getContents());
540 case MCFragment::FT_DwarfFrame: {
541 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
542 OW->writeBytes(CF.getContents());
545 case MCFragment::FT_CVInlineLines: {
546 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
547 OW->writeBytes(OF.getContents());
550 case MCFragment::FT_CVDefRange: {
551 const auto &DRF = cast<MCCVDefRangeFragment>(F);
552 OW->writeBytes(DRF.getContents());
555 case MCFragment::FT_Dummy:
556 llvm_unreachable("Should not have been added");
559 assert(OW->getStream().tell() - Start == FragmentSize &&
560 "The stream should advance by fragment size");
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!");
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() + "'");
586 report_fatal_error("non-zero initializer found in virtual section");
590 case MCFragment::FT_Align:
591 // Check that we aren't trying to write a non-zero value into a virtual
593 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
594 cast<MCAlignFragment>(F).getValue() == 0) &&
595 "Invalid align in virtual section!");
597 case MCFragment::FT_Fill:
598 assert((cast<MCFillFragment>(F).getValue() == 0) &&
599 "Invalid fill in virtual section!");
607 uint64_t Start = getWriter().getStream().tell();
610 for (const MCFragment &F : *Sec)
611 writeFragment(*this, Layout, F);
613 assert(getWriter().getStream().tell() - Start ==
614 Layout.getSectionAddressSize(Sec));
617 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
619 const MCFixup &Fixup) {
620 // Evaluate the fixup.
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,
632 return std::make_pair(FixedValue, IsPCRel);
635 void MCAssembler::layout(MCAsmLayout &Layout) {
636 DEBUG_WITH_TYPE("mc-dump", {
637 llvm::errs() << "assembler backend - pre-layout\n--\n";
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
645 if (Sec.getFragmentList().empty())
646 new MCDataFragment(&Sec);
648 Sec.setOrdinal(SectionIndex++);
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);
656 unsigned FragmentIndex = 0;
657 for (MCFragment &Frag : *Sec)
658 Frag.setLayoutOrder(FragmentIndex++);
661 // Layout until everything fits.
662 while (layoutOnce(Layout))
665 DEBUG_WITH_TYPE("mc-dump", {
666 llvm::errs() << "assembler backend - post-relaxation\n--\n";
669 // Finalize the layout, including fragment lowering.
670 finishLayout(Layout);
672 DEBUG_WITH_TYPE("mc-dump", {
673 llvm::errs() << "assembler backend - final-layout\n--\n";
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);
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
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))
690 if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag))
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();
704 llvm_unreachable("Unknown fragment with fixups!");
705 for (const MCFixup &Fixup : Fixups) {
708 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, Frag, Fixup);
709 getBackend().applyFixup(Fixup, Contents.data(),
710 Contents.size(), FixedValue, IsPCRel);
716 void MCAssembler::Finish() {
717 // Create the layout object.
718 MCAsmLayout Layout(*this);
721 raw_ostream &OS = getWriter().getStream();
722 uint64_t StartOffset = OS.tell();
724 // Write the object file.
725 getWriter().writeObject(*this, Layout);
727 stats::ObjectBytes += OS.tell() - StartOffset;
730 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
731 const MCRelaxableFragment *DF,
732 const MCAsmLayout &Layout) const {
735 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
736 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
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()))
748 for (const MCFixup &Fixup : F->getFixups())
749 if (fixupNeedsRelaxation(Fixup, F, Layout))
755 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
756 MCRelaxableFragment &F) {
757 if (!fragmentNeedsRelaxation(&F, Layout))
760 ++stats::RelaxedInstructions;
762 // FIXME-PERF: We could immediately lower out instructions if we can tell
763 // they are fully resolved, to avoid retesting on later passes.
765 // Relax the fragment.
768 getBackend().relaxInstruction(F.getInst(), F.getSubtargetInfo(), Relaxed);
770 // Encode the new instruction.
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());
779 // Update the fragment.
781 F.getContents() = Code;
782 F.getFixups() = Fixups;
787 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
788 uint64_t OldSize = LF.getContents().size();
790 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
792 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
793 SmallString<8> &Data = LF.getContents();
795 raw_svector_ostream OSE(Data);
797 encodeSLEB128(Value, OSE);
799 encodeULEB128(Value, OSE);
800 return OldSize != LF.getContents().size();
803 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
804 MCDwarfLineAddrFragment &DF) {
805 MCContext &Context = Layout.getAssembler().getContext();
806 uint64_t OldSize = DF.getContents().size();
808 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
809 assert(Abs && "We created a line delta with an invalid expression");
812 LineDelta = DF.getLineDelta();
813 SmallString<8> &Data = DF.getContents();
815 raw_svector_ostream OSE(Data);
816 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
818 return OldSize != Data.size();
821 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
822 MCDwarfCallFrameFragment &DF) {
823 MCContext &Context = Layout.getAssembler().getContext();
824 uint64_t OldSize = DF.getContents().size();
826 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
827 assert(Abs && "We created call frame with an invalid expression");
829 SmallString<8> &Data = DF.getContents();
831 raw_svector_ostream OSE(Data);
832 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
833 return OldSize != Data.size();
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();
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();
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;
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()) {
864 case MCFragment::FT_Relaxable:
865 assert(!getRelaxAll() &&
866 "Did not expect a MCRelaxableFragment in RelaxAll mode");
867 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
869 case MCFragment::FT_Dwarf:
870 RelaxedFrag = relaxDwarfLineAddr(Layout,
871 *cast<MCDwarfLineAddrFragment>(I));
873 case MCFragment::FT_DwarfFrame:
875 relaxDwarfCallFrameFragment(Layout,
876 *cast<MCDwarfCallFrameFragment>(I));
878 case MCFragment::FT_LEB:
879 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
881 case MCFragment::FT_CVInlineLines:
883 relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
885 case MCFragment::FT_CVDefRange:
886 RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
889 if (RelaxedFrag && !FirstRelaxedFragment)
890 FirstRelaxedFragment = &*I;
892 if (FirstRelaxedFragment) {
893 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
899 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
900 ++stats::RelaxationSteps;
902 bool WasRelaxed = false;
903 for (iterator it = begin(), ie = end(); it != ie; ++it) {
904 MCSection &Sec = *it;
905 while (layoutSectionOnce(Layout, Sec))
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());
917 getBackend().finishLayout(*this, Layout);