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) {
270 MCAssembler::~MCAssembler() {
273 void MCAssembler::reset() {
278 IndirectSymbols.clear();
283 SubsectionsViaSymbols = false;
285 // reset objects owned by us
286 getBackend().reset();
287 getEmitter().reset();
291 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
292 // Non-temporary labels should always be visible to the linker.
293 if (!Symbol.isTemporary())
296 // Absolute temporary labels are never visible.
297 if (!Symbol.isInSection())
300 // Otherwise, check if the section requires symbols even for temporary labels.
301 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
304 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
305 // Linker visible symbols define atoms.
306 if (isSymbolLinkerVisible(SD->getSymbol()))
309 // Absolute and undefined symbols have no defining atom.
310 if (!SD->getFragment())
313 // Non-linker visible symbols in sections which can't be atomized have no
315 if (!getBackend().isSectionAtomizable(
316 SD->getFragment()->getParent()->getSection()))
319 // Otherwise, return the atom for the containing fragment.
320 return SD->getFragment()->getAtom();
323 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
324 const MCFixup &Fixup, const MCFragment *DF,
325 MCValue &Target, uint64_t &Value) const {
326 ++stats::evaluateFixup;
328 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
329 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
331 bool IsPCRel = Backend.getFixupKindInfo(
332 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
336 if (Target.getSymB()) {
338 } else if (!Target.getSymA()) {
341 const MCSymbolRefExpr *A = Target.getSymA();
342 const MCSymbol &SA = A->getSymbol();
343 if (A->getKind() != MCSymbolRefExpr::VK_None ||
344 SA.AliasedSymbol().isUndefined()) {
347 const MCSymbolData &DataA = getSymbolData(SA);
349 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
354 IsResolved = Target.isAbsolute();
357 Value = Target.getConstant();
359 if (const MCSymbolRefExpr *A = Target.getSymA()) {
360 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
362 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
364 if (const MCSymbolRefExpr *B = Target.getSymB()) {
365 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
367 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
371 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
372 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
373 assert((ShouldAlignPC ? IsPCRel : true) &&
374 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
377 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
379 // A number of ARM fixups in Thumb mode require that the effective PC
380 // address be determined as the 32-bit aligned version of the actual offset.
381 if (ShouldAlignPC) Offset &= ~0x3;
385 // Let the backend adjust the fixup value if necessary, including whether
386 // we need a relocation.
387 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
393 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
394 const MCFragment &F) const {
395 switch (F.getKind()) {
396 case MCFragment::FT_Data:
397 case MCFragment::FT_Relaxable:
398 case MCFragment::FT_CompactEncodedInst:
399 return cast<MCEncodedFragment>(F).getContents().size();
400 case MCFragment::FT_Fill:
401 return cast<MCFillFragment>(F).getSize();
403 case MCFragment::FT_LEB:
404 return cast<MCLEBFragment>(F).getContents().size();
406 case MCFragment::FT_Align: {
407 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
408 unsigned Offset = Layout.getFragmentOffset(&AF);
409 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
410 // If we are padding with nops, force the padding to be larger than the
412 if (Size > 0 && AF.hasEmitNops()) {
413 while (Size % getBackend().getMinimumNopSize())
414 Size += AF.getAlignment();
416 if (Size > AF.getMaxBytesToEmit())
421 case MCFragment::FT_Org: {
422 MCOrgFragment &OF = cast<MCOrgFragment>(F);
423 int64_t TargetLocation;
424 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
425 report_fatal_error("expected assembly-time absolute expression");
427 // FIXME: We need a way to communicate this error.
428 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
429 int64_t Size = TargetLocation - FragmentOffset;
430 if (Size < 0 || Size >= 0x40000000)
431 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
432 "' (at offset '" + Twine(FragmentOffset) + "')");
436 case MCFragment::FT_Dwarf:
437 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
438 case MCFragment::FT_DwarfFrame:
439 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
442 llvm_unreachable("invalid fragment kind");
445 void MCAsmLayout::layoutFragment(MCFragment *F) {
446 MCFragment *Prev = F->getPrevNode();
448 // We should never try to recompute something which is valid.
449 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
450 // We should never try to compute the fragment layout if its predecessor
452 assert((!Prev || isFragmentValid(Prev)) &&
453 "Attempt to compute fragment before its predecessor!");
455 ++stats::FragmentLayouts;
457 // Compute fragment offset and size.
459 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
462 LastValidFragment[F->getParent()] = F;
464 // If bundling is enabled and this fragment has instructions in it, it has to
465 // obey the bundling restrictions. With padding, we'll have:
470 // -------------------------------------
471 // Prev |##########| F |
472 // -------------------------------------
477 // The fragment's offset will point to after the padding, and its computed
478 // size won't include the padding.
480 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
481 assert(isa<MCEncodedFragment>(F) &&
482 "Only MCEncodedFragment implementations have instructions");
483 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
485 if (FSize > Assembler.getBundleAlignSize())
486 report_fatal_error("Fragment can't be larger than a bundle size");
488 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
489 if (RequiredBundlePadding > UINT8_MAX)
490 report_fatal_error("Padding cannot exceed 255 bytes");
491 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
492 F->Offset += RequiredBundlePadding;
496 /// \brief Write the contents of a fragment to the given object writer. Expects
497 /// a MCEncodedFragment.
498 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
499 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
500 OW->WriteBytes(EF.getContents());
503 /// \brief Write the fragment \p F to the output file.
504 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
505 const MCFragment &F) {
506 MCObjectWriter *OW = &Asm.getWriter();
508 // Should NOP padding be written out before this fragment?
509 unsigned BundlePadding = F.getBundlePadding();
510 if (BundlePadding > 0) {
511 assert(Asm.isBundlingEnabled() &&
512 "Writing bundle padding with disabled bundling");
513 assert(F.hasInstructions() &&
514 "Writing bundle padding for a fragment without instructions");
516 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
517 report_fatal_error("unable to write NOP sequence of " +
518 Twine(BundlePadding) + " bytes");
521 // This variable (and its dummy usage) is to participate in the assert at
522 // the end of the function.
523 uint64_t Start = OW->getStream().tell();
526 ++stats::EmittedFragments;
528 // FIXME: Embed in fragments instead?
529 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
530 switch (F.getKind()) {
531 case MCFragment::FT_Align: {
532 ++stats::EmittedAlignFragments;
533 MCAlignFragment &AF = cast<MCAlignFragment>(F);
534 uint64_t Count = FragmentSize / AF.getValueSize();
536 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
538 // FIXME: This error shouldn't actually occur (the front end should emit
539 // multiple .align directives to enforce the semantics it wants), but is
540 // severe enough that we want to report it. How to handle this?
541 if (Count * AF.getValueSize() != FragmentSize)
542 report_fatal_error("undefined .align directive, value size '" +
543 Twine(AF.getValueSize()) +
544 "' is not a divisor of padding size '" +
545 Twine(FragmentSize) + "'");
547 // See if we are aligning with nops, and if so do that first to try to fill
548 // the Count bytes. Then if that did not fill any bytes or there are any
549 // bytes left to fill use the Value and ValueSize to fill the rest.
550 // If we are aligning with nops, ask that target to emit the right data.
551 if (AF.hasEmitNops()) {
552 if (!Asm.getBackend().writeNopData(Count, OW))
553 report_fatal_error("unable to write nop sequence of " +
554 Twine(Count) + " bytes");
558 // Otherwise, write out in multiples of the value size.
559 for (uint64_t i = 0; i != Count; ++i) {
560 switch (AF.getValueSize()) {
561 default: llvm_unreachable("Invalid size!");
562 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
563 case 2: OW->Write16(uint16_t(AF.getValue())); break;
564 case 4: OW->Write32(uint32_t(AF.getValue())); break;
565 case 8: OW->Write64(uint64_t(AF.getValue())); break;
571 case MCFragment::FT_Data:
572 ++stats::EmittedDataFragments;
573 writeFragmentContents(F, OW);
576 case MCFragment::FT_Relaxable:
577 ++stats::EmittedRelaxableFragments;
578 writeFragmentContents(F, OW);
581 case MCFragment::FT_CompactEncodedInst:
582 ++stats::EmittedCompactEncodedInstFragments;
583 writeFragmentContents(F, OW);
586 case MCFragment::FT_Fill: {
587 ++stats::EmittedFillFragments;
588 MCFillFragment &FF = cast<MCFillFragment>(F);
590 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
592 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
593 switch (FF.getValueSize()) {
594 default: llvm_unreachable("Invalid size!");
595 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
596 case 2: OW->Write16(uint16_t(FF.getValue())); break;
597 case 4: OW->Write32(uint32_t(FF.getValue())); break;
598 case 8: OW->Write64(uint64_t(FF.getValue())); break;
604 case MCFragment::FT_LEB: {
605 MCLEBFragment &LF = cast<MCLEBFragment>(F);
606 OW->WriteBytes(LF.getContents().str());
610 case MCFragment::FT_Org: {
611 ++stats::EmittedOrgFragments;
612 MCOrgFragment &OF = cast<MCOrgFragment>(F);
614 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
615 OW->Write8(uint8_t(OF.getValue()));
620 case MCFragment::FT_Dwarf: {
621 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
622 OW->WriteBytes(OF.getContents().str());
625 case MCFragment::FT_DwarfFrame: {
626 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
627 OW->WriteBytes(CF.getContents().str());
632 assert(OW->getStream().tell() - Start == FragmentSize &&
633 "The stream should advance by fragment size");
636 void MCAssembler::writeSectionData(const MCSectionData *SD,
637 const MCAsmLayout &Layout) const {
638 // Ignore virtual sections.
639 if (SD->getSection().isVirtualSection()) {
640 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
642 // Check that contents are only things legal inside a virtual section.
643 for (MCSectionData::const_iterator it = SD->begin(),
644 ie = SD->end(); it != ie; ++it) {
645 switch (it->getKind()) {
646 default: llvm_unreachable("Invalid fragment in virtual section!");
647 case MCFragment::FT_Data: {
648 // Check that we aren't trying to write a non-zero contents (or fixups)
649 // into a virtual section. This is to support clients which use standard
650 // directives to fill the contents of virtual sections.
651 MCDataFragment &DF = cast<MCDataFragment>(*it);
652 assert(DF.fixup_begin() == DF.fixup_end() &&
653 "Cannot have fixups in virtual section!");
654 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
655 assert(DF.getContents()[i] == 0 &&
656 "Invalid data value for virtual section!");
659 case MCFragment::FT_Align:
660 // Check that we aren't trying to write a non-zero value into a virtual
662 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
663 !cast<MCAlignFragment>(it)->getValue()) &&
664 "Invalid align in virtual section!");
666 case MCFragment::FT_Fill:
667 assert(!cast<MCFillFragment>(it)->getValueSize() &&
668 "Invalid fill in virtual section!");
676 uint64_t Start = getWriter().getStream().tell();
679 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
681 writeFragment(*this, Layout, *it);
683 assert(getWriter().getStream().tell() - Start ==
684 Layout.getSectionAddressSize(SD));
688 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
690 const MCFixup &Fixup) {
691 // Evaluate the fixup.
694 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
695 // The fixup was unresolved, we need a relocation. Inform the object
696 // writer of the relocation, and give it an opportunity to adjust the
697 // fixup value if need be.
698 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
703 void MCAssembler::Finish() {
704 DEBUG_WITH_TYPE("mc-dump", {
705 llvm::errs() << "assembler backend - pre-layout\n--\n";
708 // Create the layout object.
709 MCAsmLayout Layout(*this);
711 // Create dummy fragments and assign section ordinals.
712 unsigned SectionIndex = 0;
713 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
714 // Create dummy fragments to eliminate any empty sections, this simplifies
716 if (it->getFragmentList().empty())
717 new MCDataFragment(it);
719 it->setOrdinal(SectionIndex++);
722 // Assign layout order indices to sections and fragments.
723 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
724 MCSectionData *SD = Layout.getSectionOrder()[i];
725 SD->setLayoutOrder(i);
727 unsigned FragmentIndex = 0;
728 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
729 iFrag != iFragEnd; ++iFrag)
730 iFrag->setLayoutOrder(FragmentIndex++);
733 // Layout until everything fits.
734 while (layoutOnce(Layout))
737 DEBUG_WITH_TYPE("mc-dump", {
738 llvm::errs() << "assembler backend - post-relaxation\n--\n";
741 // Finalize the layout, including fragment lowering.
742 finishLayout(Layout);
744 DEBUG_WITH_TYPE("mc-dump", {
745 llvm::errs() << "assembler backend - final-layout\n--\n";
748 uint64_t StartOffset = OS.tell();
750 // Allow the object writer a chance to perform post-layout binding (for
751 // example, to set the index fields in the symbol data).
752 getWriter().ExecutePostLayoutBinding(*this, Layout);
754 // Evaluate and apply the fixups, generating relocation entries as necessary.
755 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
756 for (MCSectionData::iterator it2 = it->begin(),
757 ie2 = it->end(); it2 != ie2; ++it2) {
758 MCEncodedFragmentWithFixups *F =
759 dyn_cast<MCEncodedFragmentWithFixups>(it2);
761 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
762 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
763 MCFixup &Fixup = *it3;
764 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
765 getBackend().applyFixup(Fixup, F->getContents().data(),
766 F->getContents().size(), FixedValue);
772 // Write the object file.
773 getWriter().WriteObject(*this, Layout);
775 stats::ObjectBytes += OS.tell() - StartOffset;
778 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
779 const MCRelaxableFragment *DF,
780 const MCAsmLayout &Layout) const {
781 // If we cannot resolve the fixup value, it requires relaxation.
784 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
787 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
790 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
791 const MCAsmLayout &Layout) const {
792 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
793 // are intentionally pushing out inst fragments, or because we relaxed a
794 // previous instruction to one that doesn't need relaxation.
795 if (!getBackend().mayNeedRelaxation(F->getInst()))
798 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
799 ie = F->fixup_end(); it != ie; ++it)
800 if (fixupNeedsRelaxation(*it, F, Layout))
806 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
807 MCRelaxableFragment &F) {
808 if (!fragmentNeedsRelaxation(&F, Layout))
811 ++stats::RelaxedInstructions;
813 // FIXME-PERF: We could immediately lower out instructions if we can tell
814 // they are fully resolved, to avoid retesting on later passes.
816 // Relax the fragment.
819 getBackend().relaxInstruction(F.getInst(), Relaxed);
821 // Encode the new instruction.
823 // FIXME-PERF: If it matters, we could let the target do this. It can
824 // probably do so more efficiently in many cases.
825 SmallVector<MCFixup, 4> Fixups;
826 SmallString<256> Code;
827 raw_svector_ostream VecOS(Code);
828 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
831 // Update the fragment.
833 F.getContents() = Code;
834 F.getFixups() = Fixups;
839 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
841 uint64_t OldSize = LF.getContents().size();
842 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
845 SmallString<8> &Data = LF.getContents();
847 raw_svector_ostream OSE(Data);
849 encodeSLEB128(Value, OSE);
851 encodeULEB128(Value, OSE);
853 return OldSize != LF.getContents().size();
856 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
857 MCDwarfLineAddrFragment &DF) {
858 int64_t AddrDelta = 0;
859 uint64_t OldSize = DF.getContents().size();
860 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
864 LineDelta = DF.getLineDelta();
865 SmallString<8> &Data = DF.getContents();
867 raw_svector_ostream OSE(Data);
868 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
870 return OldSize != Data.size();
873 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
874 MCDwarfCallFrameFragment &DF) {
875 int64_t AddrDelta = 0;
876 uint64_t OldSize = DF.getContents().size();
877 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
880 SmallString<8> &Data = DF.getContents();
882 raw_svector_ostream OSE(Data);
883 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
885 return OldSize != Data.size();
888 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
889 // Holds the first fragment which needed relaxing during this layout. It will
890 // remain NULL if none were relaxed.
891 // When a fragment is relaxed, all the fragments following it should get
892 // invalidated because their offset is going to change.
893 MCFragment *FirstRelaxedFragment = NULL;
895 // Attempt to relax all the fragments in the section.
896 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
897 // Check if this is a fragment that needs relaxation.
898 bool RelaxedFrag = false;
899 switch(I->getKind()) {
902 case MCFragment::FT_Relaxable:
903 assert(!getRelaxAll() &&
904 "Did not expect a MCRelaxableFragment in RelaxAll mode");
905 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
907 case MCFragment::FT_Dwarf:
908 RelaxedFrag = relaxDwarfLineAddr(Layout,
909 *cast<MCDwarfLineAddrFragment>(I));
911 case MCFragment::FT_DwarfFrame:
913 relaxDwarfCallFrameFragment(Layout,
914 *cast<MCDwarfCallFrameFragment>(I));
916 case MCFragment::FT_LEB:
917 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
920 if (RelaxedFrag && !FirstRelaxedFragment)
921 FirstRelaxedFragment = I;
923 if (FirstRelaxedFragment) {
924 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
930 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
931 ++stats::RelaxationSteps;
933 bool WasRelaxed = false;
934 for (iterator it = begin(), ie = end(); it != ie; ++it) {
935 MCSectionData &SD = *it;
936 while (layoutSectionOnce(Layout, SD))
943 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
944 // The layout is done. Mark every fragment as valid.
945 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
946 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
954 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
955 OS << "<MCFixup" << " Offset:" << AF.getOffset()
956 << " Value:" << *AF.getValue()
957 << " Kind:" << AF.getKind() << ">";
963 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
964 void MCFragment::dump() {
965 raw_ostream &OS = llvm::errs();
969 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
970 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
971 case MCFragment::FT_CompactEncodedInst:
972 OS << "MCCompactEncodedInstFragment"; break;
973 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
974 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
975 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
976 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
977 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
978 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
981 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
982 << " Offset:" << Offset
983 << " HasInstructions:" << hasInstructions()
984 << " BundlePadding:" << getBundlePadding() << ">";
987 case MCFragment::FT_Align: {
988 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
989 if (AF->hasEmitNops())
990 OS << " (emit nops)";
992 OS << " Alignment:" << AF->getAlignment()
993 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
994 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
997 case MCFragment::FT_Data: {
998 const MCDataFragment *DF = cast<MCDataFragment>(this);
1000 OS << " Contents:[";
1001 const SmallVectorImpl<char> &Contents = DF->getContents();
1002 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1004 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1006 OS << "] (" << Contents.size() << " bytes)";
1008 if (DF->fixup_begin() != DF->fixup_end()) {
1011 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1012 ie = DF->fixup_end(); it != ie; ++it) {
1013 if (it != DF->fixup_begin()) OS << ",\n ";
1020 case MCFragment::FT_CompactEncodedInst: {
1021 const MCCompactEncodedInstFragment *CEIF =
1022 cast<MCCompactEncodedInstFragment>(this);
1024 OS << " Contents:[";
1025 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1026 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1028 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1030 OS << "] (" << Contents.size() << " bytes)";
1033 case MCFragment::FT_Fill: {
1034 const MCFillFragment *FF = cast<MCFillFragment>(this);
1035 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1036 << " Size:" << FF->getSize();
1039 case MCFragment::FT_Relaxable: {
1040 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1043 F->getInst().dump_pretty(OS);
1046 case MCFragment::FT_Org: {
1047 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1049 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1052 case MCFragment::FT_Dwarf: {
1053 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1055 OS << " AddrDelta:" << OF->getAddrDelta()
1056 << " LineDelta:" << OF->getLineDelta();
1059 case MCFragment::FT_DwarfFrame: {
1060 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1062 OS << " AddrDelta:" << CF->getAddrDelta();
1065 case MCFragment::FT_LEB: {
1066 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1068 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1075 void MCSectionData::dump() {
1076 raw_ostream &OS = llvm::errs();
1078 OS << "<MCSectionData";
1079 OS << " Alignment:" << getAlignment()
1080 << " Fragments:[\n ";
1081 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1082 if (it != begin()) OS << ",\n ";
1088 void MCSymbolData::dump() {
1089 raw_ostream &OS = llvm::errs();
1091 OS << "<MCSymbolData Symbol:" << getSymbol()
1092 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1093 << " Flags:" << getFlags() << " Index:" << getIndex();
1095 OS << " (common, size:" << getCommonSize()
1096 << " align: " << getCommonAlignment() << ")";
1098 OS << " (external)";
1099 if (isPrivateExtern())
1100 OS << " (private extern)";
1104 void MCAssembler::dump() {
1105 raw_ostream &OS = llvm::errs();
1107 OS << "<MCAssembler\n";
1108 OS << " Sections:[\n ";
1109 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1110 if (it != begin()) OS << ",\n ";
1116 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1117 if (it != symbol_begin()) OS << ",\n ";
1124 // anchors for MC*Fragment vtables
1125 void MCEncodedFragment::anchor() { }
1126 void MCEncodedFragmentWithFixups::anchor() { }
1127 void MCDataFragment::anchor() { }
1128 void MCCompactEncodedInstFragment::anchor() { }
1129 void MCRelaxableFragment::anchor() { }
1130 void MCAlignFragment::anchor() { }
1131 void MCFillFragment::anchor() { }
1132 void MCOrgFragment::anchor() { }
1133 void MCLEBFragment::anchor() { }
1134 void MCDwarfLineAddrFragment::anchor() { }
1135 void MCDwarfCallFrameFragment::anchor() { }