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 MCSectionData::MCSectionData(MCSection &Section) : Section(&Section) {}
295 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
296 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
298 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
299 OS(OS_), BundleAlignSize(0), RelaxAll(false),
300 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
301 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
304 MCAssembler::~MCAssembler() {
307 void MCAssembler::reset() {
310 IndirectSymbols.clear();
312 LinkerOptions.clear();
317 SubsectionsViaSymbols = false;
319 LOHContainer.reset();
320 VersionMinInfo.Major = 0;
322 // reset objects owned by us
323 getBackend().reset();
324 getEmitter().reset();
326 getLOHContainer().reset();
329 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
330 if (ThumbFuncs.count(Symbol))
333 if (!Symbol->isVariable())
336 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
337 // is not clear if that is a bug or a feature.
338 const MCExpr *Expr = Symbol->getVariableValue();
339 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
343 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
346 const MCSymbol &Sym = Ref->getSymbol();
347 if (!isThumbFunc(&Sym))
350 ThumbFuncs.insert(Symbol); // Cache it.
354 void MCAssembler::addLocalUsedInReloc(const MCSymbol &Sym) {
355 assert(Sym.isTemporary());
356 LocalsUsedInReloc.insert(&Sym);
359 bool MCAssembler::isLocalUsedInReloc(const MCSymbol &Sym) const {
360 assert(Sym.isTemporary());
361 return LocalsUsedInReloc.count(&Sym);
364 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
365 // Non-temporary labels should always be visible to the linker.
366 if (!Symbol.isTemporary())
369 // Absolute temporary labels are never visible.
370 if (!Symbol.isInSection())
373 if (isLocalUsedInReloc(Symbol))
379 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
380 // Linker visible symbols define atoms.
381 if (isSymbolLinkerVisible(S))
384 // Absolute and undefined symbols have no defining atom.
385 if (!S.getData().getFragment())
388 // Non-linker visible symbols in sections which can't be atomized have no
390 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
391 *S.getData().getFragment()->getParent()))
394 // Otherwise, return the atom for the containing fragment.
395 return S.getData().getFragment()->getAtom();
398 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
399 const MCFixup &Fixup, const MCFragment *DF,
400 MCValue &Target, uint64_t &Value) const {
401 ++stats::evaluateFixup;
403 // FIXME: This code has some duplication with RecordRelocation. We should
404 // probably merge the two into a single callback that tries to evaluate a
405 // fixup and records a relocation if one is needed.
406 const MCExpr *Expr = Fixup.getValue();
407 if (!Expr->EvaluateAsRelocatable(Target, &Layout, &Fixup))
408 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
410 bool IsPCRel = Backend.getFixupKindInfo(
411 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
415 if (Target.getSymB()) {
417 } else if (!Target.getSymA()) {
420 const MCSymbolRefExpr *A = Target.getSymA();
421 const MCSymbol &SA = A->getSymbol();
422 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
425 IsResolved = getWriter().IsSymbolRefDifferenceFullyResolvedImpl(
426 *this, SA, *DF, false, true);
430 IsResolved = Target.isAbsolute();
433 Value = Target.getConstant();
435 if (const MCSymbolRefExpr *A = Target.getSymA()) {
436 const MCSymbol &Sym = A->getSymbol();
438 Value += Layout.getSymbolOffset(Sym);
440 if (const MCSymbolRefExpr *B = Target.getSymB()) {
441 const MCSymbol &Sym = B->getSymbol();
443 Value -= Layout.getSymbolOffset(Sym);
447 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
448 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
449 assert((ShouldAlignPC ? IsPCRel : true) &&
450 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
453 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
455 // A number of ARM fixups in Thumb mode require that the effective PC
456 // address be determined as the 32-bit aligned version of the actual offset.
457 if (ShouldAlignPC) Offset &= ~0x3;
461 // Let the backend adjust the fixup value if necessary, including whether
462 // we need a relocation.
463 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
469 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
470 const MCFragment &F) const {
471 switch (F.getKind()) {
472 case MCFragment::FT_Data:
473 case MCFragment::FT_Relaxable:
474 case MCFragment::FT_CompactEncodedInst:
475 return cast<MCEncodedFragment>(F).getContents().size();
476 case MCFragment::FT_Fill:
477 return cast<MCFillFragment>(F).getSize();
479 case MCFragment::FT_LEB:
480 return cast<MCLEBFragment>(F).getContents().size();
482 case MCFragment::FT_Align: {
483 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
484 unsigned Offset = Layout.getFragmentOffset(&AF);
485 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
486 // If we are padding with nops, force the padding to be larger than the
488 if (Size > 0 && AF.hasEmitNops()) {
489 while (Size % getBackend().getMinimumNopSize())
490 Size += AF.getAlignment();
492 if (Size > AF.getMaxBytesToEmit())
497 case MCFragment::FT_Org: {
498 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
499 int64_t TargetLocation;
500 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
501 report_fatal_error("expected assembly-time absolute expression");
503 // FIXME: We need a way to communicate this error.
504 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
505 int64_t Size = TargetLocation - FragmentOffset;
506 if (Size < 0 || Size >= 0x40000000)
507 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
508 "' (at offset '" + Twine(FragmentOffset) + "')");
512 case MCFragment::FT_Dwarf:
513 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
514 case MCFragment::FT_DwarfFrame:
515 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
518 llvm_unreachable("invalid fragment kind");
521 void MCAsmLayout::layoutFragment(MCFragment *F) {
522 MCFragment *Prev = F->getPrevNode();
524 // We should never try to recompute something which is valid.
525 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
526 // We should never try to compute the fragment layout if its predecessor
528 assert((!Prev || isFragmentValid(Prev)) &&
529 "Attempt to compute fragment before its predecessor!");
531 ++stats::FragmentLayouts;
533 // Compute fragment offset and size.
535 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
538 LastValidFragment[F->getParent()] = F;
540 // If bundling is enabled and this fragment has instructions in it, it has to
541 // obey the bundling restrictions. With padding, we'll have:
546 // -------------------------------------
547 // Prev |##########| F |
548 // -------------------------------------
553 // The fragment's offset will point to after the padding, and its computed
554 // size won't include the padding.
556 // When the -mc-relax-all flag is used, we optimize bundling by writting the
557 // bundle padding directly into fragments when the instructions are emitted
558 // inside the streamer.
560 if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
561 F->hasInstructions()) {
562 assert(isa<MCEncodedFragment>(F) &&
563 "Only MCEncodedFragment implementations have instructions");
564 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
566 if (FSize > Assembler.getBundleAlignSize())
567 report_fatal_error("Fragment can't be larger than a bundle size");
569 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
571 if (RequiredBundlePadding > UINT8_MAX)
572 report_fatal_error("Padding cannot exceed 255 bytes");
573 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
574 F->Offset += RequiredBundlePadding;
578 /// \brief Write the contents of a fragment to the given object writer. Expects
579 /// a MCEncodedFragment.
580 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
581 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
582 OW->WriteBytes(EF.getContents());
585 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
586 MCObjectWriter *OW) const {
587 // Should NOP padding be written out before this fragment?
588 unsigned BundlePadding = F.getBundlePadding();
589 if (BundlePadding > 0) {
590 assert(isBundlingEnabled() &&
591 "Writing bundle padding with disabled bundling");
592 assert(F.hasInstructions() &&
593 "Writing bundle padding for a fragment without instructions");
595 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
596 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
597 // If the padding itself crosses a bundle boundary, it must be emitted
598 // in 2 pieces, since even nop instructions must not cross boundaries.
599 // v--------------v <- BundleAlignSize
600 // v---------v <- BundlePadding
601 // ----------------------------
602 // | Prev |####|####| F |
603 // ----------------------------
604 // ^-------------------^ <- TotalLength
605 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
606 if (!getBackend().writeNopData(DistanceToBoundary, OW))
607 report_fatal_error("unable to write NOP sequence of " +
608 Twine(DistanceToBoundary) + " bytes");
609 BundlePadding -= DistanceToBoundary;
611 if (!getBackend().writeNopData(BundlePadding, OW))
612 report_fatal_error("unable to write NOP sequence of " +
613 Twine(BundlePadding) + " bytes");
617 /// \brief Write the fragment \p F to the output file.
618 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
619 const MCFragment &F) {
620 MCObjectWriter *OW = &Asm.getWriter();
622 // FIXME: Embed in fragments instead?
623 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
625 Asm.writeFragmentPadding(F, FragmentSize, OW);
627 // This variable (and its dummy usage) is to participate in the assert at
628 // the end of the function.
629 uint64_t Start = OW->getStream().tell();
632 ++stats::EmittedFragments;
634 switch (F.getKind()) {
635 case MCFragment::FT_Align: {
636 ++stats::EmittedAlignFragments;
637 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
638 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
640 uint64_t Count = FragmentSize / AF.getValueSize();
642 // FIXME: This error shouldn't actually occur (the front end should emit
643 // multiple .align directives to enforce the semantics it wants), but is
644 // severe enough that we want to report it. How to handle this?
645 if (Count * AF.getValueSize() != FragmentSize)
646 report_fatal_error("undefined .align directive, value size '" +
647 Twine(AF.getValueSize()) +
648 "' is not a divisor of padding size '" +
649 Twine(FragmentSize) + "'");
651 // See if we are aligning with nops, and if so do that first to try to fill
652 // the Count bytes. Then if that did not fill any bytes or there are any
653 // bytes left to fill use the Value and ValueSize to fill the rest.
654 // If we are aligning with nops, ask that target to emit the right data.
655 if (AF.hasEmitNops()) {
656 if (!Asm.getBackend().writeNopData(Count, OW))
657 report_fatal_error("unable to write nop sequence of " +
658 Twine(Count) + " bytes");
662 // Otherwise, write out in multiples of the value size.
663 for (uint64_t i = 0; i != Count; ++i) {
664 switch (AF.getValueSize()) {
665 default: llvm_unreachable("Invalid size!");
666 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
667 case 2: OW->Write16(uint16_t(AF.getValue())); break;
668 case 4: OW->Write32(uint32_t(AF.getValue())); break;
669 case 8: OW->Write64(uint64_t(AF.getValue())); break;
675 case MCFragment::FT_Data:
676 ++stats::EmittedDataFragments;
677 writeFragmentContents(F, OW);
680 case MCFragment::FT_Relaxable:
681 ++stats::EmittedRelaxableFragments;
682 writeFragmentContents(F, OW);
685 case MCFragment::FT_CompactEncodedInst:
686 ++stats::EmittedCompactEncodedInstFragments;
687 writeFragmentContents(F, OW);
690 case MCFragment::FT_Fill: {
691 ++stats::EmittedFillFragments;
692 const MCFillFragment &FF = cast<MCFillFragment>(F);
694 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
696 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
697 switch (FF.getValueSize()) {
698 default: llvm_unreachable("Invalid size!");
699 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
700 case 2: OW->Write16(uint16_t(FF.getValue())); break;
701 case 4: OW->Write32(uint32_t(FF.getValue())); break;
702 case 8: OW->Write64(uint64_t(FF.getValue())); break;
708 case MCFragment::FT_LEB: {
709 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
710 OW->WriteBytes(LF.getContents());
714 case MCFragment::FT_Org: {
715 ++stats::EmittedOrgFragments;
716 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
718 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
719 OW->Write8(uint8_t(OF.getValue()));
724 case MCFragment::FT_Dwarf: {
725 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
726 OW->WriteBytes(OF.getContents());
729 case MCFragment::FT_DwarfFrame: {
730 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
731 OW->WriteBytes(CF.getContents());
736 assert(OW->getStream().tell() - Start == FragmentSize &&
737 "The stream should advance by fragment size");
740 void MCAssembler::writeSectionData(const MCSection *Sec,
741 const MCAsmLayout &Layout) const {
742 // Ignore virtual sections.
743 if (Sec->isVirtualSection()) {
744 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
746 // Check that contents are only things legal inside a virtual section.
747 for (MCSectionData::const_iterator it = Sec->begin(), ie = Sec->end();
749 switch (it->getKind()) {
750 default: llvm_unreachable("Invalid fragment in virtual section!");
751 case MCFragment::FT_Data: {
752 // Check that we aren't trying to write a non-zero contents (or fixups)
753 // into a virtual section. This is to support clients which use standard
754 // directives to fill the contents of virtual sections.
755 const MCDataFragment &DF = cast<MCDataFragment>(*it);
756 assert(DF.fixup_begin() == DF.fixup_end() &&
757 "Cannot have fixups in virtual section!");
758 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
759 if (DF.getContents()[i]) {
760 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
761 report_fatal_error("non-zero initializer found in section '" +
762 ELFSec->getSectionName() + "'");
764 report_fatal_error("non-zero initializer found in virtual section");
768 case MCFragment::FT_Align:
769 // Check that we aren't trying to write a non-zero value into a virtual
771 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
772 cast<MCAlignFragment>(it)->getValue() == 0) &&
773 "Invalid align in virtual section!");
775 case MCFragment::FT_Fill:
776 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
777 cast<MCFillFragment>(it)->getValue() == 0) &&
778 "Invalid fill in virtual section!");
786 uint64_t Start = getWriter().getStream().tell();
789 for (MCSectionData::const_iterator it = Sec->begin(), ie = Sec->end();
791 writeFragment(*this, Layout, *it);
793 assert(getWriter().getStream().tell() - Start ==
794 Layout.getSectionAddressSize(Sec));
797 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
799 const MCFixup &Fixup) {
800 // Evaluate the fixup.
803 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
804 MCFixupKindInfo::FKF_IsPCRel;
805 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
806 // The fixup was unresolved, we need a relocation. Inform the object
807 // writer of the relocation, and give it an opportunity to adjust the
808 // fixup value if need be.
809 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
812 return std::make_pair(FixedValue, IsPCRel);
815 void MCAssembler::Finish() {
816 DEBUG_WITH_TYPE("mc-dump", {
817 llvm::errs() << "assembler backend - pre-layout\n--\n";
820 // Create the layout object.
821 MCAsmLayout Layout(*this);
823 // Create dummy fragments and assign section ordinals.
824 unsigned SectionIndex = 0;
825 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
826 // Create dummy fragments to eliminate any empty sections, this simplifies
828 if (it->getFragmentList().empty())
829 new MCDataFragment(&*it);
831 it->setOrdinal(SectionIndex++);
834 // Assign layout order indices to sections and fragments.
835 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
836 MCSection *Sec = Layout.getSectionOrder()[i];
837 Sec->setLayoutOrder(i);
839 unsigned FragmentIndex = 0;
840 for (MCSectionData::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
841 iFrag != iFragEnd; ++iFrag)
842 iFrag->setLayoutOrder(FragmentIndex++);
845 // Layout until everything fits.
846 while (layoutOnce(Layout))
849 DEBUG_WITH_TYPE("mc-dump", {
850 llvm::errs() << "assembler backend - post-relaxation\n--\n";
853 // Finalize the layout, including fragment lowering.
854 finishLayout(Layout);
856 DEBUG_WITH_TYPE("mc-dump", {
857 llvm::errs() << "assembler backend - final-layout\n--\n";
860 uint64_t StartOffset = OS.tell();
862 // Allow the object writer a chance to perform post-layout binding (for
863 // example, to set the index fields in the symbol data).
864 getWriter().ExecutePostLayoutBinding(*this, Layout);
866 // Evaluate and apply the fixups, generating relocation entries as necessary.
867 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
868 for (MCSectionData::iterator it2 = it->begin(),
869 ie2 = it->end(); it2 != ie2; ++it2) {
870 MCEncodedFragmentWithFixups *F =
871 dyn_cast<MCEncodedFragmentWithFixups>(it2);
873 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
874 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
875 MCFixup &Fixup = *it3;
878 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
879 getBackend().applyFixup(Fixup, F->getContents().data(),
880 F->getContents().size(), FixedValue, IsPCRel);
886 // Write the object file.
887 getWriter().WriteObject(*this, Layout);
889 stats::ObjectBytes += OS.tell() - StartOffset;
892 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
893 const MCRelaxableFragment *DF,
894 const MCAsmLayout &Layout) const {
895 // If we cannot resolve the fixup value, it requires relaxation.
898 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
901 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
904 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
905 const MCAsmLayout &Layout) const {
906 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
907 // are intentionally pushing out inst fragments, or because we relaxed a
908 // previous instruction to one that doesn't need relaxation.
909 if (!getBackend().mayNeedRelaxation(F->getInst()))
912 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
913 ie = F->fixup_end(); it != ie; ++it)
914 if (fixupNeedsRelaxation(*it, F, Layout))
920 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
921 MCRelaxableFragment &F) {
922 if (!fragmentNeedsRelaxation(&F, Layout))
925 ++stats::RelaxedInstructions;
927 // FIXME-PERF: We could immediately lower out instructions if we can tell
928 // they are fully resolved, to avoid retesting on later passes.
930 // Relax the fragment.
933 getBackend().relaxInstruction(F.getInst(), Relaxed);
935 // Encode the new instruction.
937 // FIXME-PERF: If it matters, we could let the target do this. It can
938 // probably do so more efficiently in many cases.
939 SmallVector<MCFixup, 4> Fixups;
940 SmallString<256> Code;
941 raw_svector_ostream VecOS(Code);
942 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
945 // Update the fragment.
947 F.getContents() = Code;
948 F.getFixups() = Fixups;
953 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
954 uint64_t OldSize = LF.getContents().size();
956 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
958 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
959 SmallString<8> &Data = LF.getContents();
961 raw_svector_ostream OSE(Data);
963 encodeSLEB128(Value, OSE);
965 encodeULEB128(Value, OSE);
967 return OldSize != LF.getContents().size();
970 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
971 MCDwarfLineAddrFragment &DF) {
972 MCContext &Context = Layout.getAssembler().getContext();
973 uint64_t OldSize = DF.getContents().size();
975 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
976 assert(Abs && "We created a line delta with an invalid expression");
979 LineDelta = DF.getLineDelta();
980 SmallString<8> &Data = DF.getContents();
982 raw_svector_ostream OSE(Data);
983 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
985 return OldSize != Data.size();
988 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
989 MCDwarfCallFrameFragment &DF) {
990 MCContext &Context = Layout.getAssembler().getContext();
991 uint64_t OldSize = DF.getContents().size();
993 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
994 assert(Abs && "We created call frame with an invalid expression");
996 SmallString<8> &Data = DF.getContents();
998 raw_svector_ostream OSE(Data);
999 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1001 return OldSize != Data.size();
1004 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1005 // Holds the first fragment which needed relaxing during this layout. It will
1006 // remain NULL if none were relaxed.
1007 // When a fragment is relaxed, all the fragments following it should get
1008 // invalidated because their offset is going to change.
1009 MCFragment *FirstRelaxedFragment = nullptr;
1011 // Attempt to relax all the fragments in the section.
1012 for (MCSectionData::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1013 // Check if this is a fragment that needs relaxation.
1014 bool RelaxedFrag = false;
1015 switch(I->getKind()) {
1018 case MCFragment::FT_Relaxable:
1019 assert(!getRelaxAll() &&
1020 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1021 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1023 case MCFragment::FT_Dwarf:
1024 RelaxedFrag = relaxDwarfLineAddr(Layout,
1025 *cast<MCDwarfLineAddrFragment>(I));
1027 case MCFragment::FT_DwarfFrame:
1029 relaxDwarfCallFrameFragment(Layout,
1030 *cast<MCDwarfCallFrameFragment>(I));
1032 case MCFragment::FT_LEB:
1033 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1036 if (RelaxedFrag && !FirstRelaxedFragment)
1037 FirstRelaxedFragment = I;
1039 if (FirstRelaxedFragment) {
1040 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1046 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1047 ++stats::RelaxationSteps;
1049 bool WasRelaxed = false;
1050 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1051 MCSection &Sec = *it;
1052 while (layoutSectionOnce(Layout, Sec))
1059 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1060 // The layout is done. Mark every fragment as valid.
1061 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1062 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1066 // Debugging methods
1070 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1071 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1072 << " Value:" << *AF.getValue()
1073 << " Kind:" << AF.getKind() << ">";
1079 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 void MCFragment::dump() {
1081 raw_ostream &OS = llvm::errs();
1084 switch (getKind()) {
1085 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1086 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1087 case MCFragment::FT_CompactEncodedInst:
1088 OS << "MCCompactEncodedInstFragment"; break;
1089 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1090 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1091 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1092 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1093 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1094 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1097 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1098 << " Offset:" << Offset
1099 << " HasInstructions:" << hasInstructions()
1100 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1102 switch (getKind()) {
1103 case MCFragment::FT_Align: {
1104 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1105 if (AF->hasEmitNops())
1106 OS << " (emit nops)";
1108 OS << " Alignment:" << AF->getAlignment()
1109 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1110 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1113 case MCFragment::FT_Data: {
1114 const MCDataFragment *DF = cast<MCDataFragment>(this);
1116 OS << " Contents:[";
1117 const SmallVectorImpl<char> &Contents = DF->getContents();
1118 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1120 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1122 OS << "] (" << Contents.size() << " bytes)";
1124 if (DF->fixup_begin() != DF->fixup_end()) {
1127 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1128 ie = DF->fixup_end(); it != ie; ++it) {
1129 if (it != DF->fixup_begin()) OS << ",\n ";
1136 case MCFragment::FT_CompactEncodedInst: {
1137 const MCCompactEncodedInstFragment *CEIF =
1138 cast<MCCompactEncodedInstFragment>(this);
1140 OS << " Contents:[";
1141 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1142 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1144 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1146 OS << "] (" << Contents.size() << " bytes)";
1149 case MCFragment::FT_Fill: {
1150 const MCFillFragment *FF = cast<MCFillFragment>(this);
1151 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1152 << " Size:" << FF->getSize();
1155 case MCFragment::FT_Relaxable: {
1156 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1159 F->getInst().dump_pretty(OS);
1162 case MCFragment::FT_Org: {
1163 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1165 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1168 case MCFragment::FT_Dwarf: {
1169 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1171 OS << " AddrDelta:" << OF->getAddrDelta()
1172 << " LineDelta:" << OF->getLineDelta();
1175 case MCFragment::FT_DwarfFrame: {
1176 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1178 OS << " AddrDelta:" << CF->getAddrDelta();
1181 case MCFragment::FT_LEB: {
1182 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1184 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1191 void MCSectionData::dump() {
1192 raw_ostream &OS = llvm::errs();
1194 OS << "<MCSectionData";
1195 OS << " Fragments:[\n ";
1196 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1197 if (it != begin()) OS << ",\n ";
1203 void MCSymbolData::dump() const {
1204 raw_ostream &OS = llvm::errs();
1206 OS << "<MCSymbolData"
1207 << " Fragment:" << getFragment();
1209 OS << " Offset:" << getOffset();
1210 OS << " Flags:" << getFlags();
1212 OS << " (common, size:" << getCommonSize()
1213 << " align: " << getCommonAlignment() << ")";
1215 OS << " (external)";
1216 if (isPrivateExtern())
1217 OS << " (private extern)";
1221 void MCAssembler::dump() {
1222 raw_ostream &OS = llvm::errs();
1224 OS << "<MCAssembler\n";
1225 OS << " Sections:[\n ";
1226 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1227 if (it != begin()) OS << ",\n ";
1228 it->getSectionData().dump();
1233 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1234 if (it != symbol_begin()) OS << ",\n ";
1237 OS << ", Index:" << it->getIndex() << ", ";
1238 it->getData().dump();
1245 // anchors for MC*Fragment vtables
1246 void MCEncodedFragment::anchor() { }
1247 void MCEncodedFragmentWithFixups::anchor() { }
1248 void MCDataFragment::anchor() { }
1249 void MCCompactEncodedInstFragment::anchor() { }
1250 void MCRelaxableFragment::anchor() { }
1251 void MCAlignFragment::anchor() { }
1252 void MCFillFragment::anchor() { }
1253 void MCOrgFragment::anchor() { }
1254 void MCLEBFragment::anchor() { }
1255 void MCDwarfLineAddrFragment::anchor() { }
1256 void MCDwarfCallFrameFragment::anchor() { }