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) {}
293 MCSectionData::iterator
294 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
295 if (Subsection == 0 && SubsectionFragmentMap.empty())
298 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
299 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
300 std::make_pair(Subsection, (MCFragment *)nullptr));
301 bool ExactMatch = false;
302 if (MI != SubsectionFragmentMap.end()) {
303 ExactMatch = MI->first == Subsection;
308 if (MI == SubsectionFragmentMap.end())
312 if (!ExactMatch && Subsection != 0) {
313 // The GNU as documentation claims that subsections have an alignment of 4,
314 // although this appears not to be the case.
315 MCFragment *F = new MCDataFragment();
316 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
317 getFragmentList().insert(IP, F);
318 F->setParent(&getSection());
326 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
327 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
329 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
330 OS(OS_), BundleAlignSize(0), RelaxAll(false),
331 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
332 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
335 MCAssembler::~MCAssembler() {
338 void MCAssembler::reset() {
341 IndirectSymbols.clear();
343 LinkerOptions.clear();
348 SubsectionsViaSymbols = false;
350 LOHContainer.reset();
351 VersionMinInfo.Major = 0;
353 // reset objects owned by us
354 getBackend().reset();
355 getEmitter().reset();
357 getLOHContainer().reset();
360 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
361 if (ThumbFuncs.count(Symbol))
364 if (!Symbol->isVariable())
367 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
368 // is not clear if that is a bug or a feature.
369 const MCExpr *Expr = Symbol->getVariableValue();
370 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
374 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
377 const MCSymbol &Sym = Ref->getSymbol();
378 if (!isThumbFunc(&Sym))
381 ThumbFuncs.insert(Symbol); // Cache it.
385 void MCAssembler::addLocalUsedInReloc(const MCSymbol &Sym) {
386 assert(Sym.isTemporary());
387 LocalsUsedInReloc.insert(&Sym);
390 bool MCAssembler::isLocalUsedInReloc(const MCSymbol &Sym) const {
391 assert(Sym.isTemporary());
392 return LocalsUsedInReloc.count(&Sym);
395 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
396 // Non-temporary labels should always be visible to the linker.
397 if (!Symbol.isTemporary())
400 // Absolute temporary labels are never visible.
401 if (!Symbol.isInSection())
404 if (isLocalUsedInReloc(Symbol))
410 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
411 // Linker visible symbols define atoms.
412 if (isSymbolLinkerVisible(S))
415 // Absolute and undefined symbols have no defining atom.
416 if (!S.getData().getFragment())
419 // Non-linker visible symbols in sections which can't be atomized have no
421 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
422 *S.getData().getFragment()->getParent()))
425 // Otherwise, return the atom for the containing fragment.
426 return S.getData().getFragment()->getAtom();
429 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
430 const MCFixup &Fixup, const MCFragment *DF,
431 MCValue &Target, uint64_t &Value) const {
432 ++stats::evaluateFixup;
434 // FIXME: This code has some duplication with RecordRelocation. We should
435 // probably merge the two into a single callback that tries to evaluate a
436 // fixup and records a relocation if one is needed.
437 const MCExpr *Expr = Fixup.getValue();
438 if (!Expr->EvaluateAsRelocatable(Target, &Layout, &Fixup))
439 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
441 bool IsPCRel = Backend.getFixupKindInfo(
442 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
446 if (Target.getSymB()) {
448 } else if (!Target.getSymA()) {
451 const MCSymbolRefExpr *A = Target.getSymA();
452 const MCSymbol &SA = A->getSymbol();
453 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
456 IsResolved = getWriter().IsSymbolRefDifferenceFullyResolvedImpl(
457 *this, SA, *DF, false, true);
461 IsResolved = Target.isAbsolute();
464 Value = Target.getConstant();
466 if (const MCSymbolRefExpr *A = Target.getSymA()) {
467 const MCSymbol &Sym = A->getSymbol();
469 Value += Layout.getSymbolOffset(Sym);
471 if (const MCSymbolRefExpr *B = Target.getSymB()) {
472 const MCSymbol &Sym = B->getSymbol();
474 Value -= Layout.getSymbolOffset(Sym);
478 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
479 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
480 assert((ShouldAlignPC ? IsPCRel : true) &&
481 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
484 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
486 // A number of ARM fixups in Thumb mode require that the effective PC
487 // address be determined as the 32-bit aligned version of the actual offset.
488 if (ShouldAlignPC) Offset &= ~0x3;
492 // Let the backend adjust the fixup value if necessary, including whether
493 // we need a relocation.
494 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
500 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
501 const MCFragment &F) const {
502 switch (F.getKind()) {
503 case MCFragment::FT_Data:
504 case MCFragment::FT_Relaxable:
505 case MCFragment::FT_CompactEncodedInst:
506 return cast<MCEncodedFragment>(F).getContents().size();
507 case MCFragment::FT_Fill:
508 return cast<MCFillFragment>(F).getSize();
510 case MCFragment::FT_LEB:
511 return cast<MCLEBFragment>(F).getContents().size();
513 case MCFragment::FT_Align: {
514 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
515 unsigned Offset = Layout.getFragmentOffset(&AF);
516 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
517 // If we are padding with nops, force the padding to be larger than the
519 if (Size > 0 && AF.hasEmitNops()) {
520 while (Size % getBackend().getMinimumNopSize())
521 Size += AF.getAlignment();
523 if (Size > AF.getMaxBytesToEmit())
528 case MCFragment::FT_Org: {
529 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
530 int64_t TargetLocation;
531 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
532 report_fatal_error("expected assembly-time absolute expression");
534 // FIXME: We need a way to communicate this error.
535 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
536 int64_t Size = TargetLocation - FragmentOffset;
537 if (Size < 0 || Size >= 0x40000000)
538 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
539 "' (at offset '" + Twine(FragmentOffset) + "')");
543 case MCFragment::FT_Dwarf:
544 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
545 case MCFragment::FT_DwarfFrame:
546 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
549 llvm_unreachable("invalid fragment kind");
552 void MCAsmLayout::layoutFragment(MCFragment *F) {
553 MCFragment *Prev = F->getPrevNode();
555 // We should never try to recompute something which is valid.
556 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
557 // We should never try to compute the fragment layout if its predecessor
559 assert((!Prev || isFragmentValid(Prev)) &&
560 "Attempt to compute fragment before its predecessor!");
562 ++stats::FragmentLayouts;
564 // Compute fragment offset and size.
566 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
569 LastValidFragment[F->getParent()] = F;
571 // If bundling is enabled and this fragment has instructions in it, it has to
572 // obey the bundling restrictions. With padding, we'll have:
577 // -------------------------------------
578 // Prev |##########| F |
579 // -------------------------------------
584 // The fragment's offset will point to after the padding, and its computed
585 // size won't include the padding.
587 // When the -mc-relax-all flag is used, we optimize bundling by writting the
588 // bundle padding directly into fragments when the instructions are emitted
589 // inside the streamer.
591 if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
592 F->hasInstructions()) {
593 assert(isa<MCEncodedFragment>(F) &&
594 "Only MCEncodedFragment implementations have instructions");
595 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
597 if (FSize > Assembler.getBundleAlignSize())
598 report_fatal_error("Fragment can't be larger than a bundle size");
600 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
602 if (RequiredBundlePadding > UINT8_MAX)
603 report_fatal_error("Padding cannot exceed 255 bytes");
604 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
605 F->Offset += RequiredBundlePadding;
609 /// \brief Write the contents of a fragment to the given object writer. Expects
610 /// a MCEncodedFragment.
611 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
612 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
613 OW->WriteBytes(EF.getContents());
616 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
617 MCObjectWriter *OW) const {
618 // Should NOP padding be written out before this fragment?
619 unsigned BundlePadding = F.getBundlePadding();
620 if (BundlePadding > 0) {
621 assert(isBundlingEnabled() &&
622 "Writing bundle padding with disabled bundling");
623 assert(F.hasInstructions() &&
624 "Writing bundle padding for a fragment without instructions");
626 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
627 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
628 // If the padding itself crosses a bundle boundary, it must be emitted
629 // in 2 pieces, since even nop instructions must not cross boundaries.
630 // v--------------v <- BundleAlignSize
631 // v---------v <- BundlePadding
632 // ----------------------------
633 // | Prev |####|####| F |
634 // ----------------------------
635 // ^-------------------^ <- TotalLength
636 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
637 if (!getBackend().writeNopData(DistanceToBoundary, OW))
638 report_fatal_error("unable to write NOP sequence of " +
639 Twine(DistanceToBoundary) + " bytes");
640 BundlePadding -= DistanceToBoundary;
642 if (!getBackend().writeNopData(BundlePadding, OW))
643 report_fatal_error("unable to write NOP sequence of " +
644 Twine(BundlePadding) + " bytes");
648 /// \brief Write the fragment \p F to the output file.
649 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
650 const MCFragment &F) {
651 MCObjectWriter *OW = &Asm.getWriter();
653 // FIXME: Embed in fragments instead?
654 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
656 Asm.writeFragmentPadding(F, FragmentSize, OW);
658 // This variable (and its dummy usage) is to participate in the assert at
659 // the end of the function.
660 uint64_t Start = OW->getStream().tell();
663 ++stats::EmittedFragments;
665 switch (F.getKind()) {
666 case MCFragment::FT_Align: {
667 ++stats::EmittedAlignFragments;
668 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
669 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
671 uint64_t Count = FragmentSize / AF.getValueSize();
673 // FIXME: This error shouldn't actually occur (the front end should emit
674 // multiple .align directives to enforce the semantics it wants), but is
675 // severe enough that we want to report it. How to handle this?
676 if (Count * AF.getValueSize() != FragmentSize)
677 report_fatal_error("undefined .align directive, value size '" +
678 Twine(AF.getValueSize()) +
679 "' is not a divisor of padding size '" +
680 Twine(FragmentSize) + "'");
682 // See if we are aligning with nops, and if so do that first to try to fill
683 // the Count bytes. Then if that did not fill any bytes or there are any
684 // bytes left to fill use the Value and ValueSize to fill the rest.
685 // If we are aligning with nops, ask that target to emit the right data.
686 if (AF.hasEmitNops()) {
687 if (!Asm.getBackend().writeNopData(Count, OW))
688 report_fatal_error("unable to write nop sequence of " +
689 Twine(Count) + " bytes");
693 // Otherwise, write out in multiples of the value size.
694 for (uint64_t i = 0; i != Count; ++i) {
695 switch (AF.getValueSize()) {
696 default: llvm_unreachable("Invalid size!");
697 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
698 case 2: OW->Write16(uint16_t(AF.getValue())); break;
699 case 4: OW->Write32(uint32_t(AF.getValue())); break;
700 case 8: OW->Write64(uint64_t(AF.getValue())); break;
706 case MCFragment::FT_Data:
707 ++stats::EmittedDataFragments;
708 writeFragmentContents(F, OW);
711 case MCFragment::FT_Relaxable:
712 ++stats::EmittedRelaxableFragments;
713 writeFragmentContents(F, OW);
716 case MCFragment::FT_CompactEncodedInst:
717 ++stats::EmittedCompactEncodedInstFragments;
718 writeFragmentContents(F, OW);
721 case MCFragment::FT_Fill: {
722 ++stats::EmittedFillFragments;
723 const MCFillFragment &FF = cast<MCFillFragment>(F);
725 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
727 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
728 switch (FF.getValueSize()) {
729 default: llvm_unreachable("Invalid size!");
730 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
731 case 2: OW->Write16(uint16_t(FF.getValue())); break;
732 case 4: OW->Write32(uint32_t(FF.getValue())); break;
733 case 8: OW->Write64(uint64_t(FF.getValue())); break;
739 case MCFragment::FT_LEB: {
740 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
741 OW->WriteBytes(LF.getContents());
745 case MCFragment::FT_Org: {
746 ++stats::EmittedOrgFragments;
747 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
749 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
750 OW->Write8(uint8_t(OF.getValue()));
755 case MCFragment::FT_Dwarf: {
756 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
757 OW->WriteBytes(OF.getContents());
760 case MCFragment::FT_DwarfFrame: {
761 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
762 OW->WriteBytes(CF.getContents());
767 assert(OW->getStream().tell() - Start == FragmentSize &&
768 "The stream should advance by fragment size");
771 void MCAssembler::writeSectionData(const MCSection *Sec,
772 const MCAsmLayout &Layout) const {
773 // Ignore virtual sections.
774 if (Sec->isVirtualSection()) {
775 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
777 // Check that contents are only things legal inside a virtual section.
778 for (MCSectionData::const_iterator it = Sec->begin(), ie = Sec->end();
780 switch (it->getKind()) {
781 default: llvm_unreachable("Invalid fragment in virtual section!");
782 case MCFragment::FT_Data: {
783 // Check that we aren't trying to write a non-zero contents (or fixups)
784 // into a virtual section. This is to support clients which use standard
785 // directives to fill the contents of virtual sections.
786 const MCDataFragment &DF = cast<MCDataFragment>(*it);
787 assert(DF.fixup_begin() == DF.fixup_end() &&
788 "Cannot have fixups in virtual section!");
789 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
790 if (DF.getContents()[i]) {
791 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
792 report_fatal_error("non-zero initializer found in section '" +
793 ELFSec->getSectionName() + "'");
795 report_fatal_error("non-zero initializer found in virtual section");
799 case MCFragment::FT_Align:
800 // Check that we aren't trying to write a non-zero value into a virtual
802 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
803 cast<MCAlignFragment>(it)->getValue() == 0) &&
804 "Invalid align in virtual section!");
806 case MCFragment::FT_Fill:
807 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
808 cast<MCFillFragment>(it)->getValue() == 0) &&
809 "Invalid fill in virtual section!");
817 uint64_t Start = getWriter().getStream().tell();
820 for (MCSectionData::const_iterator it = Sec->begin(), ie = Sec->end();
822 writeFragment(*this, Layout, *it);
824 assert(getWriter().getStream().tell() - Start ==
825 Layout.getSectionAddressSize(Sec));
828 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
830 const MCFixup &Fixup) {
831 // Evaluate the fixup.
834 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
835 MCFixupKindInfo::FKF_IsPCRel;
836 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
837 // The fixup was unresolved, we need a relocation. Inform the object
838 // writer of the relocation, and give it an opportunity to adjust the
839 // fixup value if need be.
840 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
843 return std::make_pair(FixedValue, IsPCRel);
846 void MCAssembler::Finish() {
847 DEBUG_WITH_TYPE("mc-dump", {
848 llvm::errs() << "assembler backend - pre-layout\n--\n";
851 // Create the layout object.
852 MCAsmLayout Layout(*this);
854 // Create dummy fragments and assign section ordinals.
855 unsigned SectionIndex = 0;
856 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
857 // Create dummy fragments to eliminate any empty sections, this simplifies
859 if (it->getFragmentList().empty())
860 new MCDataFragment(&*it);
862 it->setOrdinal(SectionIndex++);
865 // Assign layout order indices to sections and fragments.
866 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
867 MCSection *Sec = Layout.getSectionOrder()[i];
868 Sec->setLayoutOrder(i);
870 unsigned FragmentIndex = 0;
871 for (MCSectionData::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
872 iFrag != iFragEnd; ++iFrag)
873 iFrag->setLayoutOrder(FragmentIndex++);
876 // Layout until everything fits.
877 while (layoutOnce(Layout))
880 DEBUG_WITH_TYPE("mc-dump", {
881 llvm::errs() << "assembler backend - post-relaxation\n--\n";
884 // Finalize the layout, including fragment lowering.
885 finishLayout(Layout);
887 DEBUG_WITH_TYPE("mc-dump", {
888 llvm::errs() << "assembler backend - final-layout\n--\n";
891 uint64_t StartOffset = OS.tell();
893 // Allow the object writer a chance to perform post-layout binding (for
894 // example, to set the index fields in the symbol data).
895 getWriter().ExecutePostLayoutBinding(*this, Layout);
897 // Evaluate and apply the fixups, generating relocation entries as necessary.
898 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
899 for (MCSectionData::iterator it2 = it->begin(),
900 ie2 = it->end(); it2 != ie2; ++it2) {
901 MCEncodedFragmentWithFixups *F =
902 dyn_cast<MCEncodedFragmentWithFixups>(it2);
904 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
905 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
906 MCFixup &Fixup = *it3;
909 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
910 getBackend().applyFixup(Fixup, F->getContents().data(),
911 F->getContents().size(), FixedValue, IsPCRel);
917 // Write the object file.
918 getWriter().WriteObject(*this, Layout);
920 stats::ObjectBytes += OS.tell() - StartOffset;
923 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
924 const MCRelaxableFragment *DF,
925 const MCAsmLayout &Layout) const {
926 // If we cannot resolve the fixup value, it requires relaxation.
929 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
932 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
935 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
936 const MCAsmLayout &Layout) const {
937 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
938 // are intentionally pushing out inst fragments, or because we relaxed a
939 // previous instruction to one that doesn't need relaxation.
940 if (!getBackend().mayNeedRelaxation(F->getInst()))
943 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
944 ie = F->fixup_end(); it != ie; ++it)
945 if (fixupNeedsRelaxation(*it, F, Layout))
951 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
952 MCRelaxableFragment &F) {
953 if (!fragmentNeedsRelaxation(&F, Layout))
956 ++stats::RelaxedInstructions;
958 // FIXME-PERF: We could immediately lower out instructions if we can tell
959 // they are fully resolved, to avoid retesting on later passes.
961 // Relax the fragment.
964 getBackend().relaxInstruction(F.getInst(), Relaxed);
966 // Encode the new instruction.
968 // FIXME-PERF: If it matters, we could let the target do this. It can
969 // probably do so more efficiently in many cases.
970 SmallVector<MCFixup, 4> Fixups;
971 SmallString<256> Code;
972 raw_svector_ostream VecOS(Code);
973 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
976 // Update the fragment.
978 F.getContents() = Code;
979 F.getFixups() = Fixups;
984 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
985 uint64_t OldSize = LF.getContents().size();
987 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
989 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
990 SmallString<8> &Data = LF.getContents();
992 raw_svector_ostream OSE(Data);
994 encodeSLEB128(Value, OSE);
996 encodeULEB128(Value, OSE);
998 return OldSize != LF.getContents().size();
1001 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1002 MCDwarfLineAddrFragment &DF) {
1003 MCContext &Context = Layout.getAssembler().getContext();
1004 uint64_t OldSize = DF.getContents().size();
1006 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1007 assert(Abs && "We created a line delta with an invalid expression");
1010 LineDelta = DF.getLineDelta();
1011 SmallString<8> &Data = DF.getContents();
1013 raw_svector_ostream OSE(Data);
1014 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
1016 return OldSize != Data.size();
1019 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1020 MCDwarfCallFrameFragment &DF) {
1021 MCContext &Context = Layout.getAssembler().getContext();
1022 uint64_t OldSize = DF.getContents().size();
1024 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1025 assert(Abs && "We created call frame with an invalid expression");
1027 SmallString<8> &Data = DF.getContents();
1029 raw_svector_ostream OSE(Data);
1030 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1032 return OldSize != Data.size();
1035 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1036 // Holds the first fragment which needed relaxing during this layout. It will
1037 // remain NULL if none were relaxed.
1038 // When a fragment is relaxed, all the fragments following it should get
1039 // invalidated because their offset is going to change.
1040 MCFragment *FirstRelaxedFragment = nullptr;
1042 // Attempt to relax all the fragments in the section.
1043 for (MCSectionData::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1044 // Check if this is a fragment that needs relaxation.
1045 bool RelaxedFrag = false;
1046 switch(I->getKind()) {
1049 case MCFragment::FT_Relaxable:
1050 assert(!getRelaxAll() &&
1051 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1052 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1054 case MCFragment::FT_Dwarf:
1055 RelaxedFrag = relaxDwarfLineAddr(Layout,
1056 *cast<MCDwarfLineAddrFragment>(I));
1058 case MCFragment::FT_DwarfFrame:
1060 relaxDwarfCallFrameFragment(Layout,
1061 *cast<MCDwarfCallFrameFragment>(I));
1063 case MCFragment::FT_LEB:
1064 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1067 if (RelaxedFrag && !FirstRelaxedFragment)
1068 FirstRelaxedFragment = I;
1070 if (FirstRelaxedFragment) {
1071 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1077 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1078 ++stats::RelaxationSteps;
1080 bool WasRelaxed = false;
1081 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1082 MCSection &Sec = *it;
1083 while (layoutSectionOnce(Layout, Sec))
1090 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1091 // The layout is done. Mark every fragment as valid.
1092 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1093 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1097 // Debugging methods
1101 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1102 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1103 << " Value:" << *AF.getValue()
1104 << " Kind:" << AF.getKind() << ">";
1110 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1111 void MCFragment::dump() {
1112 raw_ostream &OS = llvm::errs();
1115 switch (getKind()) {
1116 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1117 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1118 case MCFragment::FT_CompactEncodedInst:
1119 OS << "MCCompactEncodedInstFragment"; break;
1120 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1121 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1122 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1123 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1124 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1125 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1128 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1129 << " Offset:" << Offset
1130 << " HasInstructions:" << hasInstructions()
1131 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1133 switch (getKind()) {
1134 case MCFragment::FT_Align: {
1135 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1136 if (AF->hasEmitNops())
1137 OS << " (emit nops)";
1139 OS << " Alignment:" << AF->getAlignment()
1140 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1141 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1144 case MCFragment::FT_Data: {
1145 const MCDataFragment *DF = cast<MCDataFragment>(this);
1147 OS << " Contents:[";
1148 const SmallVectorImpl<char> &Contents = DF->getContents();
1149 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1151 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1153 OS << "] (" << Contents.size() << " bytes)";
1155 if (DF->fixup_begin() != DF->fixup_end()) {
1158 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1159 ie = DF->fixup_end(); it != ie; ++it) {
1160 if (it != DF->fixup_begin()) OS << ",\n ";
1167 case MCFragment::FT_CompactEncodedInst: {
1168 const MCCompactEncodedInstFragment *CEIF =
1169 cast<MCCompactEncodedInstFragment>(this);
1171 OS << " Contents:[";
1172 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1173 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1175 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1177 OS << "] (" << Contents.size() << " bytes)";
1180 case MCFragment::FT_Fill: {
1181 const MCFillFragment *FF = cast<MCFillFragment>(this);
1182 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1183 << " Size:" << FF->getSize();
1186 case MCFragment::FT_Relaxable: {
1187 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1190 F->getInst().dump_pretty(OS);
1193 case MCFragment::FT_Org: {
1194 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1196 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1199 case MCFragment::FT_Dwarf: {
1200 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1202 OS << " AddrDelta:" << OF->getAddrDelta()
1203 << " LineDelta:" << OF->getLineDelta();
1206 case MCFragment::FT_DwarfFrame: {
1207 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1209 OS << " AddrDelta:" << CF->getAddrDelta();
1212 case MCFragment::FT_LEB: {
1213 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1215 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1222 void MCSectionData::dump() {
1223 raw_ostream &OS = llvm::errs();
1225 OS << "<MCSectionData";
1226 OS << " Fragments:[\n ";
1227 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1228 if (it != begin()) OS << ",\n ";
1234 void MCSymbolData::dump() const {
1235 raw_ostream &OS = llvm::errs();
1237 OS << "<MCSymbolData"
1238 << " Fragment:" << getFragment();
1240 OS << " Offset:" << getOffset();
1241 OS << " Flags:" << getFlags();
1243 OS << " (common, size:" << getCommonSize()
1244 << " align: " << getCommonAlignment() << ")";
1246 OS << " (external)";
1247 if (isPrivateExtern())
1248 OS << " (private extern)";
1252 void MCAssembler::dump() {
1253 raw_ostream &OS = llvm::errs();
1255 OS << "<MCAssembler\n";
1256 OS << " Sections:[\n ";
1257 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1258 if (it != begin()) OS << ",\n ";
1259 it->getSectionData().dump();
1264 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1265 if (it != symbol_begin()) OS << ",\n ";
1268 OS << ", Index:" << it->getIndex() << ", ";
1269 it->getData().dump();
1276 // anchors for MC*Fragment vtables
1277 void MCEncodedFragment::anchor() { }
1278 void MCEncodedFragmentWithFixups::anchor() { }
1279 void MCDataFragment::anchor() { }
1280 void MCCompactEncodedInstFragment::anchor() { }
1281 void MCRelaxableFragment::anchor() { }
1282 void MCAlignFragment::anchor() { }
1283 void MCFillFragment::anchor() { }
1284 void MCOrgFragment::anchor() { }
1285 void MCLEBFragment::anchor() { }
1286 void MCDwarfLineAddrFragment::anchor() { }
1287 void MCDwarfCallFrameFragment::anchor() { }