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"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Host.h"
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41 "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43 "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45 "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47 "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49 "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51 "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68 : Assembler(Asm), LastValidFragment()
70 // Compute the section layout order. Virtual sections must go last.
71 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72 if (!it->getSection().isVirtualSection())
73 SectionOrder.push_back(&*it);
74 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75 if (it->getSection().isVirtualSection())
76 SectionOrder.push_back(&*it);
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80 const MCSectionData &SD = *F->getParent();
81 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
84 assert(LastValid->getParent() == F->getParent());
85 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
89 // If this fragment wasn't already valid, we don't need to do anything.
90 if (!isFragmentValid(F))
93 // Otherwise, reset the last valid fragment to the previous fragment
94 // (if this is the first fragment, it will be NULL).
95 const MCSectionData &SD = *F->getParent();
96 LastValidFragment[&SD] = F->getPrevNode();
99 void MCAsmLayout::ensureValid(const MCFragment *F) const {
100 MCSectionData &SD = *F->getParent();
102 MCFragment *Cur = LastValidFragment[&SD];
106 Cur = Cur->getNextNode();
108 // Advance the layout position until the fragment is valid.
109 while (!isFragmentValid(F)) {
110 assert(Cur && "Layout bookkeeping error");
111 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
112 Cur = Cur->getNextNode();
116 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
118 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
122 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
123 const MCSymbol &S = SD->getSymbol();
125 // If this is a variable, then recursively evaluate now.
126 if (S.isVariable()) {
128 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, this))
129 report_fatal_error("unable to evaluate offset for variable '" +
132 // Verify that any used symbols are defined.
133 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
134 report_fatal_error("unable to evaluate offset to undefined symbol '" +
135 Target.getSymA()->getSymbol().getName() + "'");
136 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
137 report_fatal_error("unable to evaluate offset to undefined symbol '" +
138 Target.getSymB()->getSymbol().getName() + "'");
140 uint64_t Offset = Target.getConstant();
141 if (Target.getSymA())
142 Offset += getSymbolOffset(&Assembler.getSymbolData(
143 Target.getSymA()->getSymbol()));
144 if (Target.getSymB())
145 Offset -= getSymbolOffset(&Assembler.getSymbolData(
146 Target.getSymB()->getSymbol()));
150 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
151 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
154 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
155 // The size is the last fragment's end offset.
156 const MCFragment &F = SD->getFragmentList().back();
157 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
160 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
161 // Virtual sections have no file size.
162 if (SD->getSection().isVirtualSection())
165 // Otherwise, the file size is the same as the address space size.
166 return getSectionAddressSize(SD);
169 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
170 uint64_t FOffset, uint64_t FSize) {
171 uint64_t BundleSize = Assembler.getBundleAlignSize();
172 assert(BundleSize > 0 &&
173 "computeBundlePadding should only be called if bundling is enabled");
174 uint64_t BundleMask = BundleSize - 1;
175 uint64_t OffsetInBundle = FOffset & BundleMask;
176 uint64_t EndOfFragment = OffsetInBundle + FSize;
178 // There are two kinds of bundling restrictions:
180 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
181 // *end* on a bundle boundary.
182 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
183 // would, add padding until the end of the bundle so that the fragment
184 // will start in a new one.
185 if (F->alignToBundleEnd()) {
186 // Three possibilities here:
188 // A) The fragment just happens to end at a bundle boundary, so we're good.
189 // B) The fragment ends before the current bundle boundary: pad it just
190 // enough to reach the boundary.
191 // C) The fragment ends after the current bundle boundary: pad it until it
192 // reaches the end of the next bundle boundary.
194 // Note: this code could be made shorter with some modulo trickery, but it's
195 // intentionally kept in its more explicit form for simplicity.
196 if (EndOfFragment == BundleSize)
198 else if (EndOfFragment < BundleSize)
199 return BundleSize - EndOfFragment;
200 else { // EndOfFragment > BundleSize
201 return 2 * BundleSize - EndOfFragment;
203 } else if (EndOfFragment > BundleSize)
204 return BundleSize - OffsetInBundle;
211 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
214 MCFragment::~MCFragment() {
217 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
218 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
221 Parent->getFragmentList().push_back(this);
226 MCEncodedFragment::~MCEncodedFragment() {
231 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
236 const SmallVectorImpl<char> &MCCompressedFragment::getCompressedContents() const {
237 assert(getParent()->size() == 1 &&
238 "Only compress sections containing a single fragment");
239 if (CompressedContents.empty()) {
240 // FIXME: could be more efficient if we let zlib::compress append to a
241 // buffer rather than always from the start.
242 zlib::Status Success =
243 zlib::compress(StringRef(getContents().data(), getContents().size()),
246 assert(Success == zlib::StatusOK);
247 static const StringRef Magic = "ZLIB";
248 uint64_t Size = getContents().size();
249 if (sys::IsLittleEndianHost)
250 Size = sys::SwapByteOrder(Size);
251 CompressedContents.insert(CompressedContents.begin(),
252 Magic.size() + sizeof(Size));
253 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
254 std::copy(reinterpret_cast<char *>(&Size),
255 reinterpret_cast<char *>(&Size + 1),
256 CompressedContents.begin() + Magic.size());
258 return CompressedContents;
261 SmallVectorImpl<char> &MCCompressedFragment::getContents() {
262 assert(CompressedContents.empty() &&
263 "Fragment contents should not be altered after compression");
264 return MCDataFragment::getContents();
269 MCSectionData::MCSectionData() : Section(0) {}
271 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
272 : Section(&_Section),
273 Ordinal(~UINT32_C(0)),
275 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
276 HasInstructions(false)
279 A->getSectionList().push_back(this);
282 MCSectionData::iterator
283 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
284 if (Subsection == 0 && SubsectionFragmentMap.empty())
287 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
288 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
289 std::make_pair(Subsection, (MCFragment *)0));
290 bool ExactMatch = false;
291 if (MI != SubsectionFragmentMap.end()) {
292 ExactMatch = MI->first == Subsection;
297 if (MI == SubsectionFragmentMap.end())
301 if (!ExactMatch && Subsection != 0) {
302 // The GNU as documentation claims that subsections have an alignment of 4,
303 // although this appears not to be the case.
304 MCFragment *F = new MCDataFragment();
305 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
306 getFragmentList().insert(IP, F);
314 MCSymbolData::MCSymbolData() : Symbol(0) {}
316 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
317 uint64_t _Offset, MCAssembler *A)
318 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
319 IsExternal(false), IsPrivateExtern(false),
320 CommonSize(0), SymbolSize(0), CommonAlign(0),
324 A->getSymbolList().push_back(this);
329 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
330 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
332 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
333 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
334 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
335 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
338 MCAssembler::~MCAssembler() {
341 void MCAssembler::reset() {
346 IndirectSymbols.clear();
351 SubsectionsViaSymbols = false;
354 // reset objects owned by us
355 getBackend().reset();
356 getEmitter().reset();
358 getLOHContainer().reset();
361 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
362 // Non-temporary labels should always be visible to the linker.
363 if (!Symbol.isTemporary())
366 // Absolute temporary labels are never visible.
367 if (!Symbol.isInSection())
370 // Otherwise, check if the section requires symbols even for temporary labels.
371 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
374 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
375 // Linker visible symbols define atoms.
376 if (isSymbolLinkerVisible(SD->getSymbol()))
379 // Absolute and undefined symbols have no defining atom.
380 if (!SD->getFragment())
383 // Non-linker visible symbols in sections which can't be atomized have no
385 if (!getBackend().isSectionAtomizable(
386 SD->getFragment()->getParent()->getSection()))
389 // Otherwise, return the atom for the containing fragment.
390 return SD->getFragment()->getAtom();
393 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
394 const MCFixup &Fixup, const MCFragment *DF,
395 MCValue &Target, uint64_t &Value) const {
396 ++stats::evaluateFixup;
398 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
399 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
401 bool IsPCRel = Backend.getFixupKindInfo(
402 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
406 if (Target.getSymB()) {
408 } else if (!Target.getSymA()) {
411 const MCSymbolRefExpr *A = Target.getSymA();
412 const MCSymbol &SA = A->getSymbol();
413 if (A->getKind() != MCSymbolRefExpr::VK_None ||
414 SA.AliasedSymbol().isUndefined()) {
417 const MCSymbolData &DataA = getSymbolData(SA);
419 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
424 IsResolved = Target.isAbsolute();
427 Value = Target.getConstant();
429 if (const MCSymbolRefExpr *A = Target.getSymA()) {
430 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
432 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
434 if (const MCSymbolRefExpr *B = Target.getSymB()) {
435 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
437 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
441 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
442 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
443 assert((ShouldAlignPC ? IsPCRel : true) &&
444 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
447 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
449 // A number of ARM fixups in Thumb mode require that the effective PC
450 // address be determined as the 32-bit aligned version of the actual offset.
451 if (ShouldAlignPC) Offset &= ~0x3;
455 // Let the backend adjust the fixup value if necessary, including whether
456 // we need a relocation.
457 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
463 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
464 const MCFragment &F) const {
465 switch (F.getKind()) {
466 case MCFragment::FT_Data:
467 case MCFragment::FT_Relaxable:
468 case MCFragment::FT_CompactEncodedInst:
469 return cast<MCEncodedFragment>(F).getContents().size();
470 case MCFragment::FT_Compressed:
471 return cast<MCCompressedFragment>(F).getCompressedContents().size();
472 case MCFragment::FT_Fill:
473 return cast<MCFillFragment>(F).getSize();
475 case MCFragment::FT_LEB:
476 return cast<MCLEBFragment>(F).getContents().size();
478 case MCFragment::FT_Align: {
479 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
480 unsigned Offset = Layout.getFragmentOffset(&AF);
481 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
482 // If we are padding with nops, force the padding to be larger than the
484 if (Size > 0 && AF.hasEmitNops()) {
485 while (Size % getBackend().getMinimumNopSize())
486 Size += AF.getAlignment();
488 if (Size > AF.getMaxBytesToEmit())
493 case MCFragment::FT_Org: {
494 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
495 int64_t TargetLocation;
496 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
497 report_fatal_error("expected assembly-time absolute expression");
499 // FIXME: We need a way to communicate this error.
500 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
501 int64_t Size = TargetLocation - FragmentOffset;
502 if (Size < 0 || Size >= 0x40000000)
503 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
504 "' (at offset '" + Twine(FragmentOffset) + "')");
508 case MCFragment::FT_Dwarf:
509 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
510 case MCFragment::FT_DwarfFrame:
511 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
514 llvm_unreachable("invalid fragment kind");
517 void MCAsmLayout::layoutFragment(MCFragment *F) {
518 MCFragment *Prev = F->getPrevNode();
520 // We should never try to recompute something which is valid.
521 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
522 // We should never try to compute the fragment layout if its predecessor
524 assert((!Prev || isFragmentValid(Prev)) &&
525 "Attempt to compute fragment before its predecessor!");
527 ++stats::FragmentLayouts;
529 // Compute fragment offset and size.
531 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
534 LastValidFragment[F->getParent()] = F;
536 // If bundling is enabled and this fragment has instructions in it, it has to
537 // obey the bundling restrictions. With padding, we'll have:
542 // -------------------------------------
543 // Prev |##########| F |
544 // -------------------------------------
549 // The fragment's offset will point to after the padding, and its computed
550 // size won't include the padding.
552 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
553 assert(isa<MCEncodedFragment>(F) &&
554 "Only MCEncodedFragment implementations have instructions");
555 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
557 if (FSize > Assembler.getBundleAlignSize())
558 report_fatal_error("Fragment can't be larger than a bundle size");
560 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
561 if (RequiredBundlePadding > UINT8_MAX)
562 report_fatal_error("Padding cannot exceed 255 bytes");
563 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
564 F->Offset += RequiredBundlePadding;
568 /// \brief Write the contents of a fragment to the given object writer. Expects
569 /// a MCEncodedFragment.
570 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
571 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
572 OW->WriteBytes(EF.getContents());
575 /// \brief Write the fragment \p F to the output file.
576 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
577 const MCFragment &F) {
578 MCObjectWriter *OW = &Asm.getWriter();
580 // FIXME: Embed in fragments instead?
581 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
583 // Should NOP padding be written out before this fragment?
584 unsigned BundlePadding = F.getBundlePadding();
585 if (BundlePadding > 0) {
586 assert(Asm.isBundlingEnabled() &&
587 "Writing bundle padding with disabled bundling");
588 assert(F.hasInstructions() &&
589 "Writing bundle padding for a fragment without instructions");
591 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
592 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
593 // If the padding itself crosses a bundle boundary, it must be emitted
594 // in 2 pieces, since even nop instructions must not cross boundaries.
595 // v--------------v <- BundleAlignSize
596 // v---------v <- BundlePadding
597 // ----------------------------
598 // | Prev |####|####| F |
599 // ----------------------------
600 // ^-------------------^ <- TotalLength
601 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
602 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
603 report_fatal_error("unable to write NOP sequence of " +
604 Twine(DistanceToBoundary) + " bytes");
605 BundlePadding -= DistanceToBoundary;
607 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
608 report_fatal_error("unable to write NOP sequence of " +
609 Twine(BundlePadding) + " bytes");
612 // This variable (and its dummy usage) is to participate in the assert at
613 // the end of the function.
614 uint64_t Start = OW->getStream().tell();
617 ++stats::EmittedFragments;
619 switch (F.getKind()) {
620 case MCFragment::FT_Align: {
621 ++stats::EmittedAlignFragments;
622 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
623 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
625 uint64_t Count = FragmentSize / AF.getValueSize();
627 // FIXME: This error shouldn't actually occur (the front end should emit
628 // multiple .align directives to enforce the semantics it wants), but is
629 // severe enough that we want to report it. How to handle this?
630 if (Count * AF.getValueSize() != FragmentSize)
631 report_fatal_error("undefined .align directive, value size '" +
632 Twine(AF.getValueSize()) +
633 "' is not a divisor of padding size '" +
634 Twine(FragmentSize) + "'");
636 // See if we are aligning with nops, and if so do that first to try to fill
637 // the Count bytes. Then if that did not fill any bytes or there are any
638 // bytes left to fill use the Value and ValueSize to fill the rest.
639 // If we are aligning with nops, ask that target to emit the right data.
640 if (AF.hasEmitNops()) {
641 if (!Asm.getBackend().writeNopData(Count, OW))
642 report_fatal_error("unable to write nop sequence of " +
643 Twine(Count) + " bytes");
647 // Otherwise, write out in multiples of the value size.
648 for (uint64_t i = 0; i != Count; ++i) {
649 switch (AF.getValueSize()) {
650 default: llvm_unreachable("Invalid size!");
651 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
652 case 2: OW->Write16(uint16_t(AF.getValue())); break;
653 case 4: OW->Write32(uint32_t(AF.getValue())); break;
654 case 8: OW->Write64(uint64_t(AF.getValue())); break;
660 case MCFragment::FT_Compressed:
661 ++stats::EmittedDataFragments;
662 OW->WriteBytes(cast<MCCompressedFragment>(F).getCompressedContents());
665 case MCFragment::FT_Data:
666 ++stats::EmittedDataFragments;
667 writeFragmentContents(F, OW);
670 case MCFragment::FT_Relaxable:
671 ++stats::EmittedRelaxableFragments;
672 writeFragmentContents(F, OW);
675 case MCFragment::FT_CompactEncodedInst:
676 ++stats::EmittedCompactEncodedInstFragments;
677 writeFragmentContents(F, OW);
680 case MCFragment::FT_Fill: {
681 ++stats::EmittedFillFragments;
682 const MCFillFragment &FF = cast<MCFillFragment>(F);
684 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
686 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
687 switch (FF.getValueSize()) {
688 default: llvm_unreachable("Invalid size!");
689 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
690 case 2: OW->Write16(uint16_t(FF.getValue())); break;
691 case 4: OW->Write32(uint32_t(FF.getValue())); break;
692 case 8: OW->Write64(uint64_t(FF.getValue())); break;
698 case MCFragment::FT_LEB: {
699 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
700 OW->WriteBytes(LF.getContents().str());
704 case MCFragment::FT_Org: {
705 ++stats::EmittedOrgFragments;
706 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
708 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
709 OW->Write8(uint8_t(OF.getValue()));
714 case MCFragment::FT_Dwarf: {
715 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
716 OW->WriteBytes(OF.getContents().str());
719 case MCFragment::FT_DwarfFrame: {
720 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
721 OW->WriteBytes(CF.getContents().str());
726 assert(OW->getStream().tell() - Start == FragmentSize &&
727 "The stream should advance by fragment size");
730 void MCAssembler::writeSectionData(const MCSectionData *SD,
731 const MCAsmLayout &Layout) const {
732 // Ignore virtual sections.
733 if (SD->getSection().isVirtualSection()) {
734 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
736 // Check that contents are only things legal inside a virtual section.
737 for (MCSectionData::const_iterator it = SD->begin(),
738 ie = SD->end(); it != ie; ++it) {
739 switch (it->getKind()) {
740 default: llvm_unreachable("Invalid fragment in virtual section!");
741 case MCFragment::FT_Compressed:
742 case MCFragment::FT_Data: {
743 // Check that we aren't trying to write a non-zero contents (or fixups)
744 // into a virtual section. This is to support clients which use standard
745 // directives to fill the contents of virtual sections.
746 const MCDataFragment &DF = cast<MCDataFragment>(*it);
747 assert(DF.fixup_begin() == DF.fixup_end() &&
748 "Cannot have fixups in virtual section!");
749 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
750 assert(DF.getContents()[i] == 0 &&
751 "Invalid data value for virtual section!");
754 case MCFragment::FT_Align:
755 // Check that we aren't trying to write a non-zero value into a virtual
757 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
758 cast<MCAlignFragment>(it)->getValue() == 0) &&
759 "Invalid align in virtual section!");
761 case MCFragment::FT_Fill:
762 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
763 cast<MCFillFragment>(it)->getValue() == 0) &&
764 "Invalid fill in virtual section!");
772 uint64_t Start = getWriter().getStream().tell();
775 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
777 writeFragment(*this, Layout, *it);
779 assert(getWriter().getStream().tell() - Start ==
780 Layout.getSectionAddressSize(SD));
783 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
785 const MCFixup &Fixup) {
786 // Evaluate the fixup.
789 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
790 MCFixupKindInfo::FKF_IsPCRel;
791 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
792 // The fixup was unresolved, we need a relocation. Inform the object
793 // writer of the relocation, and give it an opportunity to adjust the
794 // fixup value if need be.
795 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
798 return std::make_pair(FixedValue, IsPCRel);
801 void MCAssembler::Finish() {
802 DEBUG_WITH_TYPE("mc-dump", {
803 llvm::errs() << "assembler backend - pre-layout\n--\n";
806 // Create the layout object.
807 MCAsmLayout Layout(*this);
809 // Create dummy fragments and assign section ordinals.
810 unsigned SectionIndex = 0;
811 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
812 // Create dummy fragments to eliminate any empty sections, this simplifies
814 if (it->getFragmentList().empty())
815 new MCDataFragment(it);
817 it->setOrdinal(SectionIndex++);
820 // Assign layout order indices to sections and fragments.
821 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
822 MCSectionData *SD = Layout.getSectionOrder()[i];
823 SD->setLayoutOrder(i);
825 unsigned FragmentIndex = 0;
826 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
827 iFrag != iFragEnd; ++iFrag)
828 iFrag->setLayoutOrder(FragmentIndex++);
831 // Layout until everything fits.
832 while (layoutOnce(Layout))
835 DEBUG_WITH_TYPE("mc-dump", {
836 llvm::errs() << "assembler backend - post-relaxation\n--\n";
839 // Finalize the layout, including fragment lowering.
840 finishLayout(Layout);
842 DEBUG_WITH_TYPE("mc-dump", {
843 llvm::errs() << "assembler backend - final-layout\n--\n";
846 uint64_t StartOffset = OS.tell();
848 // Allow the object writer a chance to perform post-layout binding (for
849 // example, to set the index fields in the symbol data).
850 getWriter().ExecutePostLayoutBinding(*this, Layout);
852 // Evaluate and apply the fixups, generating relocation entries as necessary.
853 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
854 for (MCSectionData::iterator it2 = it->begin(),
855 ie2 = it->end(); it2 != ie2; ++it2) {
856 MCEncodedFragmentWithFixups *F =
857 dyn_cast<MCEncodedFragmentWithFixups>(it2);
859 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
860 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
861 MCFixup &Fixup = *it3;
864 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
865 getBackend().applyFixup(Fixup, F->getContents().data(),
866 F->getContents().size(), FixedValue, IsPCRel);
872 // Write the object file.
873 getWriter().WriteObject(*this, Layout);
875 stats::ObjectBytes += OS.tell() - StartOffset;
878 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
879 const MCRelaxableFragment *DF,
880 const MCAsmLayout &Layout) const {
881 // If we cannot resolve the fixup value, it requires relaxation.
884 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
887 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
890 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
891 const MCAsmLayout &Layout) const {
892 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
893 // are intentionally pushing out inst fragments, or because we relaxed a
894 // previous instruction to one that doesn't need relaxation.
895 if (!getBackend().mayNeedRelaxation(F->getInst()))
898 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
899 ie = F->fixup_end(); it != ie; ++it)
900 if (fixupNeedsRelaxation(*it, F, Layout))
906 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
907 MCRelaxableFragment &F) {
908 if (!fragmentNeedsRelaxation(&F, Layout))
911 ++stats::RelaxedInstructions;
913 // FIXME-PERF: We could immediately lower out instructions if we can tell
914 // they are fully resolved, to avoid retesting on later passes.
916 // Relax the fragment.
919 getBackend().relaxInstruction(F.getInst(), Relaxed);
921 // Encode the new instruction.
923 // FIXME-PERF: If it matters, we could let the target do this. It can
924 // probably do so more efficiently in many cases.
925 SmallVector<MCFixup, 4> Fixups;
926 SmallString<256> Code;
927 raw_svector_ostream VecOS(Code);
928 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
931 // Update the fragment.
933 F.getContents() = Code;
934 F.getFixups() = Fixups;
939 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
941 uint64_t OldSize = LF.getContents().size();
942 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
945 SmallString<8> &Data = LF.getContents();
947 raw_svector_ostream OSE(Data);
949 encodeSLEB128(Value, OSE);
951 encodeULEB128(Value, OSE);
953 return OldSize != LF.getContents().size();
956 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
957 MCDwarfLineAddrFragment &DF) {
958 MCContext &Context = Layout.getAssembler().getContext();
959 int64_t AddrDelta = 0;
960 uint64_t OldSize = DF.getContents().size();
961 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
965 LineDelta = DF.getLineDelta();
966 SmallString<8> &Data = DF.getContents();
968 raw_svector_ostream OSE(Data);
969 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
971 return OldSize != Data.size();
974 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
975 MCDwarfCallFrameFragment &DF) {
976 MCContext &Context = Layout.getAssembler().getContext();
977 int64_t AddrDelta = 0;
978 uint64_t OldSize = DF.getContents().size();
979 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
982 SmallString<8> &Data = DF.getContents();
984 raw_svector_ostream OSE(Data);
985 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
987 return OldSize != Data.size();
990 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
991 // Holds the first fragment which needed relaxing during this layout. It will
992 // remain NULL if none were relaxed.
993 // When a fragment is relaxed, all the fragments following it should get
994 // invalidated because their offset is going to change.
995 MCFragment *FirstRelaxedFragment = NULL;
997 // Attempt to relax all the fragments in the section.
998 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
999 // Check if this is a fragment that needs relaxation.
1000 bool RelaxedFrag = false;
1001 switch(I->getKind()) {
1004 case MCFragment::FT_Relaxable:
1005 assert(!getRelaxAll() &&
1006 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1007 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1009 case MCFragment::FT_Dwarf:
1010 RelaxedFrag = relaxDwarfLineAddr(Layout,
1011 *cast<MCDwarfLineAddrFragment>(I));
1013 case MCFragment::FT_DwarfFrame:
1015 relaxDwarfCallFrameFragment(Layout,
1016 *cast<MCDwarfCallFrameFragment>(I));
1018 case MCFragment::FT_LEB:
1019 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1022 if (RelaxedFrag && !FirstRelaxedFragment)
1023 FirstRelaxedFragment = I;
1025 if (FirstRelaxedFragment) {
1026 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1032 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1033 ++stats::RelaxationSteps;
1035 bool WasRelaxed = false;
1036 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1037 MCSectionData &SD = *it;
1038 while (layoutSectionOnce(Layout, SD))
1045 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1046 // The layout is done. Mark every fragment as valid.
1047 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1048 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1052 // Debugging methods
1056 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1057 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1058 << " Value:" << *AF.getValue()
1059 << " Kind:" << AF.getKind() << ">";
1065 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1066 void MCFragment::dump() {
1067 raw_ostream &OS = llvm::errs();
1070 switch (getKind()) {
1071 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1072 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1073 case MCFragment::FT_Compressed:
1074 OS << "MCCompressedFragment"; break;
1075 case MCFragment::FT_CompactEncodedInst:
1076 OS << "MCCompactEncodedInstFragment"; break;
1077 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1078 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1079 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1080 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1081 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1082 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1085 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1086 << " Offset:" << Offset
1087 << " HasInstructions:" << hasInstructions()
1088 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1090 switch (getKind()) {
1091 case MCFragment::FT_Align: {
1092 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1093 if (AF->hasEmitNops())
1094 OS << " (emit nops)";
1096 OS << " Alignment:" << AF->getAlignment()
1097 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1098 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1101 case MCFragment::FT_Compressed:
1102 case MCFragment::FT_Data: {
1103 const MCDataFragment *DF = cast<MCDataFragment>(this);
1105 OS << " Contents:[";
1106 const SmallVectorImpl<char> &Contents = DF->getContents();
1107 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1109 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1111 OS << "] (" << Contents.size() << " bytes)";
1113 if (DF->fixup_begin() != DF->fixup_end()) {
1116 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1117 ie = DF->fixup_end(); it != ie; ++it) {
1118 if (it != DF->fixup_begin()) OS << ",\n ";
1125 case MCFragment::FT_CompactEncodedInst: {
1126 const MCCompactEncodedInstFragment *CEIF =
1127 cast<MCCompactEncodedInstFragment>(this);
1129 OS << " Contents:[";
1130 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1131 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1133 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1135 OS << "] (" << Contents.size() << " bytes)";
1138 case MCFragment::FT_Fill: {
1139 const MCFillFragment *FF = cast<MCFillFragment>(this);
1140 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1141 << " Size:" << FF->getSize();
1144 case MCFragment::FT_Relaxable: {
1145 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1148 F->getInst().dump_pretty(OS);
1151 case MCFragment::FT_Org: {
1152 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1154 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1157 case MCFragment::FT_Dwarf: {
1158 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1160 OS << " AddrDelta:" << OF->getAddrDelta()
1161 << " LineDelta:" << OF->getLineDelta();
1164 case MCFragment::FT_DwarfFrame: {
1165 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1167 OS << " AddrDelta:" << CF->getAddrDelta();
1170 case MCFragment::FT_LEB: {
1171 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1173 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1180 void MCSectionData::dump() {
1181 raw_ostream &OS = llvm::errs();
1183 OS << "<MCSectionData";
1184 OS << " Alignment:" << getAlignment()
1185 << " Fragments:[\n ";
1186 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1187 if (it != begin()) OS << ",\n ";
1193 void MCSymbolData::dump() {
1194 raw_ostream &OS = llvm::errs();
1196 OS << "<MCSymbolData Symbol:" << getSymbol()
1197 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1198 << " Flags:" << getFlags() << " Index:" << getIndex();
1200 OS << " (common, size:" << getCommonSize()
1201 << " align: " << getCommonAlignment() << ")";
1203 OS << " (external)";
1204 if (isPrivateExtern())
1205 OS << " (private extern)";
1209 void MCAssembler::dump() {
1210 raw_ostream &OS = llvm::errs();
1212 OS << "<MCAssembler\n";
1213 OS << " Sections:[\n ";
1214 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1215 if (it != begin()) OS << ",\n ";
1221 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1222 if (it != symbol_begin()) OS << ",\n ";
1229 // anchors for MC*Fragment vtables
1230 void MCEncodedFragment::anchor() { }
1231 void MCEncodedFragmentWithFixups::anchor() { }
1232 void MCDataFragment::anchor() { }
1233 void MCCompactEncodedInstFragment::anchor() { }
1234 void MCRelaxableFragment::anchor() { }
1235 void MCAlignFragment::anchor() { }
1236 void MCFillFragment::anchor() { }
1237 void MCOrgFragment::anchor() { }
1238 void MCLEBFragment::anchor() { }
1239 void MCDwarfLineAddrFragment::anchor() { }
1240 void MCDwarfCallFrameFragment::anchor() { }