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) {
301 MCAssembler::~MCAssembler() {
304 void MCAssembler::reset() {
309 IndirectSymbols.clear();
314 SubsectionsViaSymbols = false;
317 // reset objects owned by us
318 getBackend().reset();
319 getEmitter().reset();
323 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
324 // Non-temporary labels should always be visible to the linker.
325 if (!Symbol.isTemporary())
328 // Absolute temporary labels are never visible.
329 if (!Symbol.isInSection())
332 // Otherwise, check if the section requires symbols even for temporary labels.
333 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
336 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
337 // Linker visible symbols define atoms.
338 if (isSymbolLinkerVisible(SD->getSymbol()))
341 // Absolute and undefined symbols have no defining atom.
342 if (!SD->getFragment())
345 // Non-linker visible symbols in sections which can't be atomized have no
347 if (!getBackend().isSectionAtomizable(
348 SD->getFragment()->getParent()->getSection()))
351 // Otherwise, return the atom for the containing fragment.
352 return SD->getFragment()->getAtom();
355 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
356 const MCFixup &Fixup, const MCFragment *DF,
357 MCValue &Target, uint64_t &Value) const {
358 ++stats::evaluateFixup;
360 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
361 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
363 bool IsPCRel = Backend.getFixupKindInfo(
364 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
368 if (Target.getSymB()) {
370 } else if (!Target.getSymA()) {
373 const MCSymbolRefExpr *A = Target.getSymA();
374 const MCSymbol &SA = A->getSymbol();
375 if (A->getKind() != MCSymbolRefExpr::VK_None ||
376 SA.AliasedSymbol().isUndefined()) {
379 const MCSymbolData &DataA = getSymbolData(SA);
381 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
386 IsResolved = Target.isAbsolute();
389 Value = Target.getConstant();
391 if (const MCSymbolRefExpr *A = Target.getSymA()) {
392 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
394 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
396 if (const MCSymbolRefExpr *B = Target.getSymB()) {
397 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
399 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
403 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
404 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
405 assert((ShouldAlignPC ? IsPCRel : true) &&
406 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
409 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
411 // A number of ARM fixups in Thumb mode require that the effective PC
412 // address be determined as the 32-bit aligned version of the actual offset.
413 if (ShouldAlignPC) Offset &= ~0x3;
417 // Let the backend adjust the fixup value if necessary, including whether
418 // we need a relocation.
419 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
425 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
426 const MCFragment &F) const {
427 switch (F.getKind()) {
428 case MCFragment::FT_Data:
429 case MCFragment::FT_Relaxable:
430 case MCFragment::FT_CompactEncodedInst:
431 return cast<MCEncodedFragment>(F).getContents().size();
432 case MCFragment::FT_Fill:
433 return cast<MCFillFragment>(F).getSize();
435 case MCFragment::FT_LEB:
436 return cast<MCLEBFragment>(F).getContents().size();
438 case MCFragment::FT_Align: {
439 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
440 unsigned Offset = Layout.getFragmentOffset(&AF);
441 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
442 // If we are padding with nops, force the padding to be larger than the
444 if (Size > 0 && AF.hasEmitNops()) {
445 while (Size % getBackend().getMinimumNopSize())
446 Size += AF.getAlignment();
448 if (Size > AF.getMaxBytesToEmit())
453 case MCFragment::FT_Org: {
454 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
455 int64_t TargetLocation;
456 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
457 report_fatal_error("expected assembly-time absolute expression");
459 // FIXME: We need a way to communicate this error.
460 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
461 int64_t Size = TargetLocation - FragmentOffset;
462 if (Size < 0 || Size >= 0x40000000)
463 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
464 "' (at offset '" + Twine(FragmentOffset) + "')");
468 case MCFragment::FT_Dwarf:
469 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
470 case MCFragment::FT_DwarfFrame:
471 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
474 llvm_unreachable("invalid fragment kind");
477 void MCAsmLayout::layoutFragment(MCFragment *F) {
478 MCFragment *Prev = F->getPrevNode();
480 // We should never try to recompute something which is valid.
481 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
482 // We should never try to compute the fragment layout if its predecessor
484 assert((!Prev || isFragmentValid(Prev)) &&
485 "Attempt to compute fragment before its predecessor!");
487 ++stats::FragmentLayouts;
489 // Compute fragment offset and size.
491 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
494 LastValidFragment[F->getParent()] = F;
496 // If bundling is enabled and this fragment has instructions in it, it has to
497 // obey the bundling restrictions. With padding, we'll have:
502 // -------------------------------------
503 // Prev |##########| F |
504 // -------------------------------------
509 // The fragment's offset will point to after the padding, and its computed
510 // size won't include the padding.
512 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
513 assert(isa<MCEncodedFragment>(F) &&
514 "Only MCEncodedFragment implementations have instructions");
515 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
517 if (FSize > Assembler.getBundleAlignSize())
518 report_fatal_error("Fragment can't be larger than a bundle size");
520 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
521 if (RequiredBundlePadding > UINT8_MAX)
522 report_fatal_error("Padding cannot exceed 255 bytes");
523 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
524 F->Offset += RequiredBundlePadding;
528 /// \brief Write the contents of a fragment to the given object writer. Expects
529 /// a MCEncodedFragment.
530 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
531 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
532 OW->WriteBytes(EF.getContents());
535 /// \brief Write the fragment \p F to the output file.
536 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
537 const MCFragment &F) {
538 MCObjectWriter *OW = &Asm.getWriter();
540 // FIXME: Embed in fragments instead?
541 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
543 // Should NOP padding be written out before this fragment?
544 unsigned BundlePadding = F.getBundlePadding();
545 if (BundlePadding > 0) {
546 assert(Asm.isBundlingEnabled() &&
547 "Writing bundle padding with disabled bundling");
548 assert(F.hasInstructions() &&
549 "Writing bundle padding for a fragment without instructions");
551 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
552 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
553 // If the padding itself crosses a bundle boundary, it must be emitted
554 // in 2 pieces, since even nop instructions must not cross boundaries.
555 // v--------------v <- BundleAlignSize
556 // v---------v <- BundlePadding
557 // ----------------------------
558 // | Prev |####|####| F |
559 // ----------------------------
560 // ^-------------------^ <- TotalLength
561 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
562 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
563 report_fatal_error("unable to write NOP sequence of " +
564 Twine(DistanceToBoundary) + " bytes");
565 BundlePadding -= DistanceToBoundary;
567 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
568 report_fatal_error("unable to write NOP sequence of " +
569 Twine(BundlePadding) + " bytes");
572 // This variable (and its dummy usage) is to participate in the assert at
573 // the end of the function.
574 uint64_t Start = OW->getStream().tell();
577 ++stats::EmittedFragments;
579 switch (F.getKind()) {
580 case MCFragment::FT_Align: {
581 ++stats::EmittedAlignFragments;
582 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
583 uint64_t Count = FragmentSize / AF.getValueSize();
585 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
587 // FIXME: This error shouldn't actually occur (the front end should emit
588 // multiple .align directives to enforce the semantics it wants), but is
589 // severe enough that we want to report it. How to handle this?
590 if (Count * AF.getValueSize() != FragmentSize)
591 report_fatal_error("undefined .align directive, value size '" +
592 Twine(AF.getValueSize()) +
593 "' is not a divisor of padding size '" +
594 Twine(FragmentSize) + "'");
596 // See if we are aligning with nops, and if so do that first to try to fill
597 // the Count bytes. Then if that did not fill any bytes or there are any
598 // bytes left to fill use the Value and ValueSize to fill the rest.
599 // If we are aligning with nops, ask that target to emit the right data.
600 if (AF.hasEmitNops()) {
601 if (!Asm.getBackend().writeNopData(Count, OW))
602 report_fatal_error("unable to write nop sequence of " +
603 Twine(Count) + " bytes");
607 // Otherwise, write out in multiples of the value size.
608 for (uint64_t i = 0; i != Count; ++i) {
609 switch (AF.getValueSize()) {
610 default: llvm_unreachable("Invalid size!");
611 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
612 case 2: OW->Write16(uint16_t(AF.getValue())); break;
613 case 4: OW->Write32(uint32_t(AF.getValue())); break;
614 case 8: OW->Write64(uint64_t(AF.getValue())); break;
620 case MCFragment::FT_Data:
621 ++stats::EmittedDataFragments;
622 writeFragmentContents(F, OW);
625 case MCFragment::FT_Relaxable:
626 ++stats::EmittedRelaxableFragments;
627 writeFragmentContents(F, OW);
630 case MCFragment::FT_CompactEncodedInst:
631 ++stats::EmittedCompactEncodedInstFragments;
632 writeFragmentContents(F, OW);
635 case MCFragment::FT_Fill: {
636 ++stats::EmittedFillFragments;
637 const MCFillFragment &FF = cast<MCFillFragment>(F);
639 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
641 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
642 switch (FF.getValueSize()) {
643 default: llvm_unreachable("Invalid size!");
644 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
645 case 2: OW->Write16(uint16_t(FF.getValue())); break;
646 case 4: OW->Write32(uint32_t(FF.getValue())); break;
647 case 8: OW->Write64(uint64_t(FF.getValue())); break;
653 case MCFragment::FT_LEB: {
654 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
655 OW->WriteBytes(LF.getContents().str());
659 case MCFragment::FT_Org: {
660 ++stats::EmittedOrgFragments;
661 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
663 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
664 OW->Write8(uint8_t(OF.getValue()));
669 case MCFragment::FT_Dwarf: {
670 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
671 OW->WriteBytes(OF.getContents().str());
674 case MCFragment::FT_DwarfFrame: {
675 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
676 OW->WriteBytes(CF.getContents().str());
681 assert(OW->getStream().tell() - Start == FragmentSize &&
682 "The stream should advance by fragment size");
685 void MCAssembler::writeSectionData(const MCSectionData *SD,
686 const MCAsmLayout &Layout) const {
687 // Ignore virtual sections.
688 if (SD->getSection().isVirtualSection()) {
689 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
691 // Check that contents are only things legal inside a virtual section.
692 for (MCSectionData::const_iterator it = SD->begin(),
693 ie = SD->end(); it != ie; ++it) {
694 switch (it->getKind()) {
695 default: llvm_unreachable("Invalid fragment in virtual section!");
696 case MCFragment::FT_Data: {
697 // Check that we aren't trying to write a non-zero contents (or fixups)
698 // into a virtual section. This is to support clients which use standard
699 // directives to fill the contents of virtual sections.
700 const MCDataFragment &DF = cast<MCDataFragment>(*it);
701 assert(DF.fixup_begin() == DF.fixup_end() &&
702 "Cannot have fixups in virtual section!");
703 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
704 assert(DF.getContents()[i] == 0 &&
705 "Invalid data value for virtual section!");
708 case MCFragment::FT_Align:
709 // Check that we aren't trying to write a non-zero value into a virtual
711 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
712 !cast<MCAlignFragment>(it)->getValue()) &&
713 "Invalid align in virtual section!");
715 case MCFragment::FT_Fill:
716 assert(!cast<MCFillFragment>(it)->getValueSize() &&
717 "Invalid fill in virtual section!");
725 uint64_t Start = getWriter().getStream().tell();
728 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
730 writeFragment(*this, Layout, *it);
732 assert(getWriter().getStream().tell() - Start ==
733 Layout.getSectionAddressSize(SD));
737 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
739 const MCFixup &Fixup) {
740 // Evaluate the fixup.
743 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
744 // The fixup was unresolved, we need a relocation. Inform the object
745 // writer of the relocation, and give it an opportunity to adjust the
746 // fixup value if need be.
747 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
752 void MCAssembler::Finish() {
753 DEBUG_WITH_TYPE("mc-dump", {
754 llvm::errs() << "assembler backend - pre-layout\n--\n";
757 // Create the layout object.
758 MCAsmLayout Layout(*this);
760 // Create dummy fragments and assign section ordinals.
761 unsigned SectionIndex = 0;
762 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
763 // Create dummy fragments to eliminate any empty sections, this simplifies
765 if (it->getFragmentList().empty())
766 new MCDataFragment(it);
768 it->setOrdinal(SectionIndex++);
771 // Assign layout order indices to sections and fragments.
772 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
773 MCSectionData *SD = Layout.getSectionOrder()[i];
774 SD->setLayoutOrder(i);
776 unsigned FragmentIndex = 0;
777 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
778 iFrag != iFragEnd; ++iFrag)
779 iFrag->setLayoutOrder(FragmentIndex++);
782 // Layout until everything fits.
783 while (layoutOnce(Layout))
786 DEBUG_WITH_TYPE("mc-dump", {
787 llvm::errs() << "assembler backend - post-relaxation\n--\n";
790 // Finalize the layout, including fragment lowering.
791 finishLayout(Layout);
793 DEBUG_WITH_TYPE("mc-dump", {
794 llvm::errs() << "assembler backend - final-layout\n--\n";
797 uint64_t StartOffset = OS.tell();
799 // Allow the object writer a chance to perform post-layout binding (for
800 // example, to set the index fields in the symbol data).
801 getWriter().ExecutePostLayoutBinding(*this, Layout);
803 // Evaluate and apply the fixups, generating relocation entries as necessary.
804 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
805 for (MCSectionData::iterator it2 = it->begin(),
806 ie2 = it->end(); it2 != ie2; ++it2) {
807 MCEncodedFragmentWithFixups *F =
808 dyn_cast<MCEncodedFragmentWithFixups>(it2);
810 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
811 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
812 MCFixup &Fixup = *it3;
813 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
814 getBackend().applyFixup(Fixup, F->getContents().data(),
815 F->getContents().size(), FixedValue);
821 // Write the object file.
822 getWriter().WriteObject(*this, Layout);
824 stats::ObjectBytes += OS.tell() - StartOffset;
827 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
828 const MCRelaxableFragment *DF,
829 const MCAsmLayout &Layout) const {
830 // If we cannot resolve the fixup value, it requires relaxation.
833 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
836 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
839 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
840 const MCAsmLayout &Layout) const {
841 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
842 // are intentionally pushing out inst fragments, or because we relaxed a
843 // previous instruction to one that doesn't need relaxation.
844 if (!getBackend().mayNeedRelaxation(F->getInst()))
847 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
848 ie = F->fixup_end(); it != ie; ++it)
849 if (fixupNeedsRelaxation(*it, F, Layout))
855 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
856 MCRelaxableFragment &F) {
857 if (!fragmentNeedsRelaxation(&F, Layout))
860 ++stats::RelaxedInstructions;
862 // FIXME-PERF: We could immediately lower out instructions if we can tell
863 // they are fully resolved, to avoid retesting on later passes.
865 // Relax the fragment.
868 getBackend().relaxInstruction(F.getInst(), Relaxed);
870 // Encode the new instruction.
872 // FIXME-PERF: If it matters, we could let the target do this. It can
873 // probably do so more efficiently in many cases.
874 SmallVector<MCFixup, 4> Fixups;
875 SmallString<256> Code;
876 raw_svector_ostream VecOS(Code);
877 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
880 // Update the fragment.
882 F.getContents() = Code;
883 F.getFixups() = Fixups;
888 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
890 uint64_t OldSize = LF.getContents().size();
891 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
894 SmallString<8> &Data = LF.getContents();
896 raw_svector_ostream OSE(Data);
898 encodeSLEB128(Value, OSE);
900 encodeULEB128(Value, OSE);
902 return OldSize != LF.getContents().size();
905 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
906 MCDwarfLineAddrFragment &DF) {
907 MCContext &Context = Layout.getAssembler().getContext();
908 int64_t AddrDelta = 0;
909 uint64_t OldSize = DF.getContents().size();
910 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
914 LineDelta = DF.getLineDelta();
915 SmallString<8> &Data = DF.getContents();
917 raw_svector_ostream OSE(Data);
918 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
920 return OldSize != Data.size();
923 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
924 MCDwarfCallFrameFragment &DF) {
925 MCContext &Context = Layout.getAssembler().getContext();
926 int64_t AddrDelta = 0;
927 uint64_t OldSize = DF.getContents().size();
928 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
931 SmallString<8> &Data = DF.getContents();
933 raw_svector_ostream OSE(Data);
934 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
936 return OldSize != Data.size();
939 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
940 // Holds the first fragment which needed relaxing during this layout. It will
941 // remain NULL if none were relaxed.
942 // When a fragment is relaxed, all the fragments following it should get
943 // invalidated because their offset is going to change.
944 MCFragment *FirstRelaxedFragment = NULL;
946 // Attempt to relax all the fragments in the section.
947 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
948 // Check if this is a fragment that needs relaxation.
949 bool RelaxedFrag = false;
950 switch(I->getKind()) {
953 case MCFragment::FT_Relaxable:
954 assert(!getRelaxAll() &&
955 "Did not expect a MCRelaxableFragment in RelaxAll mode");
956 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
958 case MCFragment::FT_Dwarf:
959 RelaxedFrag = relaxDwarfLineAddr(Layout,
960 *cast<MCDwarfLineAddrFragment>(I));
962 case MCFragment::FT_DwarfFrame:
964 relaxDwarfCallFrameFragment(Layout,
965 *cast<MCDwarfCallFrameFragment>(I));
967 case MCFragment::FT_LEB:
968 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
971 if (RelaxedFrag && !FirstRelaxedFragment)
972 FirstRelaxedFragment = I;
974 if (FirstRelaxedFragment) {
975 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
981 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
982 ++stats::RelaxationSteps;
984 bool WasRelaxed = false;
985 for (iterator it = begin(), ie = end(); it != ie; ++it) {
986 MCSectionData &SD = *it;
987 while (layoutSectionOnce(Layout, SD))
994 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
995 // The layout is done. Mark every fragment as valid.
996 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
997 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1001 // Debugging methods
1005 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1006 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1007 << " Value:" << *AF.getValue()
1008 << " Kind:" << AF.getKind() << ">";
1014 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1015 void MCFragment::dump() {
1016 raw_ostream &OS = llvm::errs();
1019 switch (getKind()) {
1020 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1021 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1022 case MCFragment::FT_CompactEncodedInst:
1023 OS << "MCCompactEncodedInstFragment"; break;
1024 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1025 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1026 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1027 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1028 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1029 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1032 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1033 << " Offset:" << Offset
1034 << " HasInstructions:" << hasInstructions()
1035 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1037 switch (getKind()) {
1038 case MCFragment::FT_Align: {
1039 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1040 if (AF->hasEmitNops())
1041 OS << " (emit nops)";
1043 OS << " Alignment:" << AF->getAlignment()
1044 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1045 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1048 case MCFragment::FT_Data: {
1049 const MCDataFragment *DF = cast<MCDataFragment>(this);
1051 OS << " Contents:[";
1052 const SmallVectorImpl<char> &Contents = DF->getContents();
1053 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1055 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1057 OS << "] (" << Contents.size() << " bytes)";
1059 if (DF->fixup_begin() != DF->fixup_end()) {
1062 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1063 ie = DF->fixup_end(); it != ie; ++it) {
1064 if (it != DF->fixup_begin()) OS << ",\n ";
1071 case MCFragment::FT_CompactEncodedInst: {
1072 const MCCompactEncodedInstFragment *CEIF =
1073 cast<MCCompactEncodedInstFragment>(this);
1075 OS << " Contents:[";
1076 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1077 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1079 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1081 OS << "] (" << Contents.size() << " bytes)";
1084 case MCFragment::FT_Fill: {
1085 const MCFillFragment *FF = cast<MCFillFragment>(this);
1086 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1087 << " Size:" << FF->getSize();
1090 case MCFragment::FT_Relaxable: {
1091 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1094 F->getInst().dump_pretty(OS);
1097 case MCFragment::FT_Org: {
1098 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1100 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1103 case MCFragment::FT_Dwarf: {
1104 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1106 OS << " AddrDelta:" << OF->getAddrDelta()
1107 << " LineDelta:" << OF->getLineDelta();
1110 case MCFragment::FT_DwarfFrame: {
1111 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1113 OS << " AddrDelta:" << CF->getAddrDelta();
1116 case MCFragment::FT_LEB: {
1117 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1119 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1126 void MCSectionData::dump() {
1127 raw_ostream &OS = llvm::errs();
1129 OS << "<MCSectionData";
1130 OS << " Alignment:" << getAlignment()
1131 << " Fragments:[\n ";
1132 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1133 if (it != begin()) OS << ",\n ";
1139 void MCSymbolData::dump() {
1140 raw_ostream &OS = llvm::errs();
1142 OS << "<MCSymbolData Symbol:" << getSymbol()
1143 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1144 << " Flags:" << getFlags() << " Index:" << getIndex();
1146 OS << " (common, size:" << getCommonSize()
1147 << " align: " << getCommonAlignment() << ")";
1149 OS << " (external)";
1150 if (isPrivateExtern())
1151 OS << " (private extern)";
1155 void MCAssembler::dump() {
1156 raw_ostream &OS = llvm::errs();
1158 OS << "<MCAssembler\n";
1159 OS << " Sections:[\n ";
1160 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1161 if (it != begin()) OS << ",\n ";
1167 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1168 if (it != symbol_begin()) OS << ",\n ";
1175 // anchors for MC*Fragment vtables
1176 void MCEncodedFragment::anchor() { }
1177 void MCEncodedFragmentWithFixups::anchor() { }
1178 void MCDataFragment::anchor() { }
1179 void MCCompactEncodedInstFragment::anchor() { }
1180 void MCRelaxableFragment::anchor() { }
1181 void MCAlignFragment::anchor() { }
1182 void MCFillFragment::anchor() { }
1183 void MCOrgFragment::anchor() { }
1184 void MCLEBFragment::anchor() { }
1185 void MCDwarfLineAddrFragment::anchor() { }
1186 void MCDwarfCallFrameFragment::anchor() { }