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/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
35 #define DEBUG_TYPE "assembler"
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41 "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43 "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45 "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47 "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49 "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51 "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68 : Assembler(Asm), LastValidFragment()
70 // Compute the section layout order. Virtual sections must go last.
71 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72 if (!it->isVirtualSection())
73 SectionOrder.push_back(&*it);
74 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75 if (it->isVirtualSection())
76 SectionOrder.push_back(&*it);
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80 const MCSection *Sec = F->getParent();
81 const MCFragment *LastValid = LastValidFragment.lookup(Sec);
84 assert(LastValid->getParent() == Sec);
85 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
89 // If this fragment wasn't already valid, we don't need to do anything.
90 if (!isFragmentValid(F))
93 // Otherwise, reset the last valid fragment to the previous fragment
94 // (if this is the first fragment, it will be NULL).
95 LastValidFragment[F->getParent()] = F->getPrevNode();
98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99 MCSection *Sec = F->getParent();
100 MCFragment *Cur = LastValidFragment[Sec];
104 Cur = Cur->getNextNode();
106 // Advance the layout position until the fragment is valid.
107 while (!isFragmentValid(F)) {
108 assert(Cur && "Layout bookkeeping error");
109 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
110 Cur = Cur->getNextNode();
114 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
116 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
120 // Simple getSymbolOffset helper for the non-varibale case.
121 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
122 bool ReportError, uint64_t &Val) {
123 const MCSymbolData &SD = S.getData();
124 if (!SD.getFragment()) {
126 report_fatal_error("unable to evaluate offset to undefined symbol '" +
130 Val = Layout.getFragmentOffset(SD.getFragment()) + SD.getOffset();
134 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
135 bool ReportError, uint64_t &Val) {
137 return getLabelOffset(Layout, S, ReportError, Val);
139 // If SD is a variable, evaluate it.
141 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout, nullptr))
142 report_fatal_error("unable to evaluate offset for variable '" +
145 uint64_t Offset = Target.getConstant();
147 const MCSymbolRefExpr *A = Target.getSymA();
150 if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
155 const MCSymbolRefExpr *B = Target.getSymB();
158 if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
167 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
168 return getSymbolOffsetImpl(*this, S, false, Val);
171 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
173 getSymbolOffsetImpl(*this, S, true, Val);
177 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
178 if (!Symbol.isVariable())
181 const MCExpr *Expr = Symbol.getVariableValue();
183 if (!Expr->evaluateAsValue(Value, *this))
184 llvm_unreachable("Invalid Expression");
186 const MCSymbolRefExpr *RefB = Value.getSymB();
188 Assembler.getContext().reportFatalError(
189 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
190 "' could not be evaluated in a subtraction expression");
192 const MCSymbolRefExpr *A = Value.getSymA();
196 const MCSymbol &ASym = A->getSymbol();
197 const MCAssembler &Asm = getAssembler();
198 const MCSymbolData &ASD = Asm.getSymbolData(ASym);
199 if (ASD.isCommon()) {
200 // FIXME: we should probably add a SMLoc to MCExpr.
201 Asm.getContext().reportFatalError(SMLoc(),
202 "Common symbol " + ASym.getName() +
203 " cannot be used in assignment expr");
209 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
210 // The size is the last fragment's end offset.
211 const MCFragment &F = Sec->getFragmentList().back();
212 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
215 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
216 // Virtual sections have no file size.
217 if (Sec->isVirtualSection())
220 // Otherwise, the file size is the same as the address space size.
221 return getSectionAddressSize(Sec);
224 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
226 uint64_t FOffset, uint64_t FSize) {
227 uint64_t BundleSize = Assembler.getBundleAlignSize();
228 assert(BundleSize > 0 &&
229 "computeBundlePadding should only be called if bundling is enabled");
230 uint64_t BundleMask = BundleSize - 1;
231 uint64_t OffsetInBundle = FOffset & BundleMask;
232 uint64_t EndOfFragment = OffsetInBundle + FSize;
234 // There are two kinds of bundling restrictions:
236 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
237 // *end* on a bundle boundary.
238 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
239 // would, add padding until the end of the bundle so that the fragment
240 // will start in a new one.
241 if (F->alignToBundleEnd()) {
242 // Three possibilities here:
244 // A) The fragment just happens to end at a bundle boundary, so we're good.
245 // B) The fragment ends before the current bundle boundary: pad it just
246 // enough to reach the boundary.
247 // C) The fragment ends after the current bundle boundary: pad it until it
248 // reaches the end of the next bundle boundary.
250 // Note: this code could be made shorter with some modulo trickery, but it's
251 // intentionally kept in its more explicit form for simplicity.
252 if (EndOfFragment == BundleSize)
254 else if (EndOfFragment < BundleSize)
255 return BundleSize - EndOfFragment;
256 else { // EndOfFragment > BundleSize
257 return 2 * BundleSize - EndOfFragment;
259 } else if (EndOfFragment > BundleSize)
260 return BundleSize - OffsetInBundle;
267 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
270 MCFragment::~MCFragment() {
273 MCFragment::MCFragment(FragmentType Kind, MCSection *Parent)
274 : Kind(Kind), Parent(Parent), Atom(nullptr), Offset(~UINT64_C(0)) {
276 Parent->getFragmentList().push_back(this);
281 MCEncodedFragment::~MCEncodedFragment() {
286 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
291 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
292 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
294 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
295 OS(OS_), BundleAlignSize(0), RelaxAll(false),
296 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
297 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
300 MCAssembler::~MCAssembler() {
303 void MCAssembler::reset() {
306 IndirectSymbols.clear();
308 LinkerOptions.clear();
313 SubsectionsViaSymbols = false;
315 LOHContainer.reset();
316 VersionMinInfo.Major = 0;
318 // reset objects owned by us
319 getBackend().reset();
320 getEmitter().reset();
322 getLOHContainer().reset();
325 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
326 if (ThumbFuncs.count(Symbol))
329 if (!Symbol->isVariable())
332 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
333 // is not clear if that is a bug or a feature.
334 const MCExpr *Expr = Symbol->getVariableValue();
335 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
339 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
342 const MCSymbol &Sym = Ref->getSymbol();
343 if (!isThumbFunc(&Sym))
346 ThumbFuncs.insert(Symbol); // Cache it.
350 void MCAssembler::addLocalUsedInReloc(const MCSymbol &Sym) {
351 assert(Sym.isTemporary());
352 LocalsUsedInReloc.insert(&Sym);
355 bool MCAssembler::isLocalUsedInReloc(const MCSymbol &Sym) const {
356 assert(Sym.isTemporary());
357 return LocalsUsedInReloc.count(&Sym);
360 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
361 // Non-temporary labels should always be visible to the linker.
362 if (!Symbol.isTemporary())
365 // Absolute temporary labels are never visible.
366 if (!Symbol.isInSection())
369 if (isLocalUsedInReloc(Symbol))
375 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
376 // Linker visible symbols define atoms.
377 if (isSymbolLinkerVisible(S))
380 // Absolute and undefined symbols have no defining atom.
381 if (!S.getData().getFragment())
384 // Non-linker visible symbols in sections which can't be atomized have no
386 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
387 *S.getData().getFragment()->getParent()))
390 // Otherwise, return the atom for the containing fragment.
391 return S.getData().getFragment()->getAtom();
394 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
395 const MCFixup &Fixup, const MCFragment *DF,
396 MCValue &Target, uint64_t &Value) const {
397 ++stats::evaluateFixup;
399 // FIXME: This code has some duplication with RecordRelocation. We should
400 // probably merge the two into a single callback that tries to evaluate a
401 // fixup and records a relocation if one is needed.
402 const MCExpr *Expr = Fixup.getValue();
403 if (!Expr->EvaluateAsRelocatable(Target, &Layout, &Fixup))
404 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
406 bool IsPCRel = Backend.getFixupKindInfo(
407 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
411 if (Target.getSymB()) {
413 } else if (!Target.getSymA()) {
416 const MCSymbolRefExpr *A = Target.getSymA();
417 const MCSymbol &SA = A->getSymbol();
418 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
421 IsResolved = getWriter().IsSymbolRefDifferenceFullyResolvedImpl(
422 *this, SA, *DF, false, true);
426 IsResolved = Target.isAbsolute();
429 Value = Target.getConstant();
431 if (const MCSymbolRefExpr *A = Target.getSymA()) {
432 const MCSymbol &Sym = A->getSymbol();
434 Value += Layout.getSymbolOffset(Sym);
436 if (const MCSymbolRefExpr *B = Target.getSymB()) {
437 const MCSymbol &Sym = B->getSymbol();
439 Value -= Layout.getSymbolOffset(Sym);
443 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
444 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
445 assert((ShouldAlignPC ? IsPCRel : true) &&
446 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
449 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
451 // A number of ARM fixups in Thumb mode require that the effective PC
452 // address be determined as the 32-bit aligned version of the actual offset.
453 if (ShouldAlignPC) Offset &= ~0x3;
457 // Let the backend adjust the fixup value if necessary, including whether
458 // we need a relocation.
459 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
465 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
466 const MCFragment &F) const {
467 switch (F.getKind()) {
468 case MCFragment::FT_Data:
469 case MCFragment::FT_Relaxable:
470 case MCFragment::FT_CompactEncodedInst:
471 return cast<MCEncodedFragment>(F).getContents().size();
472 case MCFragment::FT_Fill:
473 return cast<MCFillFragment>(F).getSize();
475 case MCFragment::FT_LEB:
476 return cast<MCLEBFragment>(F).getContents().size();
478 case MCFragment::FT_Align: {
479 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
480 unsigned Offset = Layout.getFragmentOffset(&AF);
481 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
482 // If we are padding with nops, force the padding to be larger than the
484 if (Size > 0 && AF.hasEmitNops()) {
485 while (Size % getBackend().getMinimumNopSize())
486 Size += AF.getAlignment();
488 if (Size > AF.getMaxBytesToEmit())
493 case MCFragment::FT_Org: {
494 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
495 int64_t TargetLocation;
496 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
497 report_fatal_error("expected assembly-time absolute expression");
499 // FIXME: We need a way to communicate this error.
500 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
501 int64_t Size = TargetLocation - FragmentOffset;
502 if (Size < 0 || Size >= 0x40000000)
503 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
504 "' (at offset '" + Twine(FragmentOffset) + "')");
508 case MCFragment::FT_Dwarf:
509 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
510 case MCFragment::FT_DwarfFrame:
511 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
514 llvm_unreachable("invalid fragment kind");
517 void MCAsmLayout::layoutFragment(MCFragment *F) {
518 MCFragment *Prev = F->getPrevNode();
520 // We should never try to recompute something which is valid.
521 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
522 // We should never try to compute the fragment layout if its predecessor
524 assert((!Prev || isFragmentValid(Prev)) &&
525 "Attempt to compute fragment before its predecessor!");
527 ++stats::FragmentLayouts;
529 // Compute fragment offset and size.
531 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
534 LastValidFragment[F->getParent()] = F;
536 // If bundling is enabled and this fragment has instructions in it, it has to
537 // obey the bundling restrictions. With padding, we'll have:
542 // -------------------------------------
543 // Prev |##########| F |
544 // -------------------------------------
549 // The fragment's offset will point to after the padding, and its computed
550 // size won't include the padding.
552 // When the -mc-relax-all flag is used, we optimize bundling by writting the
553 // bundle padding directly into fragments when the instructions are emitted
554 // inside the streamer.
556 if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
557 F->hasInstructions()) {
558 assert(isa<MCEncodedFragment>(F) &&
559 "Only MCEncodedFragment implementations have instructions");
560 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
562 if (FSize > Assembler.getBundleAlignSize())
563 report_fatal_error("Fragment can't be larger than a bundle size");
565 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
567 if (RequiredBundlePadding > UINT8_MAX)
568 report_fatal_error("Padding cannot exceed 255 bytes");
569 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
570 F->Offset += RequiredBundlePadding;
574 /// \brief Write the contents of a fragment to the given object writer. Expects
575 /// a MCEncodedFragment.
576 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
577 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
578 OW->WriteBytes(EF.getContents());
581 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
582 MCObjectWriter *OW) const {
583 // Should NOP padding be written out before this fragment?
584 unsigned BundlePadding = F.getBundlePadding();
585 if (BundlePadding > 0) {
586 assert(isBundlingEnabled() &&
587 "Writing bundle padding with disabled bundling");
588 assert(F.hasInstructions() &&
589 "Writing bundle padding for a fragment without instructions");
591 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
592 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
593 // If the padding itself crosses a bundle boundary, it must be emitted
594 // in 2 pieces, since even nop instructions must not cross boundaries.
595 // v--------------v <- BundleAlignSize
596 // v---------v <- BundlePadding
597 // ----------------------------
598 // | Prev |####|####| F |
599 // ----------------------------
600 // ^-------------------^ <- TotalLength
601 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
602 if (!getBackend().writeNopData(DistanceToBoundary, OW))
603 report_fatal_error("unable to write NOP sequence of " +
604 Twine(DistanceToBoundary) + " bytes");
605 BundlePadding -= DistanceToBoundary;
607 if (!getBackend().writeNopData(BundlePadding, OW))
608 report_fatal_error("unable to write NOP sequence of " +
609 Twine(BundlePadding) + " bytes");
613 /// \brief Write the fragment \p F to the output file.
614 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
615 const MCFragment &F) {
616 MCObjectWriter *OW = &Asm.getWriter();
618 // FIXME: Embed in fragments instead?
619 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
621 Asm.writeFragmentPadding(F, FragmentSize, OW);
623 // This variable (and its dummy usage) is to participate in the assert at
624 // the end of the function.
625 uint64_t Start = OW->getStream().tell();
628 ++stats::EmittedFragments;
630 switch (F.getKind()) {
631 case MCFragment::FT_Align: {
632 ++stats::EmittedAlignFragments;
633 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
634 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
636 uint64_t Count = FragmentSize / AF.getValueSize();
638 // FIXME: This error shouldn't actually occur (the front end should emit
639 // multiple .align directives to enforce the semantics it wants), but is
640 // severe enough that we want to report it. How to handle this?
641 if (Count * AF.getValueSize() != FragmentSize)
642 report_fatal_error("undefined .align directive, value size '" +
643 Twine(AF.getValueSize()) +
644 "' is not a divisor of padding size '" +
645 Twine(FragmentSize) + "'");
647 // See if we are aligning with nops, and if so do that first to try to fill
648 // the Count bytes. Then if that did not fill any bytes or there are any
649 // bytes left to fill use the Value and ValueSize to fill the rest.
650 // If we are aligning with nops, ask that target to emit the right data.
651 if (AF.hasEmitNops()) {
652 if (!Asm.getBackend().writeNopData(Count, OW))
653 report_fatal_error("unable to write nop sequence of " +
654 Twine(Count) + " bytes");
658 // Otherwise, write out in multiples of the value size.
659 for (uint64_t i = 0; i != Count; ++i) {
660 switch (AF.getValueSize()) {
661 default: llvm_unreachable("Invalid size!");
662 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
663 case 2: OW->Write16(uint16_t(AF.getValue())); break;
664 case 4: OW->Write32(uint32_t(AF.getValue())); break;
665 case 8: OW->Write64(uint64_t(AF.getValue())); break;
671 case MCFragment::FT_Data:
672 ++stats::EmittedDataFragments;
673 writeFragmentContents(F, OW);
676 case MCFragment::FT_Relaxable:
677 ++stats::EmittedRelaxableFragments;
678 writeFragmentContents(F, OW);
681 case MCFragment::FT_CompactEncodedInst:
682 ++stats::EmittedCompactEncodedInstFragments;
683 writeFragmentContents(F, OW);
686 case MCFragment::FT_Fill: {
687 ++stats::EmittedFillFragments;
688 const MCFillFragment &FF = cast<MCFillFragment>(F);
690 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
692 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
693 switch (FF.getValueSize()) {
694 default: llvm_unreachable("Invalid size!");
695 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
696 case 2: OW->Write16(uint16_t(FF.getValue())); break;
697 case 4: OW->Write32(uint32_t(FF.getValue())); break;
698 case 8: OW->Write64(uint64_t(FF.getValue())); break;
704 case MCFragment::FT_LEB: {
705 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
706 OW->WriteBytes(LF.getContents());
710 case MCFragment::FT_Org: {
711 ++stats::EmittedOrgFragments;
712 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
714 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
715 OW->Write8(uint8_t(OF.getValue()));
720 case MCFragment::FT_Dwarf: {
721 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
722 OW->WriteBytes(OF.getContents());
725 case MCFragment::FT_DwarfFrame: {
726 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
727 OW->WriteBytes(CF.getContents());
732 assert(OW->getStream().tell() - Start == FragmentSize &&
733 "The stream should advance by fragment size");
736 void MCAssembler::writeSectionData(const MCSection *Sec,
737 const MCAsmLayout &Layout) const {
738 // Ignore virtual sections.
739 if (Sec->isVirtualSection()) {
740 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
742 // Check that contents are only things legal inside a virtual section.
743 for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
745 switch (it->getKind()) {
746 default: llvm_unreachable("Invalid fragment in virtual section!");
747 case MCFragment::FT_Data: {
748 // Check that we aren't trying to write a non-zero contents (or fixups)
749 // into a virtual section. This is to support clients which use standard
750 // directives to fill the contents of virtual sections.
751 const MCDataFragment &DF = cast<MCDataFragment>(*it);
752 assert(DF.fixup_begin() == DF.fixup_end() &&
753 "Cannot have fixups in virtual section!");
754 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
755 if (DF.getContents()[i]) {
756 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
757 report_fatal_error("non-zero initializer found in section '" +
758 ELFSec->getSectionName() + "'");
760 report_fatal_error("non-zero initializer found in virtual section");
764 case MCFragment::FT_Align:
765 // Check that we aren't trying to write a non-zero value into a virtual
767 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
768 cast<MCAlignFragment>(it)->getValue() == 0) &&
769 "Invalid align in virtual section!");
771 case MCFragment::FT_Fill:
772 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
773 cast<MCFillFragment>(it)->getValue() == 0) &&
774 "Invalid fill in virtual section!");
782 uint64_t Start = getWriter().getStream().tell();
785 for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
787 writeFragment(*this, Layout, *it);
789 assert(getWriter().getStream().tell() - Start ==
790 Layout.getSectionAddressSize(Sec));
793 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
795 const MCFixup &Fixup) {
796 // Evaluate the fixup.
799 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
800 MCFixupKindInfo::FKF_IsPCRel;
801 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
802 // The fixup was unresolved, we need a relocation. Inform the object
803 // writer of the relocation, and give it an opportunity to adjust the
804 // fixup value if need be.
805 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
808 return std::make_pair(FixedValue, IsPCRel);
811 void MCAssembler::Finish() {
812 DEBUG_WITH_TYPE("mc-dump", {
813 llvm::errs() << "assembler backend - pre-layout\n--\n";
816 // Create the layout object.
817 MCAsmLayout Layout(*this);
819 // Create dummy fragments and assign section ordinals.
820 unsigned SectionIndex = 0;
821 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
822 // Create dummy fragments to eliminate any empty sections, this simplifies
824 if (it->getFragmentList().empty())
825 new MCDataFragment(&*it);
827 it->setOrdinal(SectionIndex++);
830 // Assign layout order indices to sections and fragments.
831 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
832 MCSection *Sec = Layout.getSectionOrder()[i];
833 Sec->setLayoutOrder(i);
835 unsigned FragmentIndex = 0;
836 for (MCSection::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
837 iFrag != iFragEnd; ++iFrag)
838 iFrag->setLayoutOrder(FragmentIndex++);
841 // Layout until everything fits.
842 while (layoutOnce(Layout))
845 DEBUG_WITH_TYPE("mc-dump", {
846 llvm::errs() << "assembler backend - post-relaxation\n--\n";
849 // Finalize the layout, including fragment lowering.
850 finishLayout(Layout);
852 DEBUG_WITH_TYPE("mc-dump", {
853 llvm::errs() << "assembler backend - final-layout\n--\n";
856 uint64_t StartOffset = OS.tell();
858 // Allow the object writer a chance to perform post-layout binding (for
859 // example, to set the index fields in the symbol data).
860 getWriter().ExecutePostLayoutBinding(*this, Layout);
862 // Evaluate and apply the fixups, generating relocation entries as necessary.
863 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
864 for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
866 MCEncodedFragmentWithFixups *F =
867 dyn_cast<MCEncodedFragmentWithFixups>(it2);
869 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
870 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
871 MCFixup &Fixup = *it3;
874 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
875 getBackend().applyFixup(Fixup, F->getContents().data(),
876 F->getContents().size(), FixedValue, IsPCRel);
882 // Write the object file.
883 getWriter().WriteObject(*this, Layout);
885 stats::ObjectBytes += OS.tell() - StartOffset;
888 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
889 const MCRelaxableFragment *DF,
890 const MCAsmLayout &Layout) const {
891 // If we cannot resolve the fixup value, it requires relaxation.
894 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
897 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
900 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
901 const MCAsmLayout &Layout) const {
902 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
903 // are intentionally pushing out inst fragments, or because we relaxed a
904 // previous instruction to one that doesn't need relaxation.
905 if (!getBackend().mayNeedRelaxation(F->getInst()))
908 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
909 ie = F->fixup_end(); it != ie; ++it)
910 if (fixupNeedsRelaxation(*it, F, Layout))
916 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
917 MCRelaxableFragment &F) {
918 if (!fragmentNeedsRelaxation(&F, Layout))
921 ++stats::RelaxedInstructions;
923 // FIXME-PERF: We could immediately lower out instructions if we can tell
924 // they are fully resolved, to avoid retesting on later passes.
926 // Relax the fragment.
929 getBackend().relaxInstruction(F.getInst(), Relaxed);
931 // Encode the new instruction.
933 // FIXME-PERF: If it matters, we could let the target do this. It can
934 // probably do so more efficiently in many cases.
935 SmallVector<MCFixup, 4> Fixups;
936 SmallString<256> Code;
937 raw_svector_ostream VecOS(Code);
938 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
941 // Update the fragment.
943 F.getContents() = Code;
944 F.getFixups() = Fixups;
949 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
950 uint64_t OldSize = LF.getContents().size();
952 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
954 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
955 SmallString<8> &Data = LF.getContents();
957 raw_svector_ostream OSE(Data);
959 encodeSLEB128(Value, OSE);
961 encodeULEB128(Value, OSE);
963 return OldSize != LF.getContents().size();
966 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
967 MCDwarfLineAddrFragment &DF) {
968 MCContext &Context = Layout.getAssembler().getContext();
969 uint64_t OldSize = DF.getContents().size();
971 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
972 assert(Abs && "We created a line delta with an invalid expression");
975 LineDelta = DF.getLineDelta();
976 SmallString<8> &Data = DF.getContents();
978 raw_svector_ostream OSE(Data);
979 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
981 return OldSize != Data.size();
984 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
985 MCDwarfCallFrameFragment &DF) {
986 MCContext &Context = Layout.getAssembler().getContext();
987 uint64_t OldSize = DF.getContents().size();
989 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
990 assert(Abs && "We created call frame with an invalid expression");
992 SmallString<8> &Data = DF.getContents();
994 raw_svector_ostream OSE(Data);
995 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
997 return OldSize != Data.size();
1000 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1001 // Holds the first fragment which needed relaxing during this layout. It will
1002 // remain NULL if none were relaxed.
1003 // When a fragment is relaxed, all the fragments following it should get
1004 // invalidated because their offset is going to change.
1005 MCFragment *FirstRelaxedFragment = nullptr;
1007 // Attempt to relax all the fragments in the section.
1008 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1009 // Check if this is a fragment that needs relaxation.
1010 bool RelaxedFrag = false;
1011 switch(I->getKind()) {
1014 case MCFragment::FT_Relaxable:
1015 assert(!getRelaxAll() &&
1016 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1017 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1019 case MCFragment::FT_Dwarf:
1020 RelaxedFrag = relaxDwarfLineAddr(Layout,
1021 *cast<MCDwarfLineAddrFragment>(I));
1023 case MCFragment::FT_DwarfFrame:
1025 relaxDwarfCallFrameFragment(Layout,
1026 *cast<MCDwarfCallFrameFragment>(I));
1028 case MCFragment::FT_LEB:
1029 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1032 if (RelaxedFrag && !FirstRelaxedFragment)
1033 FirstRelaxedFragment = I;
1035 if (FirstRelaxedFragment) {
1036 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1042 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1043 ++stats::RelaxationSteps;
1045 bool WasRelaxed = false;
1046 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1047 MCSection &Sec = *it;
1048 while (layoutSectionOnce(Layout, Sec))
1055 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1056 // The layout is done. Mark every fragment as valid.
1057 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1058 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1062 // Debugging methods
1066 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1067 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1068 << " Value:" << *AF.getValue()
1069 << " Kind:" << AF.getKind() << ">";
1075 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1076 void MCFragment::dump() {
1077 raw_ostream &OS = llvm::errs();
1080 switch (getKind()) {
1081 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1082 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1083 case MCFragment::FT_CompactEncodedInst:
1084 OS << "MCCompactEncodedInstFragment"; break;
1085 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1086 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1087 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1088 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1089 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1090 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1093 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1094 << " Offset:" << Offset
1095 << " HasInstructions:" << hasInstructions()
1096 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1098 switch (getKind()) {
1099 case MCFragment::FT_Align: {
1100 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1101 if (AF->hasEmitNops())
1102 OS << " (emit nops)";
1104 OS << " Alignment:" << AF->getAlignment()
1105 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1106 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1109 case MCFragment::FT_Data: {
1110 const MCDataFragment *DF = cast<MCDataFragment>(this);
1112 OS << " Contents:[";
1113 const SmallVectorImpl<char> &Contents = DF->getContents();
1114 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1116 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1118 OS << "] (" << Contents.size() << " bytes)";
1120 if (DF->fixup_begin() != DF->fixup_end()) {
1123 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1124 ie = DF->fixup_end(); it != ie; ++it) {
1125 if (it != DF->fixup_begin()) OS << ",\n ";
1132 case MCFragment::FT_CompactEncodedInst: {
1133 const MCCompactEncodedInstFragment *CEIF =
1134 cast<MCCompactEncodedInstFragment>(this);
1136 OS << " Contents:[";
1137 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1138 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1140 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1142 OS << "] (" << Contents.size() << " bytes)";
1145 case MCFragment::FT_Fill: {
1146 const MCFillFragment *FF = cast<MCFillFragment>(this);
1147 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1148 << " Size:" << FF->getSize();
1151 case MCFragment::FT_Relaxable: {
1152 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1155 F->getInst().dump_pretty(OS);
1158 case MCFragment::FT_Org: {
1159 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1161 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1164 case MCFragment::FT_Dwarf: {
1165 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1167 OS << " AddrDelta:" << OF->getAddrDelta()
1168 << " LineDelta:" << OF->getLineDelta();
1171 case MCFragment::FT_DwarfFrame: {
1172 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1174 OS << " AddrDelta:" << CF->getAddrDelta();
1177 case MCFragment::FT_LEB: {
1178 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1180 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1187 void MCSymbolData::dump() const {
1188 raw_ostream &OS = llvm::errs();
1190 OS << "<MCSymbolData"
1191 << " Fragment:" << getFragment();
1193 OS << " Offset:" << getOffset();
1194 OS << " Flags:" << getFlags();
1196 OS << " (common, size:" << getCommonSize()
1197 << " align: " << getCommonAlignment() << ")";
1199 OS << " (external)";
1200 if (isPrivateExtern())
1201 OS << " (private extern)";
1205 void MCAssembler::dump() {
1206 raw_ostream &OS = llvm::errs();
1208 OS << "<MCAssembler\n";
1209 OS << " Sections:[\n ";
1210 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1211 if (it != begin()) OS << ",\n ";
1217 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1218 if (it != symbol_begin()) OS << ",\n ";
1221 OS << ", Index:" << it->getIndex() << ", ";
1222 it->getData().dump();
1229 // anchors for MC*Fragment vtables
1230 void MCEncodedFragment::anchor() { }
1231 void MCEncodedFragmentWithFixups::anchor() { }
1232 void MCDataFragment::anchor() { }
1233 void MCCompactEncodedInstFragment::anchor() { }
1234 void MCRelaxableFragment::anchor() { }
1235 void MCAlignFragment::anchor() { }
1236 void MCFillFragment::anchor() { }
1237 void MCOrgFragment::anchor() { }
1238 void MCLEBFragment::anchor() { }
1239 void MCDwarfLineAddrFragment::anchor() { }
1240 void MCDwarfCallFrameFragment::anchor() { }