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),
340 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
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;
358 IncrementalLinkerCompatible = false;
360 LOHContainer.reset();
361 VersionMinInfo.Major = 0;
363 // reset objects owned by us
364 getBackend().reset();
365 getEmitter().reset();
367 getLOHContainer().reset();
370 bool MCAssembler::registerSection(MCSection &Section) {
371 if (Section.isRegistered())
373 Sections.push_back(&Section);
374 Section.setIsRegistered(true);
378 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
379 if (ThumbFuncs.count(Symbol))
382 if (!Symbol->isVariable())
385 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
386 // is not clear if that is a bug or a feature.
387 const MCExpr *Expr = Symbol->getVariableValue();
388 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
392 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
395 const MCSymbol &Sym = Ref->getSymbol();
396 if (!isThumbFunc(&Sym))
399 ThumbFuncs.insert(Symbol); // Cache it.
403 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
404 // Non-temporary labels should always be visible to the linker.
405 if (!Symbol.isTemporary())
408 // Absolute temporary labels are never visible.
409 if (!Symbol.isInSection())
412 if (Symbol.isUsedInReloc())
418 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
419 // Linker visible symbols define atoms.
420 if (isSymbolLinkerVisible(S))
423 // Absolute and undefined symbols have no defining atom.
424 if (!S.isInSection())
427 // Non-linker visible symbols in sections which can't be atomized have no
429 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
430 *S.getFragment()->getParent()))
433 // Otherwise, return the atom for the containing fragment.
434 return S.getFragment()->getAtom();
437 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
438 const MCFixup &Fixup, const MCFragment *DF,
439 MCValue &Target, uint64_t &Value) const {
440 ++stats::evaluateFixup;
442 // FIXME: This code has some duplication with recordRelocation. We should
443 // probably merge the two into a single callback that tries to evaluate a
444 // fixup and records a relocation if one is needed.
445 const MCExpr *Expr = Fixup.getValue();
446 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
447 getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
448 // Claim to have completely evaluated the fixup, to prevent any further
449 // processing from being done.
454 bool IsPCRel = Backend.getFixupKindInfo(
455 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
459 if (Target.getSymB()) {
461 } else if (!Target.getSymA()) {
464 const MCSymbolRefExpr *A = Target.getSymA();
465 const MCSymbol &SA = A->getSymbol();
466 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
469 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
470 *this, SA, *DF, false, true);
474 IsResolved = Target.isAbsolute();
477 Value = Target.getConstant();
479 if (const MCSymbolRefExpr *A = Target.getSymA()) {
480 const MCSymbol &Sym = A->getSymbol();
482 Value += Layout.getSymbolOffset(Sym);
484 if (const MCSymbolRefExpr *B = Target.getSymB()) {
485 const MCSymbol &Sym = B->getSymbol();
487 Value -= Layout.getSymbolOffset(Sym);
491 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
492 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
493 assert((ShouldAlignPC ? IsPCRel : true) &&
494 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
497 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
499 // A number of ARM fixups in Thumb mode require that the effective PC
500 // address be determined as the 32-bit aligned version of the actual offset.
501 if (ShouldAlignPC) Offset &= ~0x3;
505 // Let the backend adjust the fixup value if necessary, including whether
506 // we need a relocation.
507 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
513 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
514 const MCFragment &F) const {
515 switch (F.getKind()) {
516 case MCFragment::FT_Data:
517 return cast<MCDataFragment>(F).getContents().size();
518 case MCFragment::FT_Relaxable:
519 return cast<MCRelaxableFragment>(F).getContents().size();
520 case MCFragment::FT_CompactEncodedInst:
521 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
522 case MCFragment::FT_Fill:
523 return cast<MCFillFragment>(F).getSize();
525 case MCFragment::FT_LEB:
526 return cast<MCLEBFragment>(F).getContents().size();
528 case MCFragment::FT_SafeSEH:
531 case MCFragment::FT_Align: {
532 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
533 unsigned Offset = Layout.getFragmentOffset(&AF);
534 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
535 // If we are padding with nops, force the padding to be larger than the
537 if (Size > 0 && AF.hasEmitNops()) {
538 while (Size % getBackend().getMinimumNopSize())
539 Size += AF.getAlignment();
541 if (Size > AF.getMaxBytesToEmit())
546 case MCFragment::FT_Org: {
547 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
549 if (!OF.getOffset().evaluateAsValue(Value, Layout))
550 report_fatal_error("expected assembly-time absolute expression");
552 // FIXME: We need a way to communicate this error.
553 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
554 int64_t TargetLocation = Value.getConstant();
555 if (const MCSymbolRefExpr *A = Value.getSymA()) {
557 if (!Layout.getSymbolOffset(A->getSymbol(), Val))
558 report_fatal_error("expected absolute expression");
559 TargetLocation += Val;
561 int64_t Size = TargetLocation - FragmentOffset;
562 if (Size < 0 || Size >= 0x40000000)
563 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
564 "' (at offset '" + Twine(FragmentOffset) + "')");
568 case MCFragment::FT_Dwarf:
569 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
570 case MCFragment::FT_DwarfFrame:
571 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
572 case MCFragment::FT_Dummy:
573 llvm_unreachable("Should not have been added");
576 llvm_unreachable("invalid fragment kind");
579 void MCAsmLayout::layoutFragment(MCFragment *F) {
580 MCFragment *Prev = F->getPrevNode();
582 // We should never try to recompute something which is valid.
583 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
584 // We should never try to compute the fragment layout if its predecessor
586 assert((!Prev || isFragmentValid(Prev)) &&
587 "Attempt to compute fragment before its predecessor!");
589 ++stats::FragmentLayouts;
591 // Compute fragment offset and size.
593 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
596 LastValidFragment[F->getParent()] = F;
598 // If bundling is enabled and this fragment has instructions in it, it has to
599 // obey the bundling restrictions. With padding, we'll have:
604 // -------------------------------------
605 // Prev |##########| F |
606 // -------------------------------------
611 // The fragment's offset will point to after the padding, and its computed
612 // size won't include the padding.
614 // When the -mc-relax-all flag is used, we optimize bundling by writting the
615 // padding directly into fragments when the instructions are emitted inside
616 // the streamer. When the fragment is larger than the bundle size, we need to
617 // ensure that it's bundle aligned. This means that if we end up with
618 // multiple fragments, we must emit bundle padding between fragments.
620 // ".align N" is an example of a directive that introduces multiple
621 // fragments. We could add a special case to handle ".align N" by emitting
622 // within-fragment padding (which would produce less padding when N is less
623 // than the bundle size), but for now we don't.
625 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
626 assert(isa<MCEncodedFragment>(F) &&
627 "Only MCEncodedFragment implementations have instructions");
628 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
630 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
631 report_fatal_error("Fragment can't be larger than a bundle size");
633 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
635 if (RequiredBundlePadding > UINT8_MAX)
636 report_fatal_error("Padding cannot exceed 255 bytes");
637 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
638 F->Offset += RequiredBundlePadding;
642 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
643 bool New = !Symbol.isRegistered();
647 Symbol.setIsRegistered(true);
648 Symbols.push_back(&Symbol);
652 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
653 MCObjectWriter *OW) const {
654 // Should NOP padding be written out before this fragment?
655 unsigned BundlePadding = F.getBundlePadding();
656 if (BundlePadding > 0) {
657 assert(isBundlingEnabled() &&
658 "Writing bundle padding with disabled bundling");
659 assert(F.hasInstructions() &&
660 "Writing bundle padding for a fragment without instructions");
662 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
663 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
664 // If the padding itself crosses a bundle boundary, it must be emitted
665 // in 2 pieces, since even nop instructions must not cross boundaries.
666 // v--------------v <- BundleAlignSize
667 // v---------v <- BundlePadding
668 // ----------------------------
669 // | Prev |####|####| F |
670 // ----------------------------
671 // ^-------------------^ <- TotalLength
672 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
673 if (!getBackend().writeNopData(DistanceToBoundary, OW))
674 report_fatal_error("unable to write NOP sequence of " +
675 Twine(DistanceToBoundary) + " bytes");
676 BundlePadding -= DistanceToBoundary;
678 if (!getBackend().writeNopData(BundlePadding, OW))
679 report_fatal_error("unable to write NOP sequence of " +
680 Twine(BundlePadding) + " bytes");
684 /// \brief Write the fragment \p F to the output file.
685 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
686 const MCFragment &F) {
687 MCObjectWriter *OW = &Asm.getWriter();
689 // FIXME: Embed in fragments instead?
690 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
692 Asm.writeFragmentPadding(F, FragmentSize, OW);
694 // This variable (and its dummy usage) is to participate in the assert at
695 // the end of the function.
696 uint64_t Start = OW->getStream().tell();
699 ++stats::EmittedFragments;
701 switch (F.getKind()) {
702 case MCFragment::FT_Align: {
703 ++stats::EmittedAlignFragments;
704 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
705 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
707 uint64_t Count = FragmentSize / AF.getValueSize();
709 // FIXME: This error shouldn't actually occur (the front end should emit
710 // multiple .align directives to enforce the semantics it wants), but is
711 // severe enough that we want to report it. How to handle this?
712 if (Count * AF.getValueSize() != FragmentSize)
713 report_fatal_error("undefined .align directive, value size '" +
714 Twine(AF.getValueSize()) +
715 "' is not a divisor of padding size '" +
716 Twine(FragmentSize) + "'");
718 // See if we are aligning with nops, and if so do that first to try to fill
719 // the Count bytes. Then if that did not fill any bytes or there are any
720 // bytes left to fill use the Value and ValueSize to fill the rest.
721 // If we are aligning with nops, ask that target to emit the right data.
722 if (AF.hasEmitNops()) {
723 if (!Asm.getBackend().writeNopData(Count, OW))
724 report_fatal_error("unable to write nop sequence of " +
725 Twine(Count) + " bytes");
729 // Otherwise, write out in multiples of the value size.
730 for (uint64_t i = 0; i != Count; ++i) {
731 switch (AF.getValueSize()) {
732 default: llvm_unreachable("Invalid size!");
733 case 1: OW->write8 (uint8_t (AF.getValue())); break;
734 case 2: OW->write16(uint16_t(AF.getValue())); break;
735 case 4: OW->write32(uint32_t(AF.getValue())); break;
736 case 8: OW->write64(uint64_t(AF.getValue())); break;
742 case MCFragment::FT_Data:
743 ++stats::EmittedDataFragments;
744 OW->writeBytes(cast<MCDataFragment>(F).getContents());
747 case MCFragment::FT_Relaxable:
748 ++stats::EmittedRelaxableFragments;
749 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
752 case MCFragment::FT_CompactEncodedInst:
753 ++stats::EmittedCompactEncodedInstFragments;
754 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
757 case MCFragment::FT_Fill: {
758 ++stats::EmittedFillFragments;
759 const MCFillFragment &FF = cast<MCFillFragment>(F);
761 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
763 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
764 switch (FF.getValueSize()) {
765 default: llvm_unreachable("Invalid size!");
766 case 1: OW->write8 (uint8_t (FF.getValue())); break;
767 case 2: OW->write16(uint16_t(FF.getValue())); break;
768 case 4: OW->write32(uint32_t(FF.getValue())); break;
769 case 8: OW->write64(uint64_t(FF.getValue())); break;
775 case MCFragment::FT_LEB: {
776 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
777 OW->writeBytes(LF.getContents());
781 case MCFragment::FT_SafeSEH: {
782 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
783 OW->write32(SF.getSymbol()->getIndex());
787 case MCFragment::FT_Org: {
788 ++stats::EmittedOrgFragments;
789 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
791 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
792 OW->write8(uint8_t(OF.getValue()));
797 case MCFragment::FT_Dwarf: {
798 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
799 OW->writeBytes(OF.getContents());
802 case MCFragment::FT_DwarfFrame: {
803 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
804 OW->writeBytes(CF.getContents());
807 case MCFragment::FT_Dummy:
808 llvm_unreachable("Should not have been added");
811 assert(OW->getStream().tell() - Start == FragmentSize &&
812 "The stream should advance by fragment size");
815 void MCAssembler::writeSectionData(const MCSection *Sec,
816 const MCAsmLayout &Layout) const {
817 // Ignore virtual sections.
818 if (Sec->isVirtualSection()) {
819 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
821 // Check that contents are only things legal inside a virtual section.
822 for (const MCFragment &F : *Sec) {
823 switch (F.getKind()) {
824 default: llvm_unreachable("Invalid fragment in virtual section!");
825 case MCFragment::FT_Data: {
826 // Check that we aren't trying to write a non-zero contents (or fixups)
827 // into a virtual section. This is to support clients which use standard
828 // directives to fill the contents of virtual sections.
829 const MCDataFragment &DF = cast<MCDataFragment>(F);
830 assert(DF.fixup_begin() == DF.fixup_end() &&
831 "Cannot have fixups in virtual section!");
832 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
833 if (DF.getContents()[i]) {
834 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
835 report_fatal_error("non-zero initializer found in section '" +
836 ELFSec->getSectionName() + "'");
838 report_fatal_error("non-zero initializer found in virtual section");
842 case MCFragment::FT_Align:
843 // Check that we aren't trying to write a non-zero value into a virtual
845 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
846 cast<MCAlignFragment>(F).getValue() == 0) &&
847 "Invalid align in virtual section!");
849 case MCFragment::FT_Fill:
850 assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
851 cast<MCFillFragment>(F).getValue() == 0) &&
852 "Invalid fill in virtual section!");
860 uint64_t Start = getWriter().getStream().tell();
863 for (const MCFragment &F : *Sec)
864 writeFragment(*this, Layout, F);
866 assert(getWriter().getStream().tell() - Start ==
867 Layout.getSectionAddressSize(Sec));
870 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
872 const MCFixup &Fixup) {
873 // Evaluate the fixup.
876 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
877 MCFixupKindInfo::FKF_IsPCRel;
878 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
879 // The fixup was unresolved, we need a relocation. Inform the object
880 // writer of the relocation, and give it an opportunity to adjust the
881 // fixup value if need be.
882 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
885 return std::make_pair(FixedValue, IsPCRel);
888 void MCAssembler::layout(MCAsmLayout &Layout) {
889 DEBUG_WITH_TYPE("mc-dump", {
890 llvm::errs() << "assembler backend - pre-layout\n--\n";
893 // Create dummy fragments and assign section ordinals.
894 unsigned SectionIndex = 0;
895 for (MCSection &Sec : *this) {
896 // Create dummy fragments to eliminate any empty sections, this simplifies
898 if (Sec.getFragmentList().empty())
899 new MCDataFragment(&Sec);
901 Sec.setOrdinal(SectionIndex++);
904 // Assign layout order indices to sections and fragments.
905 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
906 MCSection *Sec = Layout.getSectionOrder()[i];
907 Sec->setLayoutOrder(i);
909 unsigned FragmentIndex = 0;
910 for (MCFragment &Frag : *Sec)
911 Frag.setLayoutOrder(FragmentIndex++);
914 // Layout until everything fits.
915 while (layoutOnce(Layout))
918 DEBUG_WITH_TYPE("mc-dump", {
919 llvm::errs() << "assembler backend - post-relaxation\n--\n";
922 // Finalize the layout, including fragment lowering.
923 finishLayout(Layout);
925 DEBUG_WITH_TYPE("mc-dump", {
926 llvm::errs() << "assembler backend - final-layout\n--\n";
929 // Allow the object writer a chance to perform post-layout binding (for
930 // example, to set the index fields in the symbol data).
931 getWriter().executePostLayoutBinding(*this, Layout);
933 // Evaluate and apply the fixups, generating relocation entries as necessary.
934 for (MCSection &Sec : *this) {
935 for (MCFragment &Frag : Sec) {
936 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
937 // Data and relaxable fragments both have fixups. So only process
939 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
940 // being templated makes this tricky.
941 if (!F || isa<MCCompactEncodedInstFragment>(F))
943 ArrayRef<MCFixup> Fixups;
944 MutableArrayRef<char> Contents;
945 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
946 Fixups = FragWithFixups->getFixups();
947 Contents = FragWithFixups->getContents();
948 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
949 Fixups = FragWithFixups->getFixups();
950 Contents = FragWithFixups->getContents();
952 llvm_unreachable("Unknown fragment with fixups!");
953 for (const MCFixup &Fixup : Fixups) {
956 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
957 getBackend().applyFixup(Fixup, Contents.data(),
958 Contents.size(), FixedValue, IsPCRel);
964 void MCAssembler::Finish() {
965 // Create the layout object.
966 MCAsmLayout Layout(*this);
969 raw_ostream &OS = getWriter().getStream();
970 uint64_t StartOffset = OS.tell();
972 // Write the object file.
973 getWriter().writeObject(*this, Layout);
975 stats::ObjectBytes += OS.tell() - StartOffset;
978 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
979 const MCRelaxableFragment *DF,
980 const MCAsmLayout &Layout) const {
983 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
984 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
988 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
989 const MCAsmLayout &Layout) const {
990 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
991 // are intentionally pushing out inst fragments, or because we relaxed a
992 // previous instruction to one that doesn't need relaxation.
993 if (!getBackend().mayNeedRelaxation(F->getInst()))
996 for (const MCFixup &Fixup : F->getFixups())
997 if (fixupNeedsRelaxation(Fixup, F, Layout))
1003 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
1004 MCRelaxableFragment &F) {
1005 if (!fragmentNeedsRelaxation(&F, Layout))
1008 ++stats::RelaxedInstructions;
1010 // FIXME-PERF: We could immediately lower out instructions if we can tell
1011 // they are fully resolved, to avoid retesting on later passes.
1013 // Relax the fragment.
1016 getBackend().relaxInstruction(F.getInst(), Relaxed);
1018 // Encode the new instruction.
1020 // FIXME-PERF: If it matters, we could let the target do this. It can
1021 // probably do so more efficiently in many cases.
1022 SmallVector<MCFixup, 4> Fixups;
1023 SmallString<256> Code;
1024 raw_svector_ostream VecOS(Code);
1025 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
1027 // Update the fragment.
1029 F.getContents() = Code;
1030 F.getFixups() = Fixups;
1035 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1036 uint64_t OldSize = LF.getContents().size();
1038 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1040 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1041 SmallString<8> &Data = LF.getContents();
1043 raw_svector_ostream OSE(Data);
1045 encodeSLEB128(Value, OSE);
1047 encodeULEB128(Value, OSE);
1048 return OldSize != LF.getContents().size();
1051 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1052 MCDwarfLineAddrFragment &DF) {
1053 MCContext &Context = Layout.getAssembler().getContext();
1054 uint64_t OldSize = DF.getContents().size();
1056 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1057 assert(Abs && "We created a line delta with an invalid expression");
1060 LineDelta = DF.getLineDelta();
1061 SmallString<8> &Data = DF.getContents();
1063 raw_svector_ostream OSE(Data);
1064 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1066 return OldSize != Data.size();
1069 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1070 MCDwarfCallFrameFragment &DF) {
1071 MCContext &Context = Layout.getAssembler().getContext();
1072 uint64_t OldSize = DF.getContents().size();
1074 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1075 assert(Abs && "We created call frame with an invalid expression");
1077 SmallString<8> &Data = DF.getContents();
1079 raw_svector_ostream OSE(Data);
1080 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1081 return OldSize != Data.size();
1084 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1085 // Holds the first fragment which needed relaxing during this layout. It will
1086 // remain NULL if none were relaxed.
1087 // When a fragment is relaxed, all the fragments following it should get
1088 // invalidated because their offset is going to change.
1089 MCFragment *FirstRelaxedFragment = nullptr;
1091 // Attempt to relax all the fragments in the section.
1092 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1093 // Check if this is a fragment that needs relaxation.
1094 bool RelaxedFrag = false;
1095 switch(I->getKind()) {
1098 case MCFragment::FT_Relaxable:
1099 assert(!getRelaxAll() &&
1100 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1101 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1103 case MCFragment::FT_Dwarf:
1104 RelaxedFrag = relaxDwarfLineAddr(Layout,
1105 *cast<MCDwarfLineAddrFragment>(I));
1107 case MCFragment::FT_DwarfFrame:
1109 relaxDwarfCallFrameFragment(Layout,
1110 *cast<MCDwarfCallFrameFragment>(I));
1112 case MCFragment::FT_LEB:
1113 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1116 if (RelaxedFrag && !FirstRelaxedFragment)
1117 FirstRelaxedFragment = &*I;
1119 if (FirstRelaxedFragment) {
1120 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1126 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1127 ++stats::RelaxationSteps;
1129 bool WasRelaxed = false;
1130 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1131 MCSection &Sec = *it;
1132 while (layoutSectionOnce(Layout, Sec))
1139 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1140 // The layout is done. Mark every fragment as valid.
1141 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1142 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1146 // Debugging methods
1150 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1151 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1152 << " Value:" << *AF.getValue()
1153 << " Kind:" << AF.getKind() << ">";
1159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1160 void MCFragment::dump() {
1161 raw_ostream &OS = llvm::errs();
1164 switch (getKind()) {
1165 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1166 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1167 case MCFragment::FT_CompactEncodedInst:
1168 OS << "MCCompactEncodedInstFragment"; break;
1169 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1170 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1171 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1172 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1173 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1174 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1175 case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
1176 case MCFragment::FT_Dummy:
1177 OS << "MCDummyFragment";
1181 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1182 << " Offset:" << Offset
1183 << " HasInstructions:" << hasInstructions()
1184 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1186 switch (getKind()) {
1187 case MCFragment::FT_Align: {
1188 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1189 if (AF->hasEmitNops())
1190 OS << " (emit nops)";
1192 OS << " Alignment:" << AF->getAlignment()
1193 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1194 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1197 case MCFragment::FT_Data: {
1198 const MCDataFragment *DF = cast<MCDataFragment>(this);
1200 OS << " Contents:[";
1201 const SmallVectorImpl<char> &Contents = DF->getContents();
1202 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1204 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1206 OS << "] (" << Contents.size() << " bytes)";
1208 if (DF->fixup_begin() != DF->fixup_end()) {
1211 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1212 ie = DF->fixup_end(); it != ie; ++it) {
1213 if (it != DF->fixup_begin()) OS << ",\n ";
1220 case MCFragment::FT_CompactEncodedInst: {
1221 const MCCompactEncodedInstFragment *CEIF =
1222 cast<MCCompactEncodedInstFragment>(this);
1224 OS << " Contents:[";
1225 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1226 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1228 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1230 OS << "] (" << Contents.size() << " bytes)";
1233 case MCFragment::FT_Fill: {
1234 const MCFillFragment *FF = cast<MCFillFragment>(this);
1235 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1236 << " Size:" << FF->getSize();
1239 case MCFragment::FT_Relaxable: {
1240 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1243 F->getInst().dump_pretty(OS);
1246 case MCFragment::FT_Org: {
1247 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1249 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1252 case MCFragment::FT_Dwarf: {
1253 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1255 OS << " AddrDelta:" << OF->getAddrDelta()
1256 << " LineDelta:" << OF->getLineDelta();
1259 case MCFragment::FT_DwarfFrame: {
1260 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1262 OS << " AddrDelta:" << CF->getAddrDelta();
1265 case MCFragment::FT_LEB: {
1266 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1268 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1271 case MCFragment::FT_SafeSEH: {
1272 const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1274 OS << " Sym:" << F->getSymbol();
1277 case MCFragment::FT_Dummy:
1283 void MCAssembler::dump() {
1284 raw_ostream &OS = llvm::errs();
1286 OS << "<MCAssembler\n";
1287 OS << " Sections:[\n ";
1288 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1289 if (it != begin()) OS << ",\n ";
1295 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1296 if (it != symbol_begin()) OS << ",\n ";
1299 OS << ", Index:" << it->getIndex() << ", ";