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 (MCSection &Sec : Asm)
72 if (!Sec.isVirtualSection())
73 SectionOrder.push_back(&Sec);
74 for (MCSection &Sec : Asm)
75 if (Sec.isVirtualSection())
76 SectionOrder.push_back(&Sec);
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 MCSection::iterator I;
101 if (MCFragment *Cur = LastValidFragment[Sec])
102 I = ++MCSection::iterator(Cur);
106 // Advance the layout position until the fragment is valid.
107 while (!isFragmentValid(F)) {
108 assert(I != Sec->end() && "Layout bookkeeping error");
109 const_cast<MCAsmLayout *>(this)->layoutFragment(&*I);
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 if (!S.getFragment()) {
125 report_fatal_error("unable to evaluate offset to undefined symbol '" +
129 Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
133 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
134 bool ReportError, uint64_t &Val) {
136 return getLabelOffset(Layout, S, ReportError, Val);
138 // If SD is a variable, evaluate it.
140 if (!S.getVariableValue()->evaluateAsValue(Target, Layout))
141 report_fatal_error("unable to evaluate offset for variable '" +
144 uint64_t Offset = Target.getConstant();
146 const MCSymbolRefExpr *A = Target.getSymA();
149 if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
154 const MCSymbolRefExpr *B = Target.getSymB();
157 if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
166 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
167 return getSymbolOffsetImpl(*this, S, false, Val);
170 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
172 getSymbolOffsetImpl(*this, S, true, Val);
176 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
177 if (!Symbol.isVariable())
180 const MCExpr *Expr = Symbol.getVariableValue();
182 if (!Expr->evaluateAsValue(Value, *this)) {
183 Assembler.getContext().reportError(
184 SMLoc(), "expression could not be evaluated");
188 const MCSymbolRefExpr *RefB = Value.getSymB();
190 Assembler.getContext().reportError(
191 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
192 "' could not be evaluated in a subtraction expression");
196 const MCSymbolRefExpr *A = Value.getSymA();
200 const MCSymbol &ASym = A->getSymbol();
201 const MCAssembler &Asm = getAssembler();
202 if (ASym.isCommon()) {
203 // FIXME: we should probably add a SMLoc to MCExpr.
204 Asm.getContext().reportError(SMLoc(),
205 "Common symbol '" + ASym.getName() +
206 "' cannot be used in assignment expr");
213 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
214 // The size is the last fragment's end offset.
215 const MCFragment &F = Sec->getFragmentList().back();
216 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
219 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
220 // Virtual sections have no file size.
221 if (Sec->isVirtualSection())
224 // Otherwise, the file size is the same as the address space size.
225 return getSectionAddressSize(Sec);
228 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
230 uint64_t FOffset, uint64_t FSize) {
231 uint64_t BundleSize = Assembler.getBundleAlignSize();
232 assert(BundleSize > 0 &&
233 "computeBundlePadding should only be called if bundling is enabled");
234 uint64_t BundleMask = BundleSize - 1;
235 uint64_t OffsetInBundle = FOffset & BundleMask;
236 uint64_t EndOfFragment = OffsetInBundle + FSize;
238 // There are two kinds of bundling restrictions:
240 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
241 // *end* on a bundle boundary.
242 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
243 // would, add padding until the end of the bundle so that the fragment
244 // will start in a new one.
245 if (F->alignToBundleEnd()) {
246 // Three possibilities here:
248 // A) The fragment just happens to end at a bundle boundary, so we're good.
249 // B) The fragment ends before the current bundle boundary: pad it just
250 // enough to reach the boundary.
251 // C) The fragment ends after the current bundle boundary: pad it until it
252 // reaches the end of the next bundle boundary.
254 // Note: this code could be made shorter with some modulo trickery, but it's
255 // intentionally kept in its more explicit form for simplicity.
256 if (EndOfFragment == BundleSize)
258 else if (EndOfFragment < BundleSize)
259 return BundleSize - EndOfFragment;
260 else { // EndOfFragment > BundleSize
261 return 2 * BundleSize - EndOfFragment;
263 } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
264 return BundleSize - OffsetInBundle;
271 void ilist_node_traits<MCFragment>::deleteNode(MCFragment *V) {
275 MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
276 AlignToBundleEnd(false), BundlePadding(0) {
279 MCFragment::~MCFragment() { }
281 MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
282 uint8_t BundlePadding, MCSection *Parent)
283 : Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
284 BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
285 Offset(~UINT64_C(0)) {
286 if (Parent && !isDummy())
287 Parent->getFragmentList().push_back(this);
290 void MCFragment::destroy() {
291 // First check if we are the sentinal.
292 if (Kind == FragmentType(~0)) {
299 delete cast<MCAlignFragment>(this);
302 delete cast<MCDataFragment>(this);
304 case FT_CompactEncodedInst:
305 delete cast<MCCompactEncodedInstFragment>(this);
308 delete cast<MCFillFragment>(this);
311 delete cast<MCRelaxableFragment>(this);
314 delete cast<MCOrgFragment>(this);
317 delete cast<MCDwarfLineAddrFragment>(this);
320 delete cast<MCDwarfCallFrameFragment>(this);
323 delete cast<MCLEBFragment>(this);
326 delete cast<MCSafeSEHFragment>(this);
329 delete cast<MCDummyFragment>(this);
336 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
337 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
338 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
339 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
341 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
344 MCAssembler::~MCAssembler() {
347 void MCAssembler::reset() {
350 IndirectSymbols.clear();
352 LinkerOptions.clear();
357 SubsectionsViaSymbols = false;
359 LOHContainer.reset();
360 VersionMinInfo.Major = 0;
362 // reset objects owned by us
363 getBackend().reset();
364 getEmitter().reset();
366 getLOHContainer().reset();
369 bool MCAssembler::registerSection(MCSection &Section) {
370 if (Section.isRegistered())
372 Sections.push_back(&Section);
373 Section.setIsRegistered(true);
377 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
378 if (ThumbFuncs.count(Symbol))
381 if (!Symbol->isVariable())
384 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
385 // is not clear if that is a bug or a feature.
386 const MCExpr *Expr = Symbol->getVariableValue();
387 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
391 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
394 const MCSymbol &Sym = Ref->getSymbol();
395 if (!isThumbFunc(&Sym))
398 ThumbFuncs.insert(Symbol); // Cache it.
402 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
403 // Non-temporary labels should always be visible to the linker.
404 if (!Symbol.isTemporary())
407 // Absolute temporary labels are never visible.
408 if (!Symbol.isInSection())
411 if (Symbol.isUsedInReloc())
417 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
418 // Linker visible symbols define atoms.
419 if (isSymbolLinkerVisible(S))
422 // Absolute and undefined symbols have no defining atom.
423 if (!S.isInSection())
426 // Non-linker visible symbols in sections which can't be atomized have no
428 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
429 *S.getFragment()->getParent()))
432 // Otherwise, return the atom for the containing fragment.
433 return S.getFragment()->getAtom();
436 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
437 const MCFixup &Fixup, const MCFragment *DF,
438 MCValue &Target, uint64_t &Value) const {
439 ++stats::evaluateFixup;
441 // FIXME: This code has some duplication with recordRelocation. We should
442 // probably merge the two into a single callback that tries to evaluate a
443 // fixup and records a relocation if one is needed.
444 const MCExpr *Expr = Fixup.getValue();
445 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
446 getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
447 // Claim to have completely evaluated the fixup, to prevent any further
448 // processing from being done.
453 bool IsPCRel = Backend.getFixupKindInfo(
454 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
458 if (Target.getSymB()) {
460 } else if (!Target.getSymA()) {
463 const MCSymbolRefExpr *A = Target.getSymA();
464 const MCSymbol &SA = A->getSymbol();
465 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
468 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
469 *this, SA, *DF, false, true);
473 IsResolved = Target.isAbsolute();
476 Value = Target.getConstant();
478 if (const MCSymbolRefExpr *A = Target.getSymA()) {
479 const MCSymbol &Sym = A->getSymbol();
481 Value += Layout.getSymbolOffset(Sym);
483 if (const MCSymbolRefExpr *B = Target.getSymB()) {
484 const MCSymbol &Sym = B->getSymbol();
486 Value -= Layout.getSymbolOffset(Sym);
490 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
491 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
492 assert((ShouldAlignPC ? IsPCRel : true) &&
493 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
496 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
498 // A number of ARM fixups in Thumb mode require that the effective PC
499 // address be determined as the 32-bit aligned version of the actual offset.
500 if (ShouldAlignPC) Offset &= ~0x3;
504 // Let the backend adjust the fixup value if necessary, including whether
505 // we need a relocation.
506 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
512 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
513 const MCFragment &F) const {
514 switch (F.getKind()) {
515 case MCFragment::FT_Data:
516 return cast<MCDataFragment>(F).getContents().size();
517 case MCFragment::FT_Relaxable:
518 return cast<MCRelaxableFragment>(F).getContents().size();
519 case MCFragment::FT_CompactEncodedInst:
520 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
521 case MCFragment::FT_Fill:
522 return cast<MCFillFragment>(F).getSize();
524 case MCFragment::FT_LEB:
525 return cast<MCLEBFragment>(F).getContents().size();
527 case MCFragment::FT_SafeSEH:
530 case MCFragment::FT_Align: {
531 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
532 unsigned Offset = Layout.getFragmentOffset(&AF);
533 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
534 // If we are padding with nops, force the padding to be larger than the
536 if (Size > 0 && AF.hasEmitNops()) {
537 while (Size % getBackend().getMinimumNopSize())
538 Size += AF.getAlignment();
540 if (Size > AF.getMaxBytesToEmit())
545 case MCFragment::FT_Org: {
546 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
548 if (!OF.getOffset().evaluateAsValue(Value, Layout))
549 report_fatal_error("expected assembly-time absolute expression");
551 // FIXME: We need a way to communicate this error.
552 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
553 int64_t TargetLocation = Value.getConstant();
554 if (const MCSymbolRefExpr *A = Value.getSymA()) {
556 if (!Layout.getSymbolOffset(A->getSymbol(), Val))
557 report_fatal_error("expected absolute expression");
558 TargetLocation += Val;
560 int64_t Size = TargetLocation - FragmentOffset;
561 if (Size < 0 || Size >= 0x40000000)
562 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
563 "' (at offset '" + Twine(FragmentOffset) + "')");
567 case MCFragment::FT_Dwarf:
568 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
569 case MCFragment::FT_DwarfFrame:
570 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
571 case MCFragment::FT_Dummy:
572 llvm_unreachable("Should not have been added");
575 llvm_unreachable("invalid fragment kind");
578 void MCAsmLayout::layoutFragment(MCFragment *F) {
579 MCFragment *Prev = F->getPrevNode();
581 // We should never try to recompute something which is valid.
582 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
583 // We should never try to compute the fragment layout if its predecessor
585 assert((!Prev || isFragmentValid(Prev)) &&
586 "Attempt to compute fragment before its predecessor!");
588 ++stats::FragmentLayouts;
590 // Compute fragment offset and size.
592 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
595 LastValidFragment[F->getParent()] = F;
597 // If bundling is enabled and this fragment has instructions in it, it has to
598 // obey the bundling restrictions. With padding, we'll have:
603 // -------------------------------------
604 // Prev |##########| F |
605 // -------------------------------------
610 // The fragment's offset will point to after the padding, and its computed
611 // size won't include the padding.
613 // When the -mc-relax-all flag is used, we optimize bundling by writting the
614 // padding directly into fragments when the instructions are emitted inside
615 // the streamer. When the fragment is larger than the bundle size, we need to
616 // ensure that it's bundle aligned. This means that if we end up with
617 // multiple fragments, we must emit bundle padding between fragments.
619 // ".align N" is an example of a directive that introduces multiple
620 // fragments. We could add a special case to handle ".align N" by emitting
621 // within-fragment padding (which would produce less padding when N is less
622 // than the bundle size), but for now we don't.
624 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
625 assert(isa<MCEncodedFragment>(F) &&
626 "Only MCEncodedFragment implementations have instructions");
627 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
629 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
630 report_fatal_error("Fragment can't be larger than a bundle size");
632 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
634 if (RequiredBundlePadding > UINT8_MAX)
635 report_fatal_error("Padding cannot exceed 255 bytes");
636 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
637 F->Offset += RequiredBundlePadding;
641 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
642 bool New = !Symbol.isRegistered();
646 Symbol.setIsRegistered(true);
647 Symbols.push_back(&Symbol);
651 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
652 MCObjectWriter *OW) const {
653 // Should NOP padding be written out before this fragment?
654 unsigned BundlePadding = F.getBundlePadding();
655 if (BundlePadding > 0) {
656 assert(isBundlingEnabled() &&
657 "Writing bundle padding with disabled bundling");
658 assert(F.hasInstructions() &&
659 "Writing bundle padding for a fragment without instructions");
661 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
662 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
663 // If the padding itself crosses a bundle boundary, it must be emitted
664 // in 2 pieces, since even nop instructions must not cross boundaries.
665 // v--------------v <- BundleAlignSize
666 // v---------v <- BundlePadding
667 // ----------------------------
668 // | Prev |####|####| F |
669 // ----------------------------
670 // ^-------------------^ <- TotalLength
671 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
672 if (!getBackend().writeNopData(DistanceToBoundary, OW))
673 report_fatal_error("unable to write NOP sequence of " +
674 Twine(DistanceToBoundary) + " bytes");
675 BundlePadding -= DistanceToBoundary;
677 if (!getBackend().writeNopData(BundlePadding, OW))
678 report_fatal_error("unable to write NOP sequence of " +
679 Twine(BundlePadding) + " bytes");
683 /// \brief Write the fragment \p F to the output file.
684 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
685 const MCFragment &F) {
686 MCObjectWriter *OW = &Asm.getWriter();
688 // FIXME: Embed in fragments instead?
689 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
691 Asm.writeFragmentPadding(F, FragmentSize, OW);
693 // This variable (and its dummy usage) is to participate in the assert at
694 // the end of the function.
695 uint64_t Start = OW->getStream().tell();
698 ++stats::EmittedFragments;
700 switch (F.getKind()) {
701 case MCFragment::FT_Align: {
702 ++stats::EmittedAlignFragments;
703 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
704 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
706 uint64_t Count = FragmentSize / AF.getValueSize();
708 // FIXME: This error shouldn't actually occur (the front end should emit
709 // multiple .align directives to enforce the semantics it wants), but is
710 // severe enough that we want to report it. How to handle this?
711 if (Count * AF.getValueSize() != FragmentSize)
712 report_fatal_error("undefined .align directive, value size '" +
713 Twine(AF.getValueSize()) +
714 "' is not a divisor of padding size '" +
715 Twine(FragmentSize) + "'");
717 // See if we are aligning with nops, and if so do that first to try to fill
718 // the Count bytes. Then if that did not fill any bytes or there are any
719 // bytes left to fill use the Value and ValueSize to fill the rest.
720 // If we are aligning with nops, ask that target to emit the right data.
721 if (AF.hasEmitNops()) {
722 if (!Asm.getBackend().writeNopData(Count, OW))
723 report_fatal_error("unable to write nop sequence of " +
724 Twine(Count) + " bytes");
728 // Otherwise, write out in multiples of the value size.
729 for (uint64_t i = 0; i != Count; ++i) {
730 switch (AF.getValueSize()) {
731 default: llvm_unreachable("Invalid size!");
732 case 1: OW->write8 (uint8_t (AF.getValue())); break;
733 case 2: OW->write16(uint16_t(AF.getValue())); break;
734 case 4: OW->write32(uint32_t(AF.getValue())); break;
735 case 8: OW->write64(uint64_t(AF.getValue())); break;
741 case MCFragment::FT_Data:
742 ++stats::EmittedDataFragments;
743 OW->writeBytes(cast<MCDataFragment>(F).getContents());
746 case MCFragment::FT_Relaxable:
747 ++stats::EmittedRelaxableFragments;
748 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
751 case MCFragment::FT_CompactEncodedInst:
752 ++stats::EmittedCompactEncodedInstFragments;
753 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
756 case MCFragment::FT_Fill: {
757 ++stats::EmittedFillFragments;
758 const MCFillFragment &FF = cast<MCFillFragment>(F);
760 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
762 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
763 switch (FF.getValueSize()) {
764 default: llvm_unreachable("Invalid size!");
765 case 1: OW->write8 (uint8_t (FF.getValue())); break;
766 case 2: OW->write16(uint16_t(FF.getValue())); break;
767 case 4: OW->write32(uint32_t(FF.getValue())); break;
768 case 8: OW->write64(uint64_t(FF.getValue())); break;
774 case MCFragment::FT_LEB: {
775 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
776 OW->writeBytes(LF.getContents());
780 case MCFragment::FT_SafeSEH: {
781 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
782 OW->write32(SF.getSymbol()->getIndex());
786 case MCFragment::FT_Org: {
787 ++stats::EmittedOrgFragments;
788 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
790 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
791 OW->write8(uint8_t(OF.getValue()));
796 case MCFragment::FT_Dwarf: {
797 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
798 OW->writeBytes(OF.getContents());
801 case MCFragment::FT_DwarfFrame: {
802 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
803 OW->writeBytes(CF.getContents());
806 case MCFragment::FT_Dummy:
807 llvm_unreachable("Should not have been added");
810 assert(OW->getStream().tell() - Start == FragmentSize &&
811 "The stream should advance by fragment size");
814 void MCAssembler::writeSectionData(const MCSection *Sec,
815 const MCAsmLayout &Layout) const {
816 // Ignore virtual sections.
817 if (Sec->isVirtualSection()) {
818 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
820 // Check that contents are only things legal inside a virtual section.
821 for (const MCFragment &F : *Sec) {
822 switch (F.getKind()) {
823 default: llvm_unreachable("Invalid fragment in virtual section!");
824 case MCFragment::FT_Data: {
825 // Check that we aren't trying to write a non-zero contents (or fixups)
826 // into a virtual section. This is to support clients which use standard
827 // directives to fill the contents of virtual sections.
828 const MCDataFragment &DF = cast<MCDataFragment>(F);
829 assert(DF.fixup_begin() == DF.fixup_end() &&
830 "Cannot have fixups in virtual section!");
831 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
832 if (DF.getContents()[i]) {
833 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
834 report_fatal_error("non-zero initializer found in section '" +
835 ELFSec->getSectionName() + "'");
837 report_fatal_error("non-zero initializer found in virtual section");
841 case MCFragment::FT_Align:
842 // Check that we aren't trying to write a non-zero value into a virtual
844 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
845 cast<MCAlignFragment>(F).getValue() == 0) &&
846 "Invalid align in virtual section!");
848 case MCFragment::FT_Fill:
849 assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
850 cast<MCFillFragment>(F).getValue() == 0) &&
851 "Invalid fill in virtual section!");
859 uint64_t Start = getWriter().getStream().tell();
862 for (const MCFragment &F : *Sec)
863 writeFragment(*this, Layout, F);
865 assert(getWriter().getStream().tell() - Start ==
866 Layout.getSectionAddressSize(Sec));
869 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
871 const MCFixup &Fixup) {
872 // Evaluate the fixup.
875 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
876 MCFixupKindInfo::FKF_IsPCRel;
877 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
878 // The fixup was unresolved, we need a relocation. Inform the object
879 // writer of the relocation, and give it an opportunity to adjust the
880 // fixup value if need be.
881 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
884 return std::make_pair(FixedValue, IsPCRel);
887 void MCAssembler::layout(MCAsmLayout &Layout) {
888 DEBUG_WITH_TYPE("mc-dump", {
889 llvm::errs() << "assembler backend - pre-layout\n--\n";
892 // Create dummy fragments and assign section ordinals.
893 unsigned SectionIndex = 0;
894 for (MCSection &Sec : *this) {
895 // Create dummy fragments to eliminate any empty sections, this simplifies
897 if (Sec.getFragmentList().empty())
898 new MCDataFragment(&Sec);
900 Sec.setOrdinal(SectionIndex++);
903 // Assign layout order indices to sections and fragments.
904 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
905 MCSection *Sec = Layout.getSectionOrder()[i];
906 Sec->setLayoutOrder(i);
908 unsigned FragmentIndex = 0;
909 for (MCFragment &Frag : *Sec)
910 Frag.setLayoutOrder(FragmentIndex++);
913 // Layout until everything fits.
914 while (layoutOnce(Layout))
917 DEBUG_WITH_TYPE("mc-dump", {
918 llvm::errs() << "assembler backend - post-relaxation\n--\n";
921 // Finalize the layout, including fragment lowering.
922 finishLayout(Layout);
924 DEBUG_WITH_TYPE("mc-dump", {
925 llvm::errs() << "assembler backend - final-layout\n--\n";
928 // Allow the object writer a chance to perform post-layout binding (for
929 // example, to set the index fields in the symbol data).
930 getWriter().executePostLayoutBinding(*this, Layout);
932 // Evaluate and apply the fixups, generating relocation entries as necessary.
933 for (MCSection &Sec : *this) {
934 for (MCFragment &Frag : Sec) {
935 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
936 // Data and relaxable fragments both have fixups. So only process
938 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
939 // being templated makes this tricky.
940 if (!F || isa<MCCompactEncodedInstFragment>(F))
942 ArrayRef<MCFixup> Fixups;
943 MutableArrayRef<char> Contents;
944 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
945 Fixups = FragWithFixups->getFixups();
946 Contents = FragWithFixups->getContents();
947 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
948 Fixups = FragWithFixups->getFixups();
949 Contents = FragWithFixups->getContents();
951 llvm_unreachable("Unknown fragment with fixups!");
952 for (const MCFixup &Fixup : Fixups) {
955 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
956 getBackend().applyFixup(Fixup, Contents.data(),
957 Contents.size(), FixedValue, IsPCRel);
963 void MCAssembler::Finish() {
964 // Create the layout object.
965 MCAsmLayout Layout(*this);
968 raw_ostream &OS = getWriter().getStream();
969 uint64_t StartOffset = OS.tell();
971 // Write the object file.
972 getWriter().writeObject(*this, Layout);
974 stats::ObjectBytes += OS.tell() - StartOffset;
977 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
978 const MCRelaxableFragment *DF,
979 const MCAsmLayout &Layout) const {
982 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
983 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
987 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
988 const MCAsmLayout &Layout) const {
989 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
990 // are intentionally pushing out inst fragments, or because we relaxed a
991 // previous instruction to one that doesn't need relaxation.
992 if (!getBackend().mayNeedRelaxation(F->getInst()))
995 for (const MCFixup &Fixup : F->getFixups())
996 if (fixupNeedsRelaxation(Fixup, F, Layout))
1002 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
1003 MCRelaxableFragment &F) {
1004 if (!fragmentNeedsRelaxation(&F, Layout))
1007 ++stats::RelaxedInstructions;
1009 // FIXME-PERF: We could immediately lower out instructions if we can tell
1010 // they are fully resolved, to avoid retesting on later passes.
1012 // Relax the fragment.
1015 getBackend().relaxInstruction(F.getInst(), Relaxed);
1017 // Encode the new instruction.
1019 // FIXME-PERF: If it matters, we could let the target do this. It can
1020 // probably do so more efficiently in many cases.
1021 SmallVector<MCFixup, 4> Fixups;
1022 SmallString<256> Code;
1023 raw_svector_ostream VecOS(Code);
1024 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
1026 // Update the fragment.
1028 F.getContents() = Code;
1029 F.getFixups() = Fixups;
1034 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1035 uint64_t OldSize = LF.getContents().size();
1037 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1039 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1040 SmallString<8> &Data = LF.getContents();
1042 raw_svector_ostream OSE(Data);
1044 encodeSLEB128(Value, OSE);
1046 encodeULEB128(Value, OSE);
1047 return OldSize != LF.getContents().size();
1050 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1051 MCDwarfLineAddrFragment &DF) {
1052 MCContext &Context = Layout.getAssembler().getContext();
1053 uint64_t OldSize = DF.getContents().size();
1055 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1056 assert(Abs && "We created a line delta with an invalid expression");
1059 LineDelta = DF.getLineDelta();
1060 SmallString<8> &Data = DF.getContents();
1062 raw_svector_ostream OSE(Data);
1063 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1065 return OldSize != Data.size();
1068 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1069 MCDwarfCallFrameFragment &DF) {
1070 MCContext &Context = Layout.getAssembler().getContext();
1071 uint64_t OldSize = DF.getContents().size();
1073 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1074 assert(Abs && "We created call frame with an invalid expression");
1076 SmallString<8> &Data = DF.getContents();
1078 raw_svector_ostream OSE(Data);
1079 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1080 return OldSize != Data.size();
1083 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1084 // Holds the first fragment which needed relaxing during this layout. It will
1085 // remain NULL if none were relaxed.
1086 // When a fragment is relaxed, all the fragments following it should get
1087 // invalidated because their offset is going to change.
1088 MCFragment *FirstRelaxedFragment = nullptr;
1090 // Attempt to relax all the fragments in the section.
1091 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1092 // Check if this is a fragment that needs relaxation.
1093 bool RelaxedFrag = false;
1094 switch(I->getKind()) {
1097 case MCFragment::FT_Relaxable:
1098 assert(!getRelaxAll() &&
1099 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1100 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1102 case MCFragment::FT_Dwarf:
1103 RelaxedFrag = relaxDwarfLineAddr(Layout,
1104 *cast<MCDwarfLineAddrFragment>(I));
1106 case MCFragment::FT_DwarfFrame:
1108 relaxDwarfCallFrameFragment(Layout,
1109 *cast<MCDwarfCallFrameFragment>(I));
1111 case MCFragment::FT_LEB:
1112 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1115 if (RelaxedFrag && !FirstRelaxedFragment)
1116 FirstRelaxedFragment = &*I;
1118 if (FirstRelaxedFragment) {
1119 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1125 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1126 ++stats::RelaxationSteps;
1128 bool WasRelaxed = false;
1129 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1130 MCSection &Sec = *it;
1131 while (layoutSectionOnce(Layout, Sec))
1138 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1139 // The layout is done. Mark every fragment as valid.
1140 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1141 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1145 // Debugging methods
1149 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1150 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1151 << " Value:" << *AF.getValue()
1152 << " Kind:" << AF.getKind() << ">";
1158 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1159 void MCFragment::dump() {
1160 raw_ostream &OS = llvm::errs();
1163 switch (getKind()) {
1164 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1165 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1166 case MCFragment::FT_CompactEncodedInst:
1167 OS << "MCCompactEncodedInstFragment"; break;
1168 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1169 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1170 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1171 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1172 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1173 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1174 case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
1175 case MCFragment::FT_Dummy:
1176 OS << "MCDummyFragment";
1180 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1181 << " Offset:" << Offset
1182 << " HasInstructions:" << hasInstructions()
1183 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1185 switch (getKind()) {
1186 case MCFragment::FT_Align: {
1187 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1188 if (AF->hasEmitNops())
1189 OS << " (emit nops)";
1191 OS << " Alignment:" << AF->getAlignment()
1192 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1193 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1196 case MCFragment::FT_Data: {
1197 const MCDataFragment *DF = cast<MCDataFragment>(this);
1199 OS << " Contents:[";
1200 const SmallVectorImpl<char> &Contents = DF->getContents();
1201 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1203 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1205 OS << "] (" << Contents.size() << " bytes)";
1207 if (DF->fixup_begin() != DF->fixup_end()) {
1210 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1211 ie = DF->fixup_end(); it != ie; ++it) {
1212 if (it != DF->fixup_begin()) OS << ",\n ";
1219 case MCFragment::FT_CompactEncodedInst: {
1220 const MCCompactEncodedInstFragment *CEIF =
1221 cast<MCCompactEncodedInstFragment>(this);
1223 OS << " Contents:[";
1224 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1225 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1227 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1229 OS << "] (" << Contents.size() << " bytes)";
1232 case MCFragment::FT_Fill: {
1233 const MCFillFragment *FF = cast<MCFillFragment>(this);
1234 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1235 << " Size:" << FF->getSize();
1238 case MCFragment::FT_Relaxable: {
1239 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1242 F->getInst().dump_pretty(OS);
1245 case MCFragment::FT_Org: {
1246 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1248 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1251 case MCFragment::FT_Dwarf: {
1252 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1254 OS << " AddrDelta:" << OF->getAddrDelta()
1255 << " LineDelta:" << OF->getLineDelta();
1258 case MCFragment::FT_DwarfFrame: {
1259 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1261 OS << " AddrDelta:" << CF->getAddrDelta();
1264 case MCFragment::FT_LEB: {
1265 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1267 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1270 case MCFragment::FT_SafeSEH: {
1271 const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1273 OS << " Sym:" << F->getSymbol();
1276 case MCFragment::FT_Dummy:
1282 void MCAssembler::dump() {
1283 raw_ostream &OS = llvm::errs();
1285 OS << "<MCAssembler\n";
1286 OS << " Sections:[\n ";
1287 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1288 if (it != begin()) OS << ",\n ";
1294 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1295 if (it != symbol_begin()) OS << ",\n ";
1298 OS << ", Index:" << it->getIndex() << ", ";