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::invalidateFragmentsAfter(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 this fragment.
91 const MCSectionData &SD = *F->getParent();
92 LastValidFragment[&SD] = F;
95 void MCAsmLayout::ensureValid(const MCFragment *F) const {
96 MCSectionData &SD = *F->getParent();
98 MCFragment *Cur = LastValidFragment[&SD];
102 Cur = Cur->getNextNode();
104 // Advance the layout position until the fragment is valid.
105 while (!isFragmentValid(F)) {
106 assert(Cur && "Layout bookkeeping error");
107 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
108 Cur = Cur->getNextNode();
112 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
114 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
118 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
119 const MCSymbol &S = SD->getSymbol();
121 // If this is a variable, then recursively evaluate now.
122 if (S.isVariable()) {
124 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
125 report_fatal_error("unable to evaluate offset for variable '" +
128 // Verify that any used symbols are defined.
129 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
130 report_fatal_error("unable to evaluate offset to undefined symbol '" +
131 Target.getSymA()->getSymbol().getName() + "'");
132 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
133 report_fatal_error("unable to evaluate offset to undefined symbol '" +
134 Target.getSymB()->getSymbol().getName() + "'");
136 uint64_t Offset = Target.getConstant();
137 if (Target.getSymA())
138 Offset += getSymbolOffset(&Assembler.getSymbolData(
139 Target.getSymA()->getSymbol()));
140 if (Target.getSymB())
141 Offset -= getSymbolOffset(&Assembler.getSymbolData(
142 Target.getSymB()->getSymbol()));
146 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
147 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
150 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
151 // The size is the last fragment's end offset.
152 const MCFragment &F = SD->getFragmentList().back();
153 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
156 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
157 // Virtual sections have no file size.
158 if (SD->getSection().isVirtualSection())
161 // Otherwise, the file size is the same as the address space size.
162 return getSectionAddressSize(SD);
165 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
166 uint64_t FOffset, uint64_t FSize) {
167 uint64_t BundleSize = Assembler.getBundleAlignSize();
168 assert(BundleSize > 0 &&
169 "computeBundlePadding should only be called if bundling is enabled");
170 uint64_t BundleMask = BundleSize - 1;
171 uint64_t OffsetInBundle = FOffset & BundleMask;
172 uint64_t EndOfFragment = OffsetInBundle + FSize;
174 // There are two kinds of bundling restrictions:
176 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
177 // *end* on a bundle boundary.
178 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
179 // would, add padding until the end of the bundle so that the fragment
180 // will start in a new one.
181 if (F->alignToBundleEnd()) {
182 // Three possibilities here:
184 // A) The fragment just happens to end at a bundle boundary, so we're good.
185 // B) The fragment ends before the current bundle boundary: pad it just
186 // enough to reach the boundary.
187 // C) The fragment ends after the current bundle boundary: pad it until it
188 // reaches the end of the next bundle boundary.
190 // Note: this code could be made shorter with some modulo trickery, but it's
191 // intentionally kept in its more explicit form for simplicity.
192 if (EndOfFragment == BundleSize)
194 else if (EndOfFragment < BundleSize)
195 return BundleSize - EndOfFragment;
196 else { // EndOfFragment > BundleSize
197 return 2 * BundleSize - EndOfFragment;
199 } else if (EndOfFragment > BundleSize)
200 return BundleSize - OffsetInBundle;
207 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
210 MCFragment::~MCFragment() {
213 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
214 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
217 Parent->getFragmentList().push_back(this);
222 MCEncodedFragment::~MCEncodedFragment() {
227 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
232 MCSectionData::MCSectionData() : Section(0) {}
234 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
235 : Section(&_Section),
236 Ordinal(~UINT32_C(0)),
238 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
239 HasInstructions(false)
242 A->getSectionList().push_back(this);
247 MCSymbolData::MCSymbolData() : Symbol(0) {}
249 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
250 uint64_t _Offset, MCAssembler *A)
251 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
252 IsExternal(false), IsPrivateExtern(false),
253 CommonSize(0), SymbolSize(0), CommonAlign(0),
257 A->getSymbolList().push_back(this);
262 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
263 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
265 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
266 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
267 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
270 MCAssembler::~MCAssembler() {
273 void MCAssembler::reset() {
278 IndirectSymbols.clear();
283 SubsectionsViaSymbols = false;
286 // reset objects owned by us
287 getBackend().reset();
288 getEmitter().reset();
292 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
293 // Non-temporary labels should always be visible to the linker.
294 if (!Symbol.isTemporary())
297 // Absolute temporary labels are never visible.
298 if (!Symbol.isInSection())
301 // Otherwise, check if the section requires symbols even for temporary labels.
302 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
305 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
306 // Linker visible symbols define atoms.
307 if (isSymbolLinkerVisible(SD->getSymbol()))
310 // Absolute and undefined symbols have no defining atom.
311 if (!SD->getFragment())
314 // Non-linker visible symbols in sections which can't be atomized have no
316 if (!getBackend().isSectionAtomizable(
317 SD->getFragment()->getParent()->getSection()))
320 // Otherwise, return the atom for the containing fragment.
321 return SD->getFragment()->getAtom();
324 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
325 const MCFixup &Fixup, const MCFragment *DF,
326 MCValue &Target, uint64_t &Value) const {
327 ++stats::evaluateFixup;
329 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
330 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
332 bool IsPCRel = Backend.getFixupKindInfo(
333 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
337 if (Target.getSymB()) {
339 } else if (!Target.getSymA()) {
342 const MCSymbolRefExpr *A = Target.getSymA();
343 const MCSymbol &SA = A->getSymbol();
344 if (A->getKind() != MCSymbolRefExpr::VK_None ||
345 SA.AliasedSymbol().isUndefined()) {
348 const MCSymbolData &DataA = getSymbolData(SA);
350 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
355 IsResolved = Target.isAbsolute();
358 Value = Target.getConstant();
360 if (const MCSymbolRefExpr *A = Target.getSymA()) {
361 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
363 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
365 if (const MCSymbolRefExpr *B = Target.getSymB()) {
366 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
368 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
372 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
373 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
374 assert((ShouldAlignPC ? IsPCRel : true) &&
375 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
378 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
380 // A number of ARM fixups in Thumb mode require that the effective PC
381 // address be determined as the 32-bit aligned version of the actual offset.
382 if (ShouldAlignPC) Offset &= ~0x3;
386 // Let the backend adjust the fixup value if necessary, including whether
387 // we need a relocation.
388 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
394 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
395 const MCFragment &F) const {
396 switch (F.getKind()) {
397 case MCFragment::FT_Data:
398 case MCFragment::FT_Relaxable:
399 case MCFragment::FT_CompactEncodedInst:
400 return cast<MCEncodedFragment>(F).getContents().size();
401 case MCFragment::FT_Fill:
402 return cast<MCFillFragment>(F).getSize();
404 case MCFragment::FT_LEB:
405 return cast<MCLEBFragment>(F).getContents().size();
407 case MCFragment::FT_Align: {
408 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
409 unsigned Offset = Layout.getFragmentOffset(&AF);
410 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
411 // If we are padding with nops, force the padding to be larger than the
413 if (Size > 0 && AF.hasEmitNops()) {
414 while (Size % getBackend().getMinimumNopSize())
415 Size += AF.getAlignment();
417 if (Size > AF.getMaxBytesToEmit())
422 case MCFragment::FT_Org: {
423 MCOrgFragment &OF = cast<MCOrgFragment>(F);
424 int64_t TargetLocation;
425 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
426 report_fatal_error("expected assembly-time absolute expression");
428 // FIXME: We need a way to communicate this error.
429 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
430 int64_t Size = TargetLocation - FragmentOffset;
431 if (Size < 0 || Size >= 0x40000000)
432 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
433 "' (at offset '" + Twine(FragmentOffset) + "')");
437 case MCFragment::FT_Dwarf:
438 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
439 case MCFragment::FT_DwarfFrame:
440 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
443 llvm_unreachable("invalid fragment kind");
446 void MCAsmLayout::layoutFragment(MCFragment *F) {
447 MCFragment *Prev = F->getPrevNode();
449 // We should never try to recompute something which is valid.
450 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
451 // We should never try to compute the fragment layout if its predecessor
453 assert((!Prev || isFragmentValid(Prev)) &&
454 "Attempt to compute fragment before its predecessor!");
456 ++stats::FragmentLayouts;
458 // Compute fragment offset and size.
460 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
463 LastValidFragment[F->getParent()] = F;
465 // If bundling is enabled and this fragment has instructions in it, it has to
466 // obey the bundling restrictions. With padding, we'll have:
471 // -------------------------------------
472 // Prev |##########| F |
473 // -------------------------------------
478 // The fragment's offset will point to after the padding, and its computed
479 // size won't include the padding.
481 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
482 assert(isa<MCEncodedFragment>(F) &&
483 "Only MCEncodedFragment implementations have instructions");
484 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
486 if (FSize > Assembler.getBundleAlignSize())
487 report_fatal_error("Fragment can't be larger than a bundle size");
489 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
490 if (RequiredBundlePadding > UINT8_MAX)
491 report_fatal_error("Padding cannot exceed 255 bytes");
492 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
493 F->Offset += RequiredBundlePadding;
497 /// \brief Write the contents of a fragment to the given object writer. Expects
498 /// a MCEncodedFragment.
499 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
500 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
501 OW->WriteBytes(EF.getContents());
504 /// \brief Write the fragment \p F to the output file.
505 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
506 const MCFragment &F) {
507 MCObjectWriter *OW = &Asm.getWriter();
509 // FIXME: Embed in fragments instead?
510 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
512 // Should NOP padding be written out before this fragment?
513 unsigned BundlePadding = F.getBundlePadding();
514 if (BundlePadding > 0) {
515 assert(Asm.isBundlingEnabled() &&
516 "Writing bundle padding with disabled bundling");
517 assert(F.hasInstructions() &&
518 "Writing bundle padding for a fragment without instructions");
520 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
521 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
522 // If the padding itself crosses a bundle boundary, it must be emitted
523 // in 2 pieces, since even nop instructions must not cross boundaries.
524 // v--------------v <- BundleAlignSize
525 // v---------v <- BundlePadding
526 // ----------------------------
527 // | Prev |####|####| F |
528 // ----------------------------
529 // ^-------------------^ <- TotalLength
530 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
531 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
532 report_fatal_error("unable to write NOP sequence of " +
533 Twine(DistanceToBoundary) + " bytes");
534 BundlePadding -= DistanceToBoundary;
536 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
537 report_fatal_error("unable to write NOP sequence of " +
538 Twine(BundlePadding) + " bytes");
541 // This variable (and its dummy usage) is to participate in the assert at
542 // the end of the function.
543 uint64_t Start = OW->getStream().tell();
546 ++stats::EmittedFragments;
548 switch (F.getKind()) {
549 case MCFragment::FT_Align: {
550 ++stats::EmittedAlignFragments;
551 MCAlignFragment &AF = cast<MCAlignFragment>(F);
552 uint64_t Count = FragmentSize / AF.getValueSize();
554 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
556 // FIXME: This error shouldn't actually occur (the front end should emit
557 // multiple .align directives to enforce the semantics it wants), but is
558 // severe enough that we want to report it. How to handle this?
559 if (Count * AF.getValueSize() != FragmentSize)
560 report_fatal_error("undefined .align directive, value size '" +
561 Twine(AF.getValueSize()) +
562 "' is not a divisor of padding size '" +
563 Twine(FragmentSize) + "'");
565 // See if we are aligning with nops, and if so do that first to try to fill
566 // the Count bytes. Then if that did not fill any bytes or there are any
567 // bytes left to fill use the Value and ValueSize to fill the rest.
568 // If we are aligning with nops, ask that target to emit the right data.
569 if (AF.hasEmitNops()) {
570 if (!Asm.getBackend().writeNopData(Count, OW))
571 report_fatal_error("unable to write nop sequence of " +
572 Twine(Count) + " bytes");
576 // Otherwise, write out in multiples of the value size.
577 for (uint64_t i = 0; i != Count; ++i) {
578 switch (AF.getValueSize()) {
579 default: llvm_unreachable("Invalid size!");
580 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
581 case 2: OW->Write16(uint16_t(AF.getValue())); break;
582 case 4: OW->Write32(uint32_t(AF.getValue())); break;
583 case 8: OW->Write64(uint64_t(AF.getValue())); break;
589 case MCFragment::FT_Data:
590 ++stats::EmittedDataFragments;
591 writeFragmentContents(F, OW);
594 case MCFragment::FT_Relaxable:
595 ++stats::EmittedRelaxableFragments;
596 writeFragmentContents(F, OW);
599 case MCFragment::FT_CompactEncodedInst:
600 ++stats::EmittedCompactEncodedInstFragments;
601 writeFragmentContents(F, OW);
604 case MCFragment::FT_Fill: {
605 ++stats::EmittedFillFragments;
606 MCFillFragment &FF = cast<MCFillFragment>(F);
608 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
610 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
611 switch (FF.getValueSize()) {
612 default: llvm_unreachable("Invalid size!");
613 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
614 case 2: OW->Write16(uint16_t(FF.getValue())); break;
615 case 4: OW->Write32(uint32_t(FF.getValue())); break;
616 case 8: OW->Write64(uint64_t(FF.getValue())); break;
622 case MCFragment::FT_LEB: {
623 MCLEBFragment &LF = cast<MCLEBFragment>(F);
624 OW->WriteBytes(LF.getContents().str());
628 case MCFragment::FT_Org: {
629 ++stats::EmittedOrgFragments;
630 MCOrgFragment &OF = cast<MCOrgFragment>(F);
632 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
633 OW->Write8(uint8_t(OF.getValue()));
638 case MCFragment::FT_Dwarf: {
639 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
640 OW->WriteBytes(OF.getContents().str());
643 case MCFragment::FT_DwarfFrame: {
644 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
645 OW->WriteBytes(CF.getContents().str());
650 assert(OW->getStream().tell() - Start == FragmentSize &&
651 "The stream should advance by fragment size");
654 void MCAssembler::writeSectionData(const MCSectionData *SD,
655 const MCAsmLayout &Layout) const {
656 // Ignore virtual sections.
657 if (SD->getSection().isVirtualSection()) {
658 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
660 // Check that contents are only things legal inside a virtual section.
661 for (MCSectionData::const_iterator it = SD->begin(),
662 ie = SD->end(); it != ie; ++it) {
663 switch (it->getKind()) {
664 default: llvm_unreachable("Invalid fragment in virtual section!");
665 case MCFragment::FT_Data: {
666 // Check that we aren't trying to write a non-zero contents (or fixups)
667 // into a virtual section. This is to support clients which use standard
668 // directives to fill the contents of virtual sections.
669 MCDataFragment &DF = cast<MCDataFragment>(*it);
670 assert(DF.fixup_begin() == DF.fixup_end() &&
671 "Cannot have fixups in virtual section!");
672 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
673 assert(DF.getContents()[i] == 0 &&
674 "Invalid data value for virtual section!");
677 case MCFragment::FT_Align:
678 // Check that we aren't trying to write a non-zero value into a virtual
680 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
681 !cast<MCAlignFragment>(it)->getValue()) &&
682 "Invalid align in virtual section!");
684 case MCFragment::FT_Fill:
685 assert(!cast<MCFillFragment>(it)->getValueSize() &&
686 "Invalid fill in virtual section!");
694 uint64_t Start = getWriter().getStream().tell();
697 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
699 writeFragment(*this, Layout, *it);
701 assert(getWriter().getStream().tell() - Start ==
702 Layout.getSectionAddressSize(SD));
706 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
708 const MCFixup &Fixup) {
709 // Evaluate the fixup.
712 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
713 // The fixup was unresolved, we need a relocation. Inform the object
714 // writer of the relocation, and give it an opportunity to adjust the
715 // fixup value if need be.
716 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
721 void MCAssembler::Finish() {
722 DEBUG_WITH_TYPE("mc-dump", {
723 llvm::errs() << "assembler backend - pre-layout\n--\n";
726 // Create the layout object.
727 MCAsmLayout Layout(*this);
729 // Create dummy fragments and assign section ordinals.
730 unsigned SectionIndex = 0;
731 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
732 // Create dummy fragments to eliminate any empty sections, this simplifies
734 if (it->getFragmentList().empty())
735 new MCDataFragment(it);
737 it->setOrdinal(SectionIndex++);
740 // Assign layout order indices to sections and fragments.
741 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
742 MCSectionData *SD = Layout.getSectionOrder()[i];
743 SD->setLayoutOrder(i);
745 unsigned FragmentIndex = 0;
746 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
747 iFrag != iFragEnd; ++iFrag)
748 iFrag->setLayoutOrder(FragmentIndex++);
751 // Layout until everything fits.
752 while (layoutOnce(Layout))
755 DEBUG_WITH_TYPE("mc-dump", {
756 llvm::errs() << "assembler backend - post-relaxation\n--\n";
759 // Finalize the layout, including fragment lowering.
760 finishLayout(Layout);
762 DEBUG_WITH_TYPE("mc-dump", {
763 llvm::errs() << "assembler backend - final-layout\n--\n";
766 uint64_t StartOffset = OS.tell();
768 // Allow the object writer a chance to perform post-layout binding (for
769 // example, to set the index fields in the symbol data).
770 getWriter().ExecutePostLayoutBinding(*this, Layout);
772 // Evaluate and apply the fixups, generating relocation entries as necessary.
773 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
774 for (MCSectionData::iterator it2 = it->begin(),
775 ie2 = it->end(); it2 != ie2; ++it2) {
776 MCEncodedFragmentWithFixups *F =
777 dyn_cast<MCEncodedFragmentWithFixups>(it2);
779 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
780 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
781 MCFixup &Fixup = *it3;
782 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
783 getBackend().applyFixup(Fixup, F->getContents().data(),
784 F->getContents().size(), FixedValue);
790 // Write the object file.
791 getWriter().WriteObject(*this, Layout);
793 stats::ObjectBytes += OS.tell() - StartOffset;
796 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
797 const MCRelaxableFragment *DF,
798 const MCAsmLayout &Layout) const {
799 // If we cannot resolve the fixup value, it requires relaxation.
802 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
805 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
808 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
809 const MCAsmLayout &Layout) const {
810 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
811 // are intentionally pushing out inst fragments, or because we relaxed a
812 // previous instruction to one that doesn't need relaxation.
813 if (!getBackend().mayNeedRelaxation(F->getInst()))
816 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
817 ie = F->fixup_end(); it != ie; ++it)
818 if (fixupNeedsRelaxation(*it, F, Layout))
824 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
825 MCRelaxableFragment &F) {
826 if (!fragmentNeedsRelaxation(&F, Layout))
829 ++stats::RelaxedInstructions;
831 // FIXME-PERF: We could immediately lower out instructions if we can tell
832 // they are fully resolved, to avoid retesting on later passes.
834 // Relax the fragment.
837 getBackend().relaxInstruction(F.getInst(), Relaxed);
839 // Encode the new instruction.
841 // FIXME-PERF: If it matters, we could let the target do this. It can
842 // probably do so more efficiently in many cases.
843 SmallVector<MCFixup, 4> Fixups;
844 SmallString<256> Code;
845 raw_svector_ostream VecOS(Code);
846 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
849 // Update the fragment.
851 F.getContents() = Code;
852 F.getFixups() = Fixups;
857 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
859 uint64_t OldSize = LF.getContents().size();
860 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
863 SmallString<8> &Data = LF.getContents();
865 raw_svector_ostream OSE(Data);
867 encodeSLEB128(Value, OSE);
869 encodeULEB128(Value, OSE);
871 return OldSize != LF.getContents().size();
874 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
875 MCDwarfLineAddrFragment &DF) {
876 int64_t AddrDelta = 0;
877 uint64_t OldSize = DF.getContents().size();
878 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
882 LineDelta = DF.getLineDelta();
883 SmallString<8> &Data = DF.getContents();
885 raw_svector_ostream OSE(Data);
886 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
888 return OldSize != Data.size();
891 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
892 MCDwarfCallFrameFragment &DF) {
893 int64_t AddrDelta = 0;
894 uint64_t OldSize = DF.getContents().size();
895 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
898 SmallString<8> &Data = DF.getContents();
900 raw_svector_ostream OSE(Data);
901 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
903 return OldSize != Data.size();
906 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
907 // Holds the first fragment which needed relaxing during this layout. It will
908 // remain NULL if none were relaxed.
909 // When a fragment is relaxed, all the fragments following it should get
910 // invalidated because their offset is going to change.
911 MCFragment *FirstRelaxedFragment = NULL;
913 // Attempt to relax all the fragments in the section.
914 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
915 // Check if this is a fragment that needs relaxation.
916 bool RelaxedFrag = false;
917 switch(I->getKind()) {
920 case MCFragment::FT_Relaxable:
921 assert(!getRelaxAll() &&
922 "Did not expect a MCRelaxableFragment in RelaxAll mode");
923 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
925 case MCFragment::FT_Dwarf:
926 RelaxedFrag = relaxDwarfLineAddr(Layout,
927 *cast<MCDwarfLineAddrFragment>(I));
929 case MCFragment::FT_DwarfFrame:
931 relaxDwarfCallFrameFragment(Layout,
932 *cast<MCDwarfCallFrameFragment>(I));
934 case MCFragment::FT_LEB:
935 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
938 if (RelaxedFrag && !FirstRelaxedFragment)
939 FirstRelaxedFragment = I;
941 if (FirstRelaxedFragment) {
942 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
948 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
949 ++stats::RelaxationSteps;
951 bool WasRelaxed = false;
952 for (iterator it = begin(), ie = end(); it != ie; ++it) {
953 MCSectionData &SD = *it;
954 while (layoutSectionOnce(Layout, SD))
961 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
962 // The layout is done. Mark every fragment as valid.
963 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
964 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
972 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
973 OS << "<MCFixup" << " Offset:" << AF.getOffset()
974 << " Value:" << *AF.getValue()
975 << " Kind:" << AF.getKind() << ">";
981 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
982 void MCFragment::dump() {
983 raw_ostream &OS = llvm::errs();
987 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
988 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
989 case MCFragment::FT_CompactEncodedInst:
990 OS << "MCCompactEncodedInstFragment"; break;
991 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
992 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
993 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
994 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
995 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
996 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
999 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1000 << " Offset:" << Offset
1001 << " HasInstructions:" << hasInstructions()
1002 << " BundlePadding:" << getBundlePadding() << ">";
1004 switch (getKind()) {
1005 case MCFragment::FT_Align: {
1006 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1007 if (AF->hasEmitNops())
1008 OS << " (emit nops)";
1010 OS << " Alignment:" << AF->getAlignment()
1011 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1012 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1015 case MCFragment::FT_Data: {
1016 const MCDataFragment *DF = cast<MCDataFragment>(this);
1018 OS << " Contents:[";
1019 const SmallVectorImpl<char> &Contents = DF->getContents();
1020 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1022 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1024 OS << "] (" << Contents.size() << " bytes)";
1026 if (DF->fixup_begin() != DF->fixup_end()) {
1029 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1030 ie = DF->fixup_end(); it != ie; ++it) {
1031 if (it != DF->fixup_begin()) OS << ",\n ";
1038 case MCFragment::FT_CompactEncodedInst: {
1039 const MCCompactEncodedInstFragment *CEIF =
1040 cast<MCCompactEncodedInstFragment>(this);
1042 OS << " Contents:[";
1043 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1044 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1046 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1048 OS << "] (" << Contents.size() << " bytes)";
1051 case MCFragment::FT_Fill: {
1052 const MCFillFragment *FF = cast<MCFillFragment>(this);
1053 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1054 << " Size:" << FF->getSize();
1057 case MCFragment::FT_Relaxable: {
1058 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1061 F->getInst().dump_pretty(OS);
1064 case MCFragment::FT_Org: {
1065 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1067 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1070 case MCFragment::FT_Dwarf: {
1071 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1073 OS << " AddrDelta:" << OF->getAddrDelta()
1074 << " LineDelta:" << OF->getLineDelta();
1077 case MCFragment::FT_DwarfFrame: {
1078 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1080 OS << " AddrDelta:" << CF->getAddrDelta();
1083 case MCFragment::FT_LEB: {
1084 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1086 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1093 void MCSectionData::dump() {
1094 raw_ostream &OS = llvm::errs();
1096 OS << "<MCSectionData";
1097 OS << " Alignment:" << getAlignment()
1098 << " Fragments:[\n ";
1099 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1100 if (it != begin()) OS << ",\n ";
1106 void MCSymbolData::dump() {
1107 raw_ostream &OS = llvm::errs();
1109 OS << "<MCSymbolData Symbol:" << getSymbol()
1110 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1111 << " Flags:" << getFlags() << " Index:" << getIndex();
1113 OS << " (common, size:" << getCommonSize()
1114 << " align: " << getCommonAlignment() << ")";
1116 OS << " (external)";
1117 if (isPrivateExtern())
1118 OS << " (private extern)";
1122 void MCAssembler::dump() {
1123 raw_ostream &OS = llvm::errs();
1125 OS << "<MCAssembler\n";
1126 OS << " Sections:[\n ";
1127 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1128 if (it != begin()) OS << ",\n ";
1134 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1135 if (it != symbol_begin()) OS << ",\n ";
1142 // anchors for MC*Fragment vtables
1143 void MCEncodedFragment::anchor() { }
1144 void MCEncodedFragmentWithFixups::anchor() { }
1145 void MCDataFragment::anchor() { }
1146 void MCCompactEncodedInstFragment::anchor() { }
1147 void MCRelaxableFragment::anchor() { }
1148 void MCAlignFragment::anchor() { }
1149 void MCFillFragment::anchor() { }
1150 void MCOrgFragment::anchor() { }
1151 void MCLEBFragment::anchor() { }
1152 void MCDwarfLineAddrFragment::anchor() { }
1153 void MCDwarfCallFrameFragment::anchor() { }