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 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/ADT/Statistic.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.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/MCSymbol.h"
25 #include "llvm/MC/MCValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
36 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
37 STATISTIC(EmittedRelaxableFragments,
38 "Number of emitted assembler fragments - relaxable");
39 STATISTIC(EmittedDataFragments,
40 "Number of emitted assembler fragments - data");
41 STATISTIC(EmittedCompactEncodedInstFragments,
42 "Number of emitted assembler fragments - compact encoded inst");
43 STATISTIC(EmittedAlignFragments,
44 "Number of emitted assembler fragments - align");
45 STATISTIC(EmittedFillFragments,
46 "Number of emitted assembler fragments - fill");
47 STATISTIC(EmittedOrgFragments,
48 "Number of emitted assembler fragments - org");
49 STATISTIC(evaluateFixup, "Number of evaluated fixups");
50 STATISTIC(FragmentLayouts, "Number of fragment layouts");
51 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
52 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
53 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
57 // FIXME FIXME FIXME: There are number of places in this file where we convert
58 // what is a 64-bit assembler value used for computation into a value in the
59 // object file, which may truncate it. We should detect that truncation where
60 // invalid and report errors back.
64 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
65 : Assembler(Asm), LastValidFragment()
67 // Compute the section layout order. Virtual sections must go last.
68 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
69 if (!it->getSection().isVirtualSection())
70 SectionOrder.push_back(&*it);
71 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72 if (it->getSection().isVirtualSection())
73 SectionOrder.push_back(&*it);
76 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
77 const MCSectionData &SD = *F->getParent();
78 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
81 assert(LastValid->getParent() == F->getParent());
82 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
85 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
86 // If this fragment wasn't already valid, we don't need to do anything.
87 if (!isFragmentValid(F))
90 // Otherwise, reset the last valid fragment to the previous fragment
91 // (if this is the first fragment, it will be NULL).
92 const MCSectionData &SD = *F->getParent();
93 LastValidFragment[&SD] = F->getPrevNode();
96 void MCAsmLayout::ensureValid(const MCFragment *F) const {
97 MCSectionData &SD = *F->getParent();
99 MCFragment *Cur = LastValidFragment[&SD];
103 Cur = Cur->getNextNode();
105 // Advance the layout position until the fragment is valid.
106 while (!isFragmentValid(F)) {
107 assert(Cur && "Layout bookkeeping error");
108 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
109 Cur = Cur->getNextNode();
113 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
115 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
119 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
120 const MCSymbol &S = SD->getSymbol();
122 // If this is a variable, then recursively evaluate now.
123 if (S.isVariable()) {
125 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, this))
126 report_fatal_error("unable to evaluate offset for variable '" +
129 // Verify that any used symbols are defined.
130 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
131 report_fatal_error("unable to evaluate offset to undefined symbol '" +
132 Target.getSymA()->getSymbol().getName() + "'");
133 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
134 report_fatal_error("unable to evaluate offset to undefined symbol '" +
135 Target.getSymB()->getSymbol().getName() + "'");
137 uint64_t Offset = Target.getConstant();
138 if (Target.getSymA())
139 Offset += getSymbolOffset(&Assembler.getSymbolData(
140 Target.getSymA()->getSymbol()));
141 if (Target.getSymB())
142 Offset -= getSymbolOffset(&Assembler.getSymbolData(
143 Target.getSymB()->getSymbol()));
147 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
148 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
151 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
152 // The size is the last fragment's end offset.
153 const MCFragment &F = SD->getFragmentList().back();
154 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
157 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
158 // Virtual sections have no file size.
159 if (SD->getSection().isVirtualSection())
162 // Otherwise, the file size is the same as the address space size.
163 return getSectionAddressSize(SD);
166 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
167 uint64_t FOffset, uint64_t FSize) {
168 uint64_t BundleSize = Assembler.getBundleAlignSize();
169 assert(BundleSize > 0 &&
170 "computeBundlePadding should only be called if bundling is enabled");
171 uint64_t BundleMask = BundleSize - 1;
172 uint64_t OffsetInBundle = FOffset & BundleMask;
173 uint64_t EndOfFragment = OffsetInBundle + FSize;
175 // There are two kinds of bundling restrictions:
177 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
178 // *end* on a bundle boundary.
179 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
180 // would, add padding until the end of the bundle so that the fragment
181 // will start in a new one.
182 if (F->alignToBundleEnd()) {
183 // Three possibilities here:
185 // A) The fragment just happens to end at a bundle boundary, so we're good.
186 // B) The fragment ends before the current bundle boundary: pad it just
187 // enough to reach the boundary.
188 // C) The fragment ends after the current bundle boundary: pad it until it
189 // reaches the end of the next bundle boundary.
191 // Note: this code could be made shorter with some modulo trickery, but it's
192 // intentionally kept in its more explicit form for simplicity.
193 if (EndOfFragment == BundleSize)
195 else if (EndOfFragment < BundleSize)
196 return BundleSize - EndOfFragment;
197 else { // EndOfFragment > BundleSize
198 return 2 * BundleSize - EndOfFragment;
200 } else if (EndOfFragment > BundleSize)
201 return BundleSize - OffsetInBundle;
208 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
211 MCFragment::~MCFragment() {
214 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
215 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
218 Parent->getFragmentList().push_back(this);
223 MCEncodedFragment::~MCEncodedFragment() {
228 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
233 MCSectionData::MCSectionData() : Section(0) {}
235 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
236 : Section(&_Section),
237 Ordinal(~UINT32_C(0)),
239 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
240 HasInstructions(false)
243 A->getSectionList().push_back(this);
246 MCSectionData::iterator
247 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
248 if (Subsection == 0 && SubsectionFragmentMap.empty())
251 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
252 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
253 std::make_pair(Subsection, (MCFragment *)0));
254 bool ExactMatch = false;
255 if (MI != SubsectionFragmentMap.end()) {
256 ExactMatch = MI->first == Subsection;
261 if (MI == SubsectionFragmentMap.end())
265 if (!ExactMatch && Subsection != 0) {
266 // The GNU as documentation claims that subsections have an alignment of 4,
267 // although this appears not to be the case.
268 MCFragment *F = new MCDataFragment();
269 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
270 getFragmentList().insert(IP, F);
278 MCSymbolData::MCSymbolData() : Symbol(0) {}
280 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
281 uint64_t _Offset, MCAssembler *A)
282 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
283 IsExternal(false), IsPrivateExtern(false),
284 CommonSize(0), SymbolSize(0), CommonAlign(0),
288 A->getSymbolList().push_back(this);
293 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
294 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
296 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
297 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
298 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
299 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
302 MCAssembler::~MCAssembler() {
305 void MCAssembler::reset() {
310 IndirectSymbols.clear();
315 SubsectionsViaSymbols = false;
318 // reset objects owned by us
319 getBackend().reset();
320 getEmitter().reset();
322 getLOHContainer().reset();
325 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
326 // Non-temporary labels should always be visible to the linker.
327 if (!Symbol.isTemporary())
330 // Absolute temporary labels are never visible.
331 if (!Symbol.isInSection())
334 // Otherwise, check if the section requires symbols even for temporary labels.
335 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
338 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
339 // Linker visible symbols define atoms.
340 if (isSymbolLinkerVisible(SD->getSymbol()))
343 // Absolute and undefined symbols have no defining atom.
344 if (!SD->getFragment())
347 // Non-linker visible symbols in sections which can't be atomized have no
349 if (!getBackend().isSectionAtomizable(
350 SD->getFragment()->getParent()->getSection()))
353 // Otherwise, return the atom for the containing fragment.
354 return SD->getFragment()->getAtom();
357 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
358 const MCFixup &Fixup, const MCFragment *DF,
359 MCValue &Target, uint64_t &Value) const {
360 ++stats::evaluateFixup;
362 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
363 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
365 bool IsPCRel = Backend.getFixupKindInfo(
366 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
370 if (Target.getSymB()) {
372 } else if (!Target.getSymA()) {
375 const MCSymbolRefExpr *A = Target.getSymA();
376 const MCSymbol &SA = A->getSymbol();
377 if (A->getKind() != MCSymbolRefExpr::VK_None ||
378 SA.AliasedSymbol().isUndefined()) {
381 const MCSymbolData &DataA = getSymbolData(SA);
383 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
388 IsResolved = Target.isAbsolute();
391 Value = Target.getConstant();
393 if (const MCSymbolRefExpr *A = Target.getSymA()) {
394 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
396 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
398 if (const MCSymbolRefExpr *B = Target.getSymB()) {
399 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
401 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
405 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
406 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
407 assert((ShouldAlignPC ? IsPCRel : true) &&
408 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
411 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
413 // A number of ARM fixups in Thumb mode require that the effective PC
414 // address be determined as the 32-bit aligned version of the actual offset.
415 if (ShouldAlignPC) Offset &= ~0x3;
419 // Let the backend adjust the fixup value if necessary, including whether
420 // we need a relocation.
421 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
427 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
428 const MCFragment &F) const {
429 switch (F.getKind()) {
430 case MCFragment::FT_Data:
431 case MCFragment::FT_Relaxable:
432 case MCFragment::FT_CompactEncodedInst:
433 return cast<MCEncodedFragment>(F).getContents().size();
434 case MCFragment::FT_Fill:
435 return cast<MCFillFragment>(F).getSize();
437 case MCFragment::FT_LEB:
438 return cast<MCLEBFragment>(F).getContents().size();
440 case MCFragment::FT_Align: {
441 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
442 unsigned Offset = Layout.getFragmentOffset(&AF);
443 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
444 // If we are padding with nops, force the padding to be larger than the
446 if (Size > 0 && AF.hasEmitNops()) {
447 while (Size % getBackend().getMinimumNopSize())
448 Size += AF.getAlignment();
450 if (Size > AF.getMaxBytesToEmit())
455 case MCFragment::FT_Org: {
456 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
457 int64_t TargetLocation;
458 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
459 report_fatal_error("expected assembly-time absolute expression");
461 // FIXME: We need a way to communicate this error.
462 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
463 int64_t Size = TargetLocation - FragmentOffset;
464 if (Size < 0 || Size >= 0x40000000)
465 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
466 "' (at offset '" + Twine(FragmentOffset) + "')");
470 case MCFragment::FT_Dwarf:
471 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
472 case MCFragment::FT_DwarfFrame:
473 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
476 llvm_unreachable("invalid fragment kind");
479 void MCAsmLayout::layoutFragment(MCFragment *F) {
480 MCFragment *Prev = F->getPrevNode();
482 // We should never try to recompute something which is valid.
483 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
484 // We should never try to compute the fragment layout if its predecessor
486 assert((!Prev || isFragmentValid(Prev)) &&
487 "Attempt to compute fragment before its predecessor!");
489 ++stats::FragmentLayouts;
491 // Compute fragment offset and size.
493 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
496 LastValidFragment[F->getParent()] = F;
498 // If bundling is enabled and this fragment has instructions in it, it has to
499 // obey the bundling restrictions. With padding, we'll have:
504 // -------------------------------------
505 // Prev |##########| F |
506 // -------------------------------------
511 // The fragment's offset will point to after the padding, and its computed
512 // size won't include the padding.
514 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
515 assert(isa<MCEncodedFragment>(F) &&
516 "Only MCEncodedFragment implementations have instructions");
517 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
519 if (FSize > Assembler.getBundleAlignSize())
520 report_fatal_error("Fragment can't be larger than a bundle size");
522 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
523 if (RequiredBundlePadding > UINT8_MAX)
524 report_fatal_error("Padding cannot exceed 255 bytes");
525 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
526 F->Offset += RequiredBundlePadding;
530 /// \brief Write the contents of a fragment to the given object writer. Expects
531 /// a MCEncodedFragment.
532 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
533 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
534 OW->WriteBytes(EF.getContents());
537 /// \brief Write the fragment \p F to the output file.
538 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
539 const MCFragment &F) {
540 MCObjectWriter *OW = &Asm.getWriter();
542 // FIXME: Embed in fragments instead?
543 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
545 // Should NOP padding be written out before this fragment?
546 unsigned BundlePadding = F.getBundlePadding();
547 if (BundlePadding > 0) {
548 assert(Asm.isBundlingEnabled() &&
549 "Writing bundle padding with disabled bundling");
550 assert(F.hasInstructions() &&
551 "Writing bundle padding for a fragment without instructions");
553 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
554 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
555 // If the padding itself crosses a bundle boundary, it must be emitted
556 // in 2 pieces, since even nop instructions must not cross boundaries.
557 // v--------------v <- BundleAlignSize
558 // v---------v <- BundlePadding
559 // ----------------------------
560 // | Prev |####|####| F |
561 // ----------------------------
562 // ^-------------------^ <- TotalLength
563 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
564 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
565 report_fatal_error("unable to write NOP sequence of " +
566 Twine(DistanceToBoundary) + " bytes");
567 BundlePadding -= DistanceToBoundary;
569 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
570 report_fatal_error("unable to write NOP sequence of " +
571 Twine(BundlePadding) + " bytes");
574 // This variable (and its dummy usage) is to participate in the assert at
575 // the end of the function.
576 uint64_t Start = OW->getStream().tell();
579 ++stats::EmittedFragments;
581 switch (F.getKind()) {
582 case MCFragment::FT_Align: {
583 ++stats::EmittedAlignFragments;
584 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
585 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
587 uint64_t Count = FragmentSize / AF.getValueSize();
589 // FIXME: This error shouldn't actually occur (the front end should emit
590 // multiple .align directives to enforce the semantics it wants), but is
591 // severe enough that we want to report it. How to handle this?
592 if (Count * AF.getValueSize() != FragmentSize)
593 report_fatal_error("undefined .align directive, value size '" +
594 Twine(AF.getValueSize()) +
595 "' is not a divisor of padding size '" +
596 Twine(FragmentSize) + "'");
598 // See if we are aligning with nops, and if so do that first to try to fill
599 // the Count bytes. Then if that did not fill any bytes or there are any
600 // bytes left to fill use the Value and ValueSize to fill the rest.
601 // If we are aligning with nops, ask that target to emit the right data.
602 if (AF.hasEmitNops()) {
603 if (!Asm.getBackend().writeNopData(Count, OW))
604 report_fatal_error("unable to write nop sequence of " +
605 Twine(Count) + " bytes");
609 // Otherwise, write out in multiples of the value size.
610 for (uint64_t i = 0; i != Count; ++i) {
611 switch (AF.getValueSize()) {
612 default: llvm_unreachable("Invalid size!");
613 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
614 case 2: OW->Write16(uint16_t(AF.getValue())); break;
615 case 4: OW->Write32(uint32_t(AF.getValue())); break;
616 case 8: OW->Write64(uint64_t(AF.getValue())); break;
622 case MCFragment::FT_Data:
623 ++stats::EmittedDataFragments;
624 writeFragmentContents(F, OW);
627 case MCFragment::FT_Relaxable:
628 ++stats::EmittedRelaxableFragments;
629 writeFragmentContents(F, OW);
632 case MCFragment::FT_CompactEncodedInst:
633 ++stats::EmittedCompactEncodedInstFragments;
634 writeFragmentContents(F, OW);
637 case MCFragment::FT_Fill: {
638 ++stats::EmittedFillFragments;
639 const MCFillFragment &FF = cast<MCFillFragment>(F);
641 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
643 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
644 switch (FF.getValueSize()) {
645 default: llvm_unreachable("Invalid size!");
646 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
647 case 2: OW->Write16(uint16_t(FF.getValue())); break;
648 case 4: OW->Write32(uint32_t(FF.getValue())); break;
649 case 8: OW->Write64(uint64_t(FF.getValue())); break;
655 case MCFragment::FT_LEB: {
656 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
657 OW->WriteBytes(LF.getContents().str());
661 case MCFragment::FT_Org: {
662 ++stats::EmittedOrgFragments;
663 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
665 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
666 OW->Write8(uint8_t(OF.getValue()));
671 case MCFragment::FT_Dwarf: {
672 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
673 OW->WriteBytes(OF.getContents().str());
676 case MCFragment::FT_DwarfFrame: {
677 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
678 OW->WriteBytes(CF.getContents().str());
683 assert(OW->getStream().tell() - Start == FragmentSize &&
684 "The stream should advance by fragment size");
687 void MCAssembler::writeSectionData(const MCSectionData *SD,
688 const MCAsmLayout &Layout) const {
689 // Ignore virtual sections.
690 if (SD->getSection().isVirtualSection()) {
691 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
693 // Check that contents are only things legal inside a virtual section.
694 for (MCSectionData::const_iterator it = SD->begin(),
695 ie = SD->end(); it != ie; ++it) {
696 switch (it->getKind()) {
697 default: llvm_unreachable("Invalid fragment in virtual section!");
698 case MCFragment::FT_Data: {
699 // Check that we aren't trying to write a non-zero contents (or fixups)
700 // into a virtual section. This is to support clients which use standard
701 // directives to fill the contents of virtual sections.
702 const MCDataFragment &DF = cast<MCDataFragment>(*it);
703 assert(DF.fixup_begin() == DF.fixup_end() &&
704 "Cannot have fixups in virtual section!");
705 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
706 assert(DF.getContents()[i] == 0 &&
707 "Invalid data value for virtual section!");
710 case MCFragment::FT_Align:
711 // Check that we aren't trying to write a non-zero value into a virtual
713 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
714 cast<MCAlignFragment>(it)->getValue() == 0) &&
715 "Invalid align in virtual section!");
717 case MCFragment::FT_Fill:
718 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
719 cast<MCFillFragment>(it)->getValue() == 0) &&
720 "Invalid fill in virtual section!");
728 uint64_t Start = getWriter().getStream().tell();
731 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
733 writeFragment(*this, Layout, *it);
735 assert(getWriter().getStream().tell() - Start ==
736 Layout.getSectionAddressSize(SD));
739 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
741 const MCFixup &Fixup) {
742 // Evaluate the fixup.
745 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
746 MCFixupKindInfo::FKF_IsPCRel;
747 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
748 // The fixup was unresolved, we need a relocation. Inform the object
749 // writer of the relocation, and give it an opportunity to adjust the
750 // fixup value if need be.
751 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
754 return std::make_pair(FixedValue, IsPCRel);
757 void MCAssembler::Finish() {
758 DEBUG_WITH_TYPE("mc-dump", {
759 llvm::errs() << "assembler backend - pre-layout\n--\n";
762 // Create the layout object.
763 MCAsmLayout Layout(*this);
765 // Create dummy fragments and assign section ordinals.
766 unsigned SectionIndex = 0;
767 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
768 // Create dummy fragments to eliminate any empty sections, this simplifies
770 if (it->getFragmentList().empty())
771 new MCDataFragment(it);
773 it->setOrdinal(SectionIndex++);
776 // Assign layout order indices to sections and fragments.
777 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
778 MCSectionData *SD = Layout.getSectionOrder()[i];
779 SD->setLayoutOrder(i);
781 unsigned FragmentIndex = 0;
782 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
783 iFrag != iFragEnd; ++iFrag)
784 iFrag->setLayoutOrder(FragmentIndex++);
787 // Layout until everything fits.
788 while (layoutOnce(Layout))
791 DEBUG_WITH_TYPE("mc-dump", {
792 llvm::errs() << "assembler backend - post-relaxation\n--\n";
795 // Finalize the layout, including fragment lowering.
796 finishLayout(Layout);
798 DEBUG_WITH_TYPE("mc-dump", {
799 llvm::errs() << "assembler backend - final-layout\n--\n";
802 uint64_t StartOffset = OS.tell();
804 // Allow the object writer a chance to perform post-layout binding (for
805 // example, to set the index fields in the symbol data).
806 getWriter().ExecutePostLayoutBinding(*this, Layout);
808 // Evaluate and apply the fixups, generating relocation entries as necessary.
809 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
810 for (MCSectionData::iterator it2 = it->begin(),
811 ie2 = it->end(); it2 != ie2; ++it2) {
812 MCEncodedFragmentWithFixups *F =
813 dyn_cast<MCEncodedFragmentWithFixups>(it2);
815 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
816 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
817 MCFixup &Fixup = *it3;
820 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
821 getBackend().applyFixup(Fixup, F->getContents().data(),
822 F->getContents().size(), FixedValue, IsPCRel);
828 // Write the object file.
829 getWriter().WriteObject(*this, Layout);
831 stats::ObjectBytes += OS.tell() - StartOffset;
834 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
835 const MCRelaxableFragment *DF,
836 const MCAsmLayout &Layout) const {
837 // If we cannot resolve the fixup value, it requires relaxation.
840 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
843 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
846 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
847 const MCAsmLayout &Layout) const {
848 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
849 // are intentionally pushing out inst fragments, or because we relaxed a
850 // previous instruction to one that doesn't need relaxation.
851 if (!getBackend().mayNeedRelaxation(F->getInst()))
854 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
855 ie = F->fixup_end(); it != ie; ++it)
856 if (fixupNeedsRelaxation(*it, F, Layout))
862 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
863 MCRelaxableFragment &F) {
864 if (!fragmentNeedsRelaxation(&F, Layout))
867 ++stats::RelaxedInstructions;
869 // FIXME-PERF: We could immediately lower out instructions if we can tell
870 // they are fully resolved, to avoid retesting on later passes.
872 // Relax the fragment.
875 getBackend().relaxInstruction(F.getInst(), Relaxed);
877 // Encode the new instruction.
879 // FIXME-PERF: If it matters, we could let the target do this. It can
880 // probably do so more efficiently in many cases.
881 SmallVector<MCFixup, 4> Fixups;
882 SmallString<256> Code;
883 raw_svector_ostream VecOS(Code);
884 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
887 // Update the fragment.
889 F.getContents() = Code;
890 F.getFixups() = Fixups;
895 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
897 uint64_t OldSize = LF.getContents().size();
898 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
901 SmallString<8> &Data = LF.getContents();
903 raw_svector_ostream OSE(Data);
905 encodeSLEB128(Value, OSE);
907 encodeULEB128(Value, OSE);
909 return OldSize != LF.getContents().size();
912 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
913 MCDwarfLineAddrFragment &DF) {
914 MCContext &Context = Layout.getAssembler().getContext();
915 int64_t AddrDelta = 0;
916 uint64_t OldSize = DF.getContents().size();
917 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
921 LineDelta = DF.getLineDelta();
922 SmallString<8> &Data = DF.getContents();
924 raw_svector_ostream OSE(Data);
925 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
927 return OldSize != Data.size();
930 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
931 MCDwarfCallFrameFragment &DF) {
932 MCContext &Context = Layout.getAssembler().getContext();
933 int64_t AddrDelta = 0;
934 uint64_t OldSize = DF.getContents().size();
935 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
938 SmallString<8> &Data = DF.getContents();
940 raw_svector_ostream OSE(Data);
941 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
943 return OldSize != Data.size();
946 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
947 // Holds the first fragment which needed relaxing during this layout. It will
948 // remain NULL if none were relaxed.
949 // When a fragment is relaxed, all the fragments following it should get
950 // invalidated because their offset is going to change.
951 MCFragment *FirstRelaxedFragment = NULL;
953 // Attempt to relax all the fragments in the section.
954 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
955 // Check if this is a fragment that needs relaxation.
956 bool RelaxedFrag = false;
957 switch(I->getKind()) {
960 case MCFragment::FT_Relaxable:
961 assert(!getRelaxAll() &&
962 "Did not expect a MCRelaxableFragment in RelaxAll mode");
963 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
965 case MCFragment::FT_Dwarf:
966 RelaxedFrag = relaxDwarfLineAddr(Layout,
967 *cast<MCDwarfLineAddrFragment>(I));
969 case MCFragment::FT_DwarfFrame:
971 relaxDwarfCallFrameFragment(Layout,
972 *cast<MCDwarfCallFrameFragment>(I));
974 case MCFragment::FT_LEB:
975 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
978 if (RelaxedFrag && !FirstRelaxedFragment)
979 FirstRelaxedFragment = I;
981 if (FirstRelaxedFragment) {
982 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
988 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
989 ++stats::RelaxationSteps;
991 bool WasRelaxed = false;
992 for (iterator it = begin(), ie = end(); it != ie; ++it) {
993 MCSectionData &SD = *it;
994 while (layoutSectionOnce(Layout, SD))
1001 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1002 // The layout is done. Mark every fragment as valid.
1003 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1004 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1008 // Debugging methods
1012 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1013 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1014 << " Value:" << *AF.getValue()
1015 << " Kind:" << AF.getKind() << ">";
1021 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1022 void MCFragment::dump() {
1023 raw_ostream &OS = llvm::errs();
1026 switch (getKind()) {
1027 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1028 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1029 case MCFragment::FT_CompactEncodedInst:
1030 OS << "MCCompactEncodedInstFragment"; break;
1031 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1032 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1033 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1034 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1035 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1036 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1039 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1040 << " Offset:" << Offset
1041 << " HasInstructions:" << hasInstructions()
1042 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1044 switch (getKind()) {
1045 case MCFragment::FT_Align: {
1046 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1047 if (AF->hasEmitNops())
1048 OS << " (emit nops)";
1050 OS << " Alignment:" << AF->getAlignment()
1051 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1052 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1055 case MCFragment::FT_Data: {
1056 const MCDataFragment *DF = cast<MCDataFragment>(this);
1058 OS << " Contents:[";
1059 const SmallVectorImpl<char> &Contents = DF->getContents();
1060 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1062 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1064 OS << "] (" << Contents.size() << " bytes)";
1066 if (DF->fixup_begin() != DF->fixup_end()) {
1069 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1070 ie = DF->fixup_end(); it != ie; ++it) {
1071 if (it != DF->fixup_begin()) OS << ",\n ";
1078 case MCFragment::FT_CompactEncodedInst: {
1079 const MCCompactEncodedInstFragment *CEIF =
1080 cast<MCCompactEncodedInstFragment>(this);
1082 OS << " Contents:[";
1083 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1084 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1086 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1088 OS << "] (" << Contents.size() << " bytes)";
1091 case MCFragment::FT_Fill: {
1092 const MCFillFragment *FF = cast<MCFillFragment>(this);
1093 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1094 << " Size:" << FF->getSize();
1097 case MCFragment::FT_Relaxable: {
1098 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1101 F->getInst().dump_pretty(OS);
1104 case MCFragment::FT_Org: {
1105 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1107 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1110 case MCFragment::FT_Dwarf: {
1111 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1113 OS << " AddrDelta:" << OF->getAddrDelta()
1114 << " LineDelta:" << OF->getLineDelta();
1117 case MCFragment::FT_DwarfFrame: {
1118 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1120 OS << " AddrDelta:" << CF->getAddrDelta();
1123 case MCFragment::FT_LEB: {
1124 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1126 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1133 void MCSectionData::dump() {
1134 raw_ostream &OS = llvm::errs();
1136 OS << "<MCSectionData";
1137 OS << " Alignment:" << getAlignment()
1138 << " Fragments:[\n ";
1139 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1140 if (it != begin()) OS << ",\n ";
1146 void MCSymbolData::dump() {
1147 raw_ostream &OS = llvm::errs();
1149 OS << "<MCSymbolData Symbol:" << getSymbol()
1150 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1151 << " Flags:" << getFlags() << " Index:" << getIndex();
1153 OS << " (common, size:" << getCommonSize()
1154 << " align: " << getCommonAlignment() << ")";
1156 OS << " (external)";
1157 if (isPrivateExtern())
1158 OS << " (private extern)";
1162 void MCAssembler::dump() {
1163 raw_ostream &OS = llvm::errs();
1165 OS << "<MCAssembler\n";
1166 OS << " Sections:[\n ";
1167 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1168 if (it != begin()) OS << ",\n ";
1174 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1175 if (it != symbol_begin()) OS << ",\n ";
1182 // anchors for MC*Fragment vtables
1183 void MCEncodedFragment::anchor() { }
1184 void MCEncodedFragmentWithFixups::anchor() { }
1185 void MCDataFragment::anchor() { }
1186 void MCCompactEncodedInstFragment::anchor() { }
1187 void MCRelaxableFragment::anchor() { }
1188 void MCAlignFragment::anchor() { }
1189 void MCFillFragment::anchor() { }
1190 void MCOrgFragment::anchor() { }
1191 void MCLEBFragment::anchor() { }
1192 void MCDwarfLineAddrFragment::anchor() { }
1193 void MCDwarfCallFrameFragment::anchor() { }