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/MCAsmLayout.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCDwarf.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCValue.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LEB128.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
33 #define DEBUG_TYPE "assembler"
37 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
38 STATISTIC(EmittedRelaxableFragments,
39 "Number of emitted assembler fragments - relaxable");
40 STATISTIC(EmittedDataFragments,
41 "Number of emitted assembler fragments - data");
42 STATISTIC(EmittedCompactEncodedInstFragments,
43 "Number of emitted assembler fragments - compact encoded inst");
44 STATISTIC(EmittedAlignFragments,
45 "Number of emitted assembler fragments - align");
46 STATISTIC(EmittedFillFragments,
47 "Number of emitted assembler fragments - fill");
48 STATISTIC(EmittedOrgFragments,
49 "Number of emitted assembler fragments - org");
50 STATISTIC(evaluateFixup, "Number of evaluated fixups");
51 STATISTIC(FragmentLayouts, "Number of fragment layouts");
52 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
53 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
54 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
58 // FIXME FIXME FIXME: There are number of places in this file where we convert
59 // what is a 64-bit assembler value used for computation into a value in the
60 // object file, which may truncate it. We should detect that truncation where
61 // invalid and report errors back.
65 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
66 : Assembler(Asm), LastValidFragment()
68 // Compute the section layout order. Virtual sections must go last.
69 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
70 if (!it->getSection().isVirtualSection())
71 SectionOrder.push_back(&*it);
72 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
73 if (it->getSection().isVirtualSection())
74 SectionOrder.push_back(&*it);
77 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
78 const MCSectionData &SD = *F->getParent();
79 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
82 assert(LastValid->getParent() == F->getParent());
83 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
86 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
87 // If this fragment wasn't already valid, we don't need to do anything.
88 if (!isFragmentValid(F))
91 // Otherwise, reset the last valid fragment to the previous fragment
92 // (if this is the first fragment, it will be NULL).
93 const MCSectionData &SD = *F->getParent();
94 LastValidFragment[&SD] = F->getPrevNode();
97 void MCAsmLayout::ensureValid(const MCFragment *F) const {
98 MCSectionData &SD = *F->getParent();
100 MCFragment *Cur = LastValidFragment[&SD];
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 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
121 const MCSymbol &S = SD->getSymbol();
123 // If this is a variable, then recursively evaluate now.
124 if (S.isVariable()) {
126 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, this))
127 report_fatal_error("unable to evaluate offset for variable '" +
130 // Verify that any used symbols are defined.
131 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
132 report_fatal_error("unable to evaluate offset to undefined symbol '" +
133 Target.getSymA()->getSymbol().getName() + "'");
134 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
135 report_fatal_error("unable to evaluate offset to undefined symbol '" +
136 Target.getSymB()->getSymbol().getName() + "'");
138 uint64_t Offset = Target.getConstant();
139 if (Target.getSymA())
140 Offset += getSymbolOffset(&Assembler.getSymbolData(
141 Target.getSymA()->getSymbol()));
142 if (Target.getSymB())
143 Offset -= getSymbolOffset(&Assembler.getSymbolData(
144 Target.getSymB()->getSymbol()));
148 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
149 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
152 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
153 // The size is the last fragment's end offset.
154 const MCFragment &F = SD->getFragmentList().back();
155 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
158 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
159 // Virtual sections have no file size.
160 if (SD->getSection().isVirtualSection())
163 // Otherwise, the file size is the same as the address space size.
164 return getSectionAddressSize(SD);
167 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
168 uint64_t FOffset, uint64_t FSize) {
169 uint64_t BundleSize = Assembler.getBundleAlignSize();
170 assert(BundleSize > 0 &&
171 "computeBundlePadding should only be called if bundling is enabled");
172 uint64_t BundleMask = BundleSize - 1;
173 uint64_t OffsetInBundle = FOffset & BundleMask;
174 uint64_t EndOfFragment = OffsetInBundle + FSize;
176 // There are two kinds of bundling restrictions:
178 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
179 // *end* on a bundle boundary.
180 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
181 // would, add padding until the end of the bundle so that the fragment
182 // will start in a new one.
183 if (F->alignToBundleEnd()) {
184 // Three possibilities here:
186 // A) The fragment just happens to end at a bundle boundary, so we're good.
187 // B) The fragment ends before the current bundle boundary: pad it just
188 // enough to reach the boundary.
189 // C) The fragment ends after the current bundle boundary: pad it until it
190 // reaches the end of the next bundle boundary.
192 // Note: this code could be made shorter with some modulo trickery, but it's
193 // intentionally kept in its more explicit form for simplicity.
194 if (EndOfFragment == BundleSize)
196 else if (EndOfFragment < BundleSize)
197 return BundleSize - EndOfFragment;
198 else { // EndOfFragment > BundleSize
199 return 2 * BundleSize - EndOfFragment;
201 } else if (EndOfFragment > BundleSize)
202 return BundleSize - OffsetInBundle;
209 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
212 MCFragment::~MCFragment() {
215 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
216 : Kind(_Kind), Parent(_Parent), Atom(nullptr), Offset(~UINT64_C(0))
219 Parent->getFragmentList().push_back(this);
224 MCEncodedFragment::~MCEncodedFragment() {
229 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
234 MCSectionData::MCSectionData() : Section(nullptr) {}
236 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
237 : Section(&_Section),
238 Ordinal(~UINT32_C(0)),
240 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
241 HasInstructions(false)
244 A->getSectionList().push_back(this);
247 MCSectionData::iterator
248 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
249 if (Subsection == 0 && SubsectionFragmentMap.empty())
252 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
253 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
254 std::make_pair(Subsection, (MCFragment *)nullptr));
255 bool ExactMatch = false;
256 if (MI != SubsectionFragmentMap.end()) {
257 ExactMatch = MI->first == Subsection;
262 if (MI == SubsectionFragmentMap.end())
266 if (!ExactMatch && Subsection != 0) {
267 // The GNU as documentation claims that subsections have an alignment of 4,
268 // although this appears not to be the case.
269 MCFragment *F = new MCDataFragment();
270 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
271 getFragmentList().insert(IP, F);
279 MCSymbolData::MCSymbolData() : Symbol(nullptr) {}
281 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
282 uint64_t _Offset, MCAssembler *A)
283 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
284 IsExternal(false), IsPrivateExtern(false),
285 CommonSize(0), SymbolSize(nullptr), CommonAlign(0),
289 A->getSymbolList().push_back(this);
294 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
295 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
297 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
298 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
299 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
300 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
303 MCAssembler::~MCAssembler() {
306 void MCAssembler::reset() {
311 IndirectSymbols.clear();
316 SubsectionsViaSymbols = false;
319 // reset objects owned by us
320 getBackend().reset();
321 getEmitter().reset();
323 getLOHContainer().reset();
326 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
327 // Non-temporary labels should always be visible to the linker.
328 if (!Symbol.isTemporary())
331 // Absolute temporary labels are never visible.
332 if (!Symbol.isInSection())
335 // Otherwise, check if the section requires symbols even for temporary labels.
336 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
339 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
340 // Linker visible symbols define atoms.
341 if (isSymbolLinkerVisible(SD->getSymbol()))
344 // Absolute and undefined symbols have no defining atom.
345 if (!SD->getFragment())
348 // Non-linker visible symbols in sections which can't be atomized have no
350 if (!getBackend().isSectionAtomizable(
351 SD->getFragment()->getParent()->getSection()))
354 // Otherwise, return the atom for the containing fragment.
355 return SD->getFragment()->getAtom();
358 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
359 const MCFixup &Fixup, const MCFragment *DF,
360 MCValue &Target, uint64_t &Value) const {
361 ++stats::evaluateFixup;
363 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
364 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
366 bool IsPCRel = Backend.getFixupKindInfo(
367 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
371 if (Target.getSymB()) {
373 } else if (!Target.getSymA()) {
376 const MCSymbolRefExpr *A = Target.getSymA();
377 const MCSymbol &SA = A->getSymbol();
378 if (A->getKind() != MCSymbolRefExpr::VK_None ||
379 SA.AliasedSymbol().isUndefined()) {
382 const MCSymbolData &DataA = getSymbolData(SA);
384 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
389 IsResolved = Target.isAbsolute();
392 Value = Target.getConstant();
394 if (const MCSymbolRefExpr *A = Target.getSymA()) {
395 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
397 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
399 if (const MCSymbolRefExpr *B = Target.getSymB()) {
400 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
402 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
406 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
407 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
408 assert((ShouldAlignPC ? IsPCRel : true) &&
409 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
412 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
414 // A number of ARM fixups in Thumb mode require that the effective PC
415 // address be determined as the 32-bit aligned version of the actual offset.
416 if (ShouldAlignPC) Offset &= ~0x3;
420 // Let the backend adjust the fixup value if necessary, including whether
421 // we need a relocation.
422 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
428 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
429 const MCFragment &F) const {
430 switch (F.getKind()) {
431 case MCFragment::FT_Data:
432 case MCFragment::FT_Relaxable:
433 case MCFragment::FT_CompactEncodedInst:
434 return cast<MCEncodedFragment>(F).getContents().size();
435 case MCFragment::FT_Fill:
436 return cast<MCFillFragment>(F).getSize();
438 case MCFragment::FT_LEB:
439 return cast<MCLEBFragment>(F).getContents().size();
441 case MCFragment::FT_Align: {
442 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
443 unsigned Offset = Layout.getFragmentOffset(&AF);
444 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
445 // If we are padding with nops, force the padding to be larger than the
447 if (Size > 0 && AF.hasEmitNops()) {
448 while (Size % getBackend().getMinimumNopSize())
449 Size += AF.getAlignment();
451 if (Size > AF.getMaxBytesToEmit())
456 case MCFragment::FT_Org: {
457 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
458 int64_t TargetLocation;
459 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
460 report_fatal_error("expected assembly-time absolute expression");
462 // FIXME: We need a way to communicate this error.
463 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
464 int64_t Size = TargetLocation - FragmentOffset;
465 if (Size < 0 || Size >= 0x40000000)
466 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
467 "' (at offset '" + Twine(FragmentOffset) + "')");
471 case MCFragment::FT_Dwarf:
472 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
473 case MCFragment::FT_DwarfFrame:
474 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
477 llvm_unreachable("invalid fragment kind");
480 void MCAsmLayout::layoutFragment(MCFragment *F) {
481 MCFragment *Prev = F->getPrevNode();
483 // We should never try to recompute something which is valid.
484 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
485 // We should never try to compute the fragment layout if its predecessor
487 assert((!Prev || isFragmentValid(Prev)) &&
488 "Attempt to compute fragment before its predecessor!");
490 ++stats::FragmentLayouts;
492 // Compute fragment offset and size.
494 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
497 LastValidFragment[F->getParent()] = F;
499 // If bundling is enabled and this fragment has instructions in it, it has to
500 // obey the bundling restrictions. With padding, we'll have:
505 // -------------------------------------
506 // Prev |##########| F |
507 // -------------------------------------
512 // The fragment's offset will point to after the padding, and its computed
513 // size won't include the padding.
515 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
516 assert(isa<MCEncodedFragment>(F) &&
517 "Only MCEncodedFragment implementations have instructions");
518 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
520 if (FSize > Assembler.getBundleAlignSize())
521 report_fatal_error("Fragment can't be larger than a bundle size");
523 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
524 if (RequiredBundlePadding > UINT8_MAX)
525 report_fatal_error("Padding cannot exceed 255 bytes");
526 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
527 F->Offset += RequiredBundlePadding;
531 /// \brief Write the contents of a fragment to the given object writer. Expects
532 /// a MCEncodedFragment.
533 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
534 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
535 OW->WriteBytes(EF.getContents());
538 /// \brief Write the fragment \p F to the output file.
539 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
540 const MCFragment &F) {
541 MCObjectWriter *OW = &Asm.getWriter();
543 // FIXME: Embed in fragments instead?
544 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
546 // Should NOP padding be written out before this fragment?
547 unsigned BundlePadding = F.getBundlePadding();
548 if (BundlePadding > 0) {
549 assert(Asm.isBundlingEnabled() &&
550 "Writing bundle padding with disabled bundling");
551 assert(F.hasInstructions() &&
552 "Writing bundle padding for a fragment without instructions");
554 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
555 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
556 // If the padding itself crosses a bundle boundary, it must be emitted
557 // in 2 pieces, since even nop instructions must not cross boundaries.
558 // v--------------v <- BundleAlignSize
559 // v---------v <- BundlePadding
560 // ----------------------------
561 // | Prev |####|####| F |
562 // ----------------------------
563 // ^-------------------^ <- TotalLength
564 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
565 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
566 report_fatal_error("unable to write NOP sequence of " +
567 Twine(DistanceToBoundary) + " bytes");
568 BundlePadding -= DistanceToBoundary;
570 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
571 report_fatal_error("unable to write NOP sequence of " +
572 Twine(BundlePadding) + " bytes");
575 // This variable (and its dummy usage) is to participate in the assert at
576 // the end of the function.
577 uint64_t Start = OW->getStream().tell();
580 ++stats::EmittedFragments;
582 switch (F.getKind()) {
583 case MCFragment::FT_Align: {
584 ++stats::EmittedAlignFragments;
585 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
586 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
588 uint64_t Count = FragmentSize / AF.getValueSize();
590 // FIXME: This error shouldn't actually occur (the front end should emit
591 // multiple .align directives to enforce the semantics it wants), but is
592 // severe enough that we want to report it. How to handle this?
593 if (Count * AF.getValueSize() != FragmentSize)
594 report_fatal_error("undefined .align directive, value size '" +
595 Twine(AF.getValueSize()) +
596 "' is not a divisor of padding size '" +
597 Twine(FragmentSize) + "'");
599 // See if we are aligning with nops, and if so do that first to try to fill
600 // the Count bytes. Then if that did not fill any bytes or there are any
601 // bytes left to fill use the Value and ValueSize to fill the rest.
602 // If we are aligning with nops, ask that target to emit the right data.
603 if (AF.hasEmitNops()) {
604 if (!Asm.getBackend().writeNopData(Count, OW))
605 report_fatal_error("unable to write nop sequence of " +
606 Twine(Count) + " bytes");
610 // Otherwise, write out in multiples of the value size.
611 for (uint64_t i = 0; i != Count; ++i) {
612 switch (AF.getValueSize()) {
613 default: llvm_unreachable("Invalid size!");
614 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
615 case 2: OW->Write16(uint16_t(AF.getValue())); break;
616 case 4: OW->Write32(uint32_t(AF.getValue())); break;
617 case 8: OW->Write64(uint64_t(AF.getValue())); break;
623 case MCFragment::FT_Data:
624 ++stats::EmittedDataFragments;
625 writeFragmentContents(F, OW);
628 case MCFragment::FT_Relaxable:
629 ++stats::EmittedRelaxableFragments;
630 writeFragmentContents(F, OW);
633 case MCFragment::FT_CompactEncodedInst:
634 ++stats::EmittedCompactEncodedInstFragments;
635 writeFragmentContents(F, OW);
638 case MCFragment::FT_Fill: {
639 ++stats::EmittedFillFragments;
640 const MCFillFragment &FF = cast<MCFillFragment>(F);
642 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
644 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
645 switch (FF.getValueSize()) {
646 default: llvm_unreachable("Invalid size!");
647 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
648 case 2: OW->Write16(uint16_t(FF.getValue())); break;
649 case 4: OW->Write32(uint32_t(FF.getValue())); break;
650 case 8: OW->Write64(uint64_t(FF.getValue())); break;
656 case MCFragment::FT_LEB: {
657 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
658 OW->WriteBytes(LF.getContents().str());
662 case MCFragment::FT_Org: {
663 ++stats::EmittedOrgFragments;
664 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
666 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
667 OW->Write8(uint8_t(OF.getValue()));
672 case MCFragment::FT_Dwarf: {
673 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
674 OW->WriteBytes(OF.getContents().str());
677 case MCFragment::FT_DwarfFrame: {
678 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
679 OW->WriteBytes(CF.getContents().str());
684 assert(OW->getStream().tell() - Start == FragmentSize &&
685 "The stream should advance by fragment size");
688 void MCAssembler::writeSectionData(const MCSectionData *SD,
689 const MCAsmLayout &Layout) const {
690 // Ignore virtual sections.
691 if (SD->getSection().isVirtualSection()) {
692 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
694 // Check that contents are only things legal inside a virtual section.
695 for (MCSectionData::const_iterator it = SD->begin(),
696 ie = SD->end(); it != ie; ++it) {
697 switch (it->getKind()) {
698 default: llvm_unreachable("Invalid fragment in virtual section!");
699 case MCFragment::FT_Data: {
700 // Check that we aren't trying to write a non-zero contents (or fixups)
701 // into a virtual section. This is to support clients which use standard
702 // directives to fill the contents of virtual sections.
703 const MCDataFragment &DF = cast<MCDataFragment>(*it);
704 assert(DF.fixup_begin() == DF.fixup_end() &&
705 "Cannot have fixups in virtual section!");
706 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
707 assert(DF.getContents()[i] == 0 &&
708 "Invalid data value for virtual section!");
711 case MCFragment::FT_Align:
712 // Check that we aren't trying to write a non-zero value into a virtual
714 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
715 cast<MCAlignFragment>(it)->getValue() == 0) &&
716 "Invalid align in virtual section!");
718 case MCFragment::FT_Fill:
719 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
720 cast<MCFillFragment>(it)->getValue() == 0) &&
721 "Invalid fill in virtual section!");
729 uint64_t Start = getWriter().getStream().tell();
732 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
734 writeFragment(*this, Layout, *it);
736 assert(getWriter().getStream().tell() - Start ==
737 Layout.getSectionAddressSize(SD));
740 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
742 const MCFixup &Fixup) {
743 // Evaluate the fixup.
746 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
747 MCFixupKindInfo::FKF_IsPCRel;
748 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
749 // The fixup was unresolved, we need a relocation. Inform the object
750 // writer of the relocation, and give it an opportunity to adjust the
751 // fixup value if need be.
752 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
755 return std::make_pair(FixedValue, IsPCRel);
758 void MCAssembler::Finish() {
759 DEBUG_WITH_TYPE("mc-dump", {
760 llvm::errs() << "assembler backend - pre-layout\n--\n";
763 // Create the layout object.
764 MCAsmLayout Layout(*this);
766 // Create dummy fragments and assign section ordinals.
767 unsigned SectionIndex = 0;
768 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
769 // Create dummy fragments to eliminate any empty sections, this simplifies
771 if (it->getFragmentList().empty())
772 new MCDataFragment(it);
774 it->setOrdinal(SectionIndex++);
777 // Assign layout order indices to sections and fragments.
778 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
779 MCSectionData *SD = Layout.getSectionOrder()[i];
780 SD->setLayoutOrder(i);
782 unsigned FragmentIndex = 0;
783 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
784 iFrag != iFragEnd; ++iFrag)
785 iFrag->setLayoutOrder(FragmentIndex++);
788 // Layout until everything fits.
789 while (layoutOnce(Layout))
792 DEBUG_WITH_TYPE("mc-dump", {
793 llvm::errs() << "assembler backend - post-relaxation\n--\n";
796 // Finalize the layout, including fragment lowering.
797 finishLayout(Layout);
799 DEBUG_WITH_TYPE("mc-dump", {
800 llvm::errs() << "assembler backend - final-layout\n--\n";
803 uint64_t StartOffset = OS.tell();
805 // Allow the object writer a chance to perform post-layout binding (for
806 // example, to set the index fields in the symbol data).
807 getWriter().ExecutePostLayoutBinding(*this, Layout);
809 // Evaluate and apply the fixups, generating relocation entries as necessary.
810 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
811 for (MCSectionData::iterator it2 = it->begin(),
812 ie2 = it->end(); it2 != ie2; ++it2) {
813 MCEncodedFragmentWithFixups *F =
814 dyn_cast<MCEncodedFragmentWithFixups>(it2);
816 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
817 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
818 MCFixup &Fixup = *it3;
821 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
822 getBackend().applyFixup(Fixup, F->getContents().data(),
823 F->getContents().size(), FixedValue, IsPCRel);
829 // Write the object file.
830 getWriter().WriteObject(*this, Layout);
832 stats::ObjectBytes += OS.tell() - StartOffset;
835 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
836 const MCRelaxableFragment *DF,
837 const MCAsmLayout &Layout) const {
838 // If we cannot resolve the fixup value, it requires relaxation.
841 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
844 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
847 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
848 const MCAsmLayout &Layout) const {
849 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
850 // are intentionally pushing out inst fragments, or because we relaxed a
851 // previous instruction to one that doesn't need relaxation.
852 if (!getBackend().mayNeedRelaxation(F->getInst()))
855 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
856 ie = F->fixup_end(); it != ie; ++it)
857 if (fixupNeedsRelaxation(*it, F, Layout))
863 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
864 MCRelaxableFragment &F) {
865 if (!fragmentNeedsRelaxation(&F, Layout))
868 ++stats::RelaxedInstructions;
870 // FIXME-PERF: We could immediately lower out instructions if we can tell
871 // they are fully resolved, to avoid retesting on later passes.
873 // Relax the fragment.
876 getBackend().relaxInstruction(F.getInst(), Relaxed);
878 // Encode the new instruction.
880 // FIXME-PERF: If it matters, we could let the target do this. It can
881 // probably do so more efficiently in many cases.
882 SmallVector<MCFixup, 4> Fixups;
883 SmallString<256> Code;
884 raw_svector_ostream VecOS(Code);
885 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
888 // Update the fragment.
890 F.getContents() = Code;
891 F.getFixups() = Fixups;
896 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
898 uint64_t OldSize = LF.getContents().size();
899 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
902 SmallString<8> &Data = LF.getContents();
904 raw_svector_ostream OSE(Data);
906 encodeSLEB128(Value, OSE);
908 encodeULEB128(Value, OSE);
910 return OldSize != LF.getContents().size();
913 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
914 MCDwarfLineAddrFragment &DF) {
915 MCContext &Context = Layout.getAssembler().getContext();
916 int64_t AddrDelta = 0;
917 uint64_t OldSize = DF.getContents().size();
918 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
922 LineDelta = DF.getLineDelta();
923 SmallString<8> &Data = DF.getContents();
925 raw_svector_ostream OSE(Data);
926 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
928 return OldSize != Data.size();
931 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
932 MCDwarfCallFrameFragment &DF) {
933 MCContext &Context = Layout.getAssembler().getContext();
934 int64_t AddrDelta = 0;
935 uint64_t OldSize = DF.getContents().size();
936 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
939 SmallString<8> &Data = DF.getContents();
941 raw_svector_ostream OSE(Data);
942 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
944 return OldSize != Data.size();
947 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
948 // Holds the first fragment which needed relaxing during this layout. It will
949 // remain NULL if none were relaxed.
950 // When a fragment is relaxed, all the fragments following it should get
951 // invalidated because their offset is going to change.
952 MCFragment *FirstRelaxedFragment = nullptr;
954 // Attempt to relax all the fragments in the section.
955 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
956 // Check if this is a fragment that needs relaxation.
957 bool RelaxedFrag = false;
958 switch(I->getKind()) {
961 case MCFragment::FT_Relaxable:
962 assert(!getRelaxAll() &&
963 "Did not expect a MCRelaxableFragment in RelaxAll mode");
964 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
966 case MCFragment::FT_Dwarf:
967 RelaxedFrag = relaxDwarfLineAddr(Layout,
968 *cast<MCDwarfLineAddrFragment>(I));
970 case MCFragment::FT_DwarfFrame:
972 relaxDwarfCallFrameFragment(Layout,
973 *cast<MCDwarfCallFrameFragment>(I));
975 case MCFragment::FT_LEB:
976 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
979 if (RelaxedFrag && !FirstRelaxedFragment)
980 FirstRelaxedFragment = I;
982 if (FirstRelaxedFragment) {
983 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
989 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
990 ++stats::RelaxationSteps;
992 bool WasRelaxed = false;
993 for (iterator it = begin(), ie = end(); it != ie; ++it) {
994 MCSectionData &SD = *it;
995 while (layoutSectionOnce(Layout, SD))
1002 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1003 // The layout is done. Mark every fragment as valid.
1004 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1005 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1009 // Debugging methods
1013 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1014 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1015 << " Value:" << *AF.getValue()
1016 << " Kind:" << AF.getKind() << ">";
1022 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1023 void MCFragment::dump() {
1024 raw_ostream &OS = llvm::errs();
1027 switch (getKind()) {
1028 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1029 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1030 case MCFragment::FT_CompactEncodedInst:
1031 OS << "MCCompactEncodedInstFragment"; break;
1032 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1033 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1034 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1035 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1036 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1037 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1040 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1041 << " Offset:" << Offset
1042 << " HasInstructions:" << hasInstructions()
1043 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1045 switch (getKind()) {
1046 case MCFragment::FT_Align: {
1047 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1048 if (AF->hasEmitNops())
1049 OS << " (emit nops)";
1051 OS << " Alignment:" << AF->getAlignment()
1052 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1053 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1056 case MCFragment::FT_Data: {
1057 const MCDataFragment *DF = cast<MCDataFragment>(this);
1059 OS << " Contents:[";
1060 const SmallVectorImpl<char> &Contents = DF->getContents();
1061 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1063 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1065 OS << "] (" << Contents.size() << " bytes)";
1067 if (DF->fixup_begin() != DF->fixup_end()) {
1070 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1071 ie = DF->fixup_end(); it != ie; ++it) {
1072 if (it != DF->fixup_begin()) OS << ",\n ";
1079 case MCFragment::FT_CompactEncodedInst: {
1080 const MCCompactEncodedInstFragment *CEIF =
1081 cast<MCCompactEncodedInstFragment>(this);
1083 OS << " Contents:[";
1084 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1085 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1087 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1089 OS << "] (" << Contents.size() << " bytes)";
1092 case MCFragment::FT_Fill: {
1093 const MCFillFragment *FF = cast<MCFillFragment>(this);
1094 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1095 << " Size:" << FF->getSize();
1098 case MCFragment::FT_Relaxable: {
1099 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1102 F->getInst().dump_pretty(OS);
1105 case MCFragment::FT_Org: {
1106 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1108 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1111 case MCFragment::FT_Dwarf: {
1112 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1114 OS << " AddrDelta:" << OF->getAddrDelta()
1115 << " LineDelta:" << OF->getLineDelta();
1118 case MCFragment::FT_DwarfFrame: {
1119 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1121 OS << " AddrDelta:" << CF->getAddrDelta();
1124 case MCFragment::FT_LEB: {
1125 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1127 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1134 void MCSectionData::dump() {
1135 raw_ostream &OS = llvm::errs();
1137 OS << "<MCSectionData";
1138 OS << " Alignment:" << getAlignment()
1139 << " Fragments:[\n ";
1140 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1141 if (it != begin()) OS << ",\n ";
1147 void MCSymbolData::dump() {
1148 raw_ostream &OS = llvm::errs();
1150 OS << "<MCSymbolData Symbol:" << getSymbol()
1151 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1152 << " Flags:" << getFlags() << " Index:" << getIndex();
1154 OS << " (common, size:" << getCommonSize()
1155 << " align: " << getCommonAlignment() << ")";
1157 OS << " (external)";
1158 if (isPrivateExtern())
1159 OS << " (private extern)";
1163 void MCAssembler::dump() {
1164 raw_ostream &OS = llvm::errs();
1166 OS << "<MCAssembler\n";
1167 OS << " Sections:[\n ";
1168 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1169 if (it != begin()) OS << ",\n ";
1175 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1176 if (it != symbol_begin()) OS << ",\n ";
1183 // anchors for MC*Fragment vtables
1184 void MCEncodedFragment::anchor() { }
1185 void MCEncodedFragmentWithFixups::anchor() { }
1186 void MCDataFragment::anchor() { }
1187 void MCCompactEncodedInstFragment::anchor() { }
1188 void MCRelaxableFragment::anchor() { }
1189 void MCAlignFragment::anchor() { }
1190 void MCFillFragment::anchor() { }
1191 void MCOrgFragment::anchor() { }
1192 void MCLEBFragment::anchor() { }
1193 void MCDwarfLineAddrFragment::anchor() { }
1194 void MCDwarfCallFrameFragment::anchor() { }