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(EmittedAlignFragments,
42 "Number of emitted assembler fragments - align");
43 STATISTIC(EmittedFillFragments,
44 "Number of emitted assembler fragments - fill");
45 STATISTIC(EmittedOrgFragments,
46 "Number of emitted assembler fragments - org");
47 STATISTIC(evaluateFixup, "Number of evaluated fixups");
48 STATISTIC(FragmentLayouts, "Number of fragment layouts");
49 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
50 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
51 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
55 // FIXME FIXME FIXME: There are number of places in this file where we convert
56 // what is a 64-bit assembler value used for computation into a value in the
57 // object file, which may truncate it. We should detect that truncation where
58 // invalid and report errors back.
62 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
63 : Assembler(Asm), LastValidFragment()
65 // Compute the section layout order. Virtual sections must go last.
66 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
67 if (!it->getSection().isVirtualSection())
68 SectionOrder.push_back(&*it);
69 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
70 if (it->getSection().isVirtualSection())
71 SectionOrder.push_back(&*it);
74 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
75 const MCSectionData &SD = *F->getParent();
76 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
79 assert(LastValid->getParent() == F->getParent());
80 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
83 void MCAsmLayout::invalidateFragmentsAfter(MCFragment *F) {
84 // If this fragment wasn't already valid, we don't need to do anything.
85 if (!isFragmentValid(F))
88 // Otherwise, reset the last valid fragment to this fragment.
89 const MCSectionData &SD = *F->getParent();
90 LastValidFragment[&SD] = F;
93 void MCAsmLayout::ensureValid(const MCFragment *F) const {
94 MCSectionData &SD = *F->getParent();
96 MCFragment *Cur = LastValidFragment[&SD];
100 Cur = Cur->getNextNode();
102 // Advance the layout position until the fragment is valid.
103 while (!isFragmentValid(F)) {
104 assert(Cur && "Layout bookkeeping error");
105 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
106 Cur = Cur->getNextNode();
110 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
112 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
116 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
117 const MCSymbol &S = SD->getSymbol();
119 // If this is a variable, then recursively evaluate now.
120 if (S.isVariable()) {
122 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
123 report_fatal_error("unable to evaluate offset for variable '" +
126 // Verify that any used symbols are defined.
127 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
128 report_fatal_error("unable to evaluate offset to undefined symbol '" +
129 Target.getSymA()->getSymbol().getName() + "'");
130 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
131 report_fatal_error("unable to evaluate offset to undefined symbol '" +
132 Target.getSymB()->getSymbol().getName() + "'");
134 uint64_t Offset = Target.getConstant();
135 if (Target.getSymA())
136 Offset += getSymbolOffset(&Assembler.getSymbolData(
137 Target.getSymA()->getSymbol()));
138 if (Target.getSymB())
139 Offset -= getSymbolOffset(&Assembler.getSymbolData(
140 Target.getSymB()->getSymbol()));
144 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
145 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
148 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
149 // The size is the last fragment's end offset.
150 const MCFragment &F = SD->getFragmentList().back();
151 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
154 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
155 // Virtual sections have no file size.
156 if (SD->getSection().isVirtualSection())
159 // Otherwise, the file size is the same as the address space size.
160 return getSectionAddressSize(SD);
163 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
164 uint64_t FOffset, uint64_t FSize) {
165 uint64_t BundleSize = Assembler.getBundleAlignSize();
166 assert(BundleSize > 0 &&
167 "computeBundlePadding should only be called if bundling is enabled");
168 uint64_t BundleMask = BundleSize - 1;
169 uint64_t OffsetInBundle = FOffset & BundleMask;
170 uint64_t EndOfFragment = OffsetInBundle + FSize;
172 // There are two kinds of bundling restrictions:
174 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
175 // *end* on a bundle boundary.
176 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
177 // would, add padding until the end of the bundle so that the fragment
178 // will start in a new one.
179 if (F->alignToBundleEnd()) {
180 // Three possibilities here:
182 // A) The fragment just happens to end at a bundle boundary, so we're good.
183 // B) The fragment ends before the current bundle boundary: pad it just
184 // enough to reach the boundary.
185 // C) The fragment ends after the current bundle boundary: pad it until it
186 // reaches the end of the next bundle boundary.
188 // Note: this code could be made shorter with some modulo trickery, but it's
189 // intentionally kept in its more explicit form for simplicity.
190 if (EndOfFragment == BundleSize)
192 else if (EndOfFragment < BundleSize)
193 return BundleSize - EndOfFragment;
194 else { // EndOfFragment > BundleSize
195 return 2 * BundleSize - EndOfFragment;
197 } else if (EndOfFragment > BundleSize)
198 return BundleSize - OffsetInBundle;
205 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
208 MCFragment::~MCFragment() {
211 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
212 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
215 Parent->getFragmentList().push_back(this);
220 MCEncodedFragment::~MCEncodedFragment() {
225 MCSectionData::MCSectionData() : Section(0) {}
227 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
228 : Section(&_Section),
229 Ordinal(~UINT32_C(0)),
231 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
232 HasInstructions(false)
235 A->getSectionList().push_back(this);
240 MCSymbolData::MCSymbolData() : Symbol(0) {}
242 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
243 uint64_t _Offset, MCAssembler *A)
244 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
245 IsExternal(false), IsPrivateExtern(false),
246 CommonSize(0), SymbolSize(0), CommonAlign(0),
250 A->getSymbolList().push_back(this);
255 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
256 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
258 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
259 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
260 SubsectionsViaSymbols(false) {
263 MCAssembler::~MCAssembler() {
266 void MCAssembler::reset() {
271 IndirectSymbols.clear();
276 SubsectionsViaSymbols = false;
278 // reset objects owned by us
279 getBackend().reset();
280 getEmitter().reset();
284 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
285 // Non-temporary labels should always be visible to the linker.
286 if (!Symbol.isTemporary())
289 // Absolute temporary labels are never visible.
290 if (!Symbol.isInSection())
293 // Otherwise, check if the section requires symbols even for temporary labels.
294 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
297 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
298 // Linker visible symbols define atoms.
299 if (isSymbolLinkerVisible(SD->getSymbol()))
302 // Absolute and undefined symbols have no defining atom.
303 if (!SD->getFragment())
306 // Non-linker visible symbols in sections which can't be atomized have no
308 if (!getBackend().isSectionAtomizable(
309 SD->getFragment()->getParent()->getSection()))
312 // Otherwise, return the atom for the containing fragment.
313 return SD->getFragment()->getAtom();
316 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
317 const MCFixup &Fixup, const MCFragment *DF,
318 MCValue &Target, uint64_t &Value) const {
319 ++stats::evaluateFixup;
321 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
322 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
324 bool IsPCRel = Backend.getFixupKindInfo(
325 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
329 if (Target.getSymB()) {
331 } else if (!Target.getSymA()) {
334 const MCSymbolRefExpr *A = Target.getSymA();
335 const MCSymbol &SA = A->getSymbol();
336 if (A->getKind() != MCSymbolRefExpr::VK_None ||
337 SA.AliasedSymbol().isUndefined()) {
340 const MCSymbolData &DataA = getSymbolData(SA);
342 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
347 IsResolved = Target.isAbsolute();
350 Value = Target.getConstant();
352 if (const MCSymbolRefExpr *A = Target.getSymA()) {
353 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
355 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
357 if (const MCSymbolRefExpr *B = Target.getSymB()) {
358 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
360 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
364 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
365 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
366 assert((ShouldAlignPC ? IsPCRel : true) &&
367 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
370 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
372 // A number of ARM fixups in Thumb mode require that the effective PC
373 // address be determined as the 32-bit aligned version of the actual offset.
374 if (ShouldAlignPC) Offset &= ~0x3;
378 // Let the backend adjust the fixup value if necessary, including whether
379 // we need a relocation.
380 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
386 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
387 const MCFragment &F) const {
388 switch (F.getKind()) {
389 case MCFragment::FT_Data:
390 return cast<MCDataFragment>(F).getContents().size();
391 case MCFragment::FT_Fill:
392 return cast<MCFillFragment>(F).getSize();
393 case MCFragment::FT_Relaxable:
394 return cast<MCRelaxableFragment>(F).getInstSize();
396 case MCFragment::FT_LEB:
397 return cast<MCLEBFragment>(F).getContents().size();
399 case MCFragment::FT_Align: {
400 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
401 unsigned Offset = Layout.getFragmentOffset(&AF);
402 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
403 // If we are padding with nops, force the padding to be larger than the
405 if (Size > 0 && AF.hasEmitNops()) {
406 while (Size % getBackend().getMinimumNopSize())
407 Size += AF.getAlignment();
409 if (Size > AF.getMaxBytesToEmit())
414 case MCFragment::FT_Org: {
415 MCOrgFragment &OF = cast<MCOrgFragment>(F);
416 int64_t TargetLocation;
417 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
418 report_fatal_error("expected assembly-time absolute expression");
420 // FIXME: We need a way to communicate this error.
421 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
422 int64_t Size = TargetLocation - FragmentOffset;
423 if (Size < 0 || Size >= 0x40000000)
424 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
425 "' (at offset '" + Twine(FragmentOffset) + "')");
429 case MCFragment::FT_Dwarf:
430 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
431 case MCFragment::FT_DwarfFrame:
432 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
435 llvm_unreachable("invalid fragment kind");
438 void MCAsmLayout::layoutFragment(MCFragment *F) {
439 MCFragment *Prev = F->getPrevNode();
441 // We should never try to recompute something which is valid.
442 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
443 // We should never try to compute the fragment layout if its predecessor
445 assert((!Prev || isFragmentValid(Prev)) &&
446 "Attempt to compute fragment before its predecessor!");
448 ++stats::FragmentLayouts;
450 // Compute fragment offset and size.
452 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
455 LastValidFragment[F->getParent()] = F;
457 // If bundling is enabled and this fragment has instructions in it, it has to
458 // obey the bundling restrictions. With padding, we'll have:
463 // -------------------------------------
464 // Prev |##########| F |
465 // -------------------------------------
470 // The fragment's offset will point to after the padding, and its computed
471 // size won't include the padding.
473 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
474 assert(isa<MCEncodedFragment>(F) &&
475 "Only MCEncodedFragment implementations have instructions");
476 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
478 if (FSize > Assembler.getBundleAlignSize())
479 report_fatal_error("Fragment can't be larger than a bundle size");
481 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
482 if (RequiredBundlePadding > UINT8_MAX)
483 report_fatal_error("Padding cannot exceed 255 bytes");
484 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
485 F->Offset += RequiredBundlePadding;
489 /// \brief Write the contents of a fragment to the given object writer. Expects
490 /// a MCEncodedFragment.
491 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
492 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
493 OW->WriteBytes(EF.getContents());
496 /// \brief Write the fragment \p F to the output file.
497 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
498 const MCFragment &F) {
499 MCObjectWriter *OW = &Asm.getWriter();
501 // Should NOP padding be written out before this fragment?
502 unsigned BundlePadding = F.getBundlePadding();
503 if (BundlePadding > 0) {
504 assert(Asm.isBundlingEnabled() &&
505 "Writing bundle padding with disabled bundling");
506 assert(F.hasInstructions() &&
507 "Writing bundle padding for a fragment without instructions");
509 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
510 report_fatal_error("unable to write NOP sequence of " +
511 Twine(BundlePadding) + " bytes");
514 // This variable (and its dummy usage) is to participate in the assert at
515 // the end of the function.
516 uint64_t Start = OW->getStream().tell();
519 ++stats::EmittedFragments;
521 // FIXME: Embed in fragments instead?
522 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
523 switch (F.getKind()) {
524 case MCFragment::FT_Align: {
525 ++stats::EmittedAlignFragments;
526 MCAlignFragment &AF = cast<MCAlignFragment>(F);
527 uint64_t Count = FragmentSize / AF.getValueSize();
529 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
531 // FIXME: This error shouldn't actually occur (the front end should emit
532 // multiple .align directives to enforce the semantics it wants), but is
533 // severe enough that we want to report it. How to handle this?
534 if (Count * AF.getValueSize() != FragmentSize)
535 report_fatal_error("undefined .align directive, value size '" +
536 Twine(AF.getValueSize()) +
537 "' is not a divisor of padding size '" +
538 Twine(FragmentSize) + "'");
540 // See if we are aligning with nops, and if so do that first to try to fill
541 // the Count bytes. Then if that did not fill any bytes or there are any
542 // bytes left to fill use the Value and ValueSize to fill the rest.
543 // If we are aligning with nops, ask that target to emit the right data.
544 if (AF.hasEmitNops()) {
545 if (!Asm.getBackend().writeNopData(Count, OW))
546 report_fatal_error("unable to write nop sequence of " +
547 Twine(Count) + " bytes");
551 // Otherwise, write out in multiples of the value size.
552 for (uint64_t i = 0; i != Count; ++i) {
553 switch (AF.getValueSize()) {
554 default: llvm_unreachable("Invalid size!");
555 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
556 case 2: OW->Write16(uint16_t(AF.getValue())); break;
557 case 4: OW->Write32(uint32_t(AF.getValue())); break;
558 case 8: OW->Write64(uint64_t(AF.getValue())); break;
564 case MCFragment::FT_Data:
565 ++stats::EmittedDataFragments;
566 writeFragmentContents(F, OW);
569 case MCFragment::FT_Relaxable:
570 ++stats::EmittedRelaxableFragments;
571 writeFragmentContents(F, OW);
574 case MCFragment::FT_Fill: {
575 ++stats::EmittedFillFragments;
576 MCFillFragment &FF = cast<MCFillFragment>(F);
578 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
580 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
581 switch (FF.getValueSize()) {
582 default: llvm_unreachable("Invalid size!");
583 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
584 case 2: OW->Write16(uint16_t(FF.getValue())); break;
585 case 4: OW->Write32(uint32_t(FF.getValue())); break;
586 case 8: OW->Write64(uint64_t(FF.getValue())); break;
592 case MCFragment::FT_LEB: {
593 MCLEBFragment &LF = cast<MCLEBFragment>(F);
594 OW->WriteBytes(LF.getContents().str());
598 case MCFragment::FT_Org: {
599 ++stats::EmittedOrgFragments;
600 MCOrgFragment &OF = cast<MCOrgFragment>(F);
602 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
603 OW->Write8(uint8_t(OF.getValue()));
608 case MCFragment::FT_Dwarf: {
609 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
610 OW->WriteBytes(OF.getContents().str());
613 case MCFragment::FT_DwarfFrame: {
614 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
615 OW->WriteBytes(CF.getContents().str());
620 assert(OW->getStream().tell() - Start == FragmentSize &&
621 "The stream should advance by fragment size");
624 void MCAssembler::writeSectionData(const MCSectionData *SD,
625 const MCAsmLayout &Layout) const {
626 // Ignore virtual sections.
627 if (SD->getSection().isVirtualSection()) {
628 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
630 // Check that contents are only things legal inside a virtual section.
631 for (MCSectionData::const_iterator it = SD->begin(),
632 ie = SD->end(); it != ie; ++it) {
633 switch (it->getKind()) {
634 default: llvm_unreachable("Invalid fragment in virtual section!");
635 case MCFragment::FT_Data: {
636 // Check that we aren't trying to write a non-zero contents (or fixups)
637 // into a virtual section. This is to support clients which use standard
638 // directives to fill the contents of virtual sections.
639 MCDataFragment &DF = cast<MCDataFragment>(*it);
640 assert(DF.fixup_begin() == DF.fixup_end() &&
641 "Cannot have fixups in virtual section!");
642 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
643 assert(DF.getContents()[i] == 0 &&
644 "Invalid data value for virtual section!");
647 case MCFragment::FT_Align:
648 // Check that we aren't trying to write a non-zero value into a virtual
650 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
651 !cast<MCAlignFragment>(it)->getValue()) &&
652 "Invalid align in virtual section!");
654 case MCFragment::FT_Fill:
655 assert(!cast<MCFillFragment>(it)->getValueSize() &&
656 "Invalid fill in virtual section!");
664 uint64_t Start = getWriter().getStream().tell();
667 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
669 writeFragment(*this, Layout, *it);
671 assert(getWriter().getStream().tell() - Start ==
672 Layout.getSectionAddressSize(SD));
676 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
678 const MCFixup &Fixup) {
679 // Evaluate the fixup.
682 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
683 // The fixup was unresolved, we need a relocation. Inform the object
684 // writer of the relocation, and give it an opportunity to adjust the
685 // fixup value if need be.
686 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
691 void MCAssembler::Finish() {
692 DEBUG_WITH_TYPE("mc-dump", {
693 llvm::errs() << "assembler backend - pre-layout\n--\n";
696 // Create the layout object.
697 MCAsmLayout Layout(*this);
699 // Create dummy fragments and assign section ordinals.
700 unsigned SectionIndex = 0;
701 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
702 // Create dummy fragments to eliminate any empty sections, this simplifies
704 if (it->getFragmentList().empty())
705 new MCDataFragment(it);
707 it->setOrdinal(SectionIndex++);
710 // Assign layout order indices to sections and fragments.
711 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
712 MCSectionData *SD = Layout.getSectionOrder()[i];
713 SD->setLayoutOrder(i);
715 unsigned FragmentIndex = 0;
716 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
717 iFrag != iFragEnd; ++iFrag)
718 iFrag->setLayoutOrder(FragmentIndex++);
721 // Layout until everything fits.
722 while (layoutOnce(Layout))
725 DEBUG_WITH_TYPE("mc-dump", {
726 llvm::errs() << "assembler backend - post-relaxation\n--\n";
729 // Finalize the layout, including fragment lowering.
730 finishLayout(Layout);
732 DEBUG_WITH_TYPE("mc-dump", {
733 llvm::errs() << "assembler backend - final-layout\n--\n";
736 uint64_t StartOffset = OS.tell();
738 // Allow the object writer a chance to perform post-layout binding (for
739 // example, to set the index fields in the symbol data).
740 getWriter().ExecutePostLayoutBinding(*this, Layout);
742 // Evaluate and apply the fixups, generating relocation entries as necessary.
743 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
744 for (MCSectionData::iterator it2 = it->begin(),
745 ie2 = it->end(); it2 != ie2; ++it2) {
746 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
748 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
749 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
750 MCFixup &Fixup = *it3;
751 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
752 getBackend().applyFixup(Fixup, F->getContents().data(),
753 F->getContents().size(), FixedValue);
759 // Write the object file.
760 getWriter().WriteObject(*this, Layout);
762 stats::ObjectBytes += OS.tell() - StartOffset;
765 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
766 const MCRelaxableFragment *DF,
767 const MCAsmLayout &Layout) const {
768 // If we cannot resolve the fixup value, it requires relaxation.
771 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
774 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
777 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
778 const MCAsmLayout &Layout) const {
779 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
780 // are intentionally pushing out inst fragments, or because we relaxed a
781 // previous instruction to one that doesn't need relaxation.
782 if (!getBackend().mayNeedRelaxation(F->getInst()))
785 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
786 ie = F->fixup_end(); it != ie; ++it)
787 if (fixupNeedsRelaxation(*it, F, Layout))
793 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
794 MCRelaxableFragment &F) {
795 if (!fragmentNeedsRelaxation(&F, Layout))
798 ++stats::RelaxedInstructions;
800 // FIXME-PERF: We could immediately lower out instructions if we can tell
801 // they are fully resolved, to avoid retesting on later passes.
803 // Relax the fragment.
806 getBackend().relaxInstruction(F.getInst(), Relaxed);
808 // Encode the new instruction.
810 // FIXME-PERF: If it matters, we could let the target do this. It can
811 // probably do so more efficiently in many cases.
812 SmallVector<MCFixup, 4> Fixups;
813 SmallString<256> Code;
814 raw_svector_ostream VecOS(Code);
815 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
818 // Update the fragment.
820 F.getContents() = Code;
821 F.getFixups() = Fixups;
826 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
828 uint64_t OldSize = LF.getContents().size();
829 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
832 SmallString<8> &Data = LF.getContents();
834 raw_svector_ostream OSE(Data);
836 encodeSLEB128(Value, OSE);
838 encodeULEB128(Value, OSE);
840 return OldSize != LF.getContents().size();
843 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
844 MCDwarfLineAddrFragment &DF) {
845 int64_t AddrDelta = 0;
846 uint64_t OldSize = DF.getContents().size();
847 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
851 LineDelta = DF.getLineDelta();
852 SmallString<8> &Data = DF.getContents();
854 raw_svector_ostream OSE(Data);
855 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
857 return OldSize != Data.size();
860 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
861 MCDwarfCallFrameFragment &DF) {
862 int64_t AddrDelta = 0;
863 uint64_t OldSize = DF.getContents().size();
864 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
867 SmallString<8> &Data = DF.getContents();
869 raw_svector_ostream OSE(Data);
870 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
872 return OldSize != Data.size();
875 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
876 // Holds the first fragment which needed relaxing during this layout. It will
877 // remain NULL if none were relaxed.
878 // When a fragment is relaxed, all the fragments following it should get
879 // invalidated because their offset is going to change.
880 MCFragment *FirstRelaxedFragment = NULL;
882 // Attempt to relax all the fragments in the section.
883 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
884 // Check if this is a fragment that needs relaxation.
885 bool RelaxedFrag = false;
886 switch(I->getKind()) {
889 case MCFragment::FT_Relaxable:
890 assert(!getRelaxAll() &&
891 "Did not expect a MCRelaxableFragment in RelaxAll mode");
892 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
894 case MCFragment::FT_Dwarf:
895 RelaxedFrag = relaxDwarfLineAddr(Layout,
896 *cast<MCDwarfLineAddrFragment>(I));
898 case MCFragment::FT_DwarfFrame:
900 relaxDwarfCallFrameFragment(Layout,
901 *cast<MCDwarfCallFrameFragment>(I));
903 case MCFragment::FT_LEB:
904 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
907 if (RelaxedFrag && !FirstRelaxedFragment)
908 FirstRelaxedFragment = I;
910 if (FirstRelaxedFragment) {
911 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
917 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
918 ++stats::RelaxationSteps;
920 bool WasRelaxed = false;
921 for (iterator it = begin(), ie = end(); it != ie; ++it) {
922 MCSectionData &SD = *it;
923 while (layoutSectionOnce(Layout, SD))
930 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
931 // The layout is done. Mark every fragment as valid.
932 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
933 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
941 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
942 OS << "<MCFixup" << " Offset:" << AF.getOffset()
943 << " Value:" << *AF.getValue()
944 << " Kind:" << AF.getKind() << ">";
950 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
951 void MCFragment::dump() {
952 raw_ostream &OS = llvm::errs();
956 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
957 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
958 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
959 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
960 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
961 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
962 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
963 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
966 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
967 << " Offset:" << Offset
968 << " HasInstructions:" << hasInstructions()
969 << " BundlePadding:" << getBundlePadding() << ">";
972 case MCFragment::FT_Align: {
973 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
974 if (AF->hasEmitNops())
975 OS << " (emit nops)";
977 OS << " Alignment:" << AF->getAlignment()
978 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
979 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
982 case MCFragment::FT_Data: {
983 const MCDataFragment *DF = cast<MCDataFragment>(this);
986 const SmallVectorImpl<char> &Contents = DF->getContents();
987 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
989 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
991 OS << "] (" << Contents.size() << " bytes)";
993 if (DF->fixup_begin() != DF->fixup_end()) {
996 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
997 ie = DF->fixup_end(); it != ie; ++it) {
998 if (it != DF->fixup_begin()) OS << ",\n ";
1005 case MCFragment::FT_Fill: {
1006 const MCFillFragment *FF = cast<MCFillFragment>(this);
1007 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1008 << " Size:" << FF->getSize();
1011 case MCFragment::FT_Relaxable: {
1012 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1015 F->getInst().dump_pretty(OS);
1018 case MCFragment::FT_Org: {
1019 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1021 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1024 case MCFragment::FT_Dwarf: {
1025 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1027 OS << " AddrDelta:" << OF->getAddrDelta()
1028 << " LineDelta:" << OF->getLineDelta();
1031 case MCFragment::FT_DwarfFrame: {
1032 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1034 OS << " AddrDelta:" << CF->getAddrDelta();
1037 case MCFragment::FT_LEB: {
1038 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1040 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1047 void MCSectionData::dump() {
1048 raw_ostream &OS = llvm::errs();
1050 OS << "<MCSectionData";
1051 OS << " Alignment:" << getAlignment()
1052 << " Fragments:[\n ";
1053 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1054 if (it != begin()) OS << ",\n ";
1060 void MCSymbolData::dump() {
1061 raw_ostream &OS = llvm::errs();
1063 OS << "<MCSymbolData Symbol:" << getSymbol()
1064 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1065 << " Flags:" << getFlags() << " Index:" << getIndex();
1067 OS << " (common, size:" << getCommonSize()
1068 << " align: " << getCommonAlignment() << ")";
1070 OS << " (external)";
1071 if (isPrivateExtern())
1072 OS << " (private extern)";
1076 void MCAssembler::dump() {
1077 raw_ostream &OS = llvm::errs();
1079 OS << "<MCAssembler\n";
1080 OS << " Sections:[\n ";
1081 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1082 if (it != begin()) OS << ",\n ";
1088 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1089 if (it != symbol_begin()) OS << ",\n ";
1096 // anchors for MC*Fragment vtables
1097 void MCEncodedFragment::anchor() { }
1098 void MCDataFragment::anchor() { }
1099 void MCRelaxableFragment::anchor() { }
1100 void MCAlignFragment::anchor() { }
1101 void MCFillFragment::anchor() { }
1102 void MCOrgFragment::anchor() { }
1103 void MCLEBFragment::anchor() { }
1104 void MCDwarfLineAddrFragment::anchor() { }
1105 void MCDwarfCallFrameFragment::anchor() { }