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(EmittedInstFragments,
38 "Number of emitted assembler fragments - instruction");
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::isFragmentUpToDate(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 up-to-date, we don't need to do anything.
85 if (!isFragmentUpToDate(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 up-to-date.
103 while (!isFragmentUpToDate(F)) {
104 const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
105 Cur = Cur->getNextNode();
109 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
111 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
115 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
116 const MCSymbol &S = SD->getSymbol();
118 // If this is a variable, then recursively evaluate now.
119 if (S.isVariable()) {
121 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
122 report_fatal_error("unable to evaluate offset for variable '" +
125 // Verify that any used symbols are defined.
126 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
127 report_fatal_error("unable to evaluate offset to undefined symbol '" +
128 Target.getSymA()->getSymbol().getName() + "'");
129 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
130 report_fatal_error("unable to evaluate offset to undefined symbol '" +
131 Target.getSymB()->getSymbol().getName() + "'");
133 uint64_t Offset = Target.getConstant();
134 if (Target.getSymA())
135 Offset += getSymbolOffset(&Assembler.getSymbolData(
136 Target.getSymA()->getSymbol()));
137 if (Target.getSymB())
138 Offset -= getSymbolOffset(&Assembler.getSymbolData(
139 Target.getSymB()->getSymbol()));
143 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
144 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
147 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
148 // The size is the last fragment's end offset.
149 const MCFragment &F = SD->getFragmentList().back();
150 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
153 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
154 // Virtual sections have no file size.
155 if (SD->getSection().isVirtualSection())
158 // Otherwise, the file size is the same as the address space size.
159 return getSectionAddressSize(SD);
164 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
167 MCFragment::~MCFragment() {
170 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
171 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
174 Parent->getFragmentList().push_back(this);
179 MCEncodedFragment::~MCEncodedFragment() {
184 MCSectionData::MCSectionData() : Section(0) {}
186 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
187 : Section(&_Section),
188 Ordinal(~UINT32_C(0)),
190 HasInstructions(false)
193 A->getSectionList().push_back(this);
198 MCSymbolData::MCSymbolData() : Symbol(0) {}
200 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
201 uint64_t _Offset, MCAssembler *A)
202 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
203 IsExternal(false), IsPrivateExtern(false),
204 CommonSize(0), SymbolSize(0), CommonAlign(0),
208 A->getSymbolList().push_back(this);
213 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
214 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
216 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
217 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false) {
220 MCAssembler::~MCAssembler() {
223 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
224 // Non-temporary labels should always be visible to the linker.
225 if (!Symbol.isTemporary())
228 // Absolute temporary labels are never visible.
229 if (!Symbol.isInSection())
232 // Otherwise, check if the section requires symbols even for temporary labels.
233 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
236 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
237 // Linker visible symbols define atoms.
238 if (isSymbolLinkerVisible(SD->getSymbol()))
241 // Absolute and undefined symbols have no defining atom.
242 if (!SD->getFragment())
245 // Non-linker visible symbols in sections which can't be atomized have no
247 if (!getBackend().isSectionAtomizable(
248 SD->getFragment()->getParent()->getSection()))
251 // Otherwise, return the atom for the containing fragment.
252 return SD->getFragment()->getAtom();
255 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
256 const MCFixup &Fixup, const MCFragment *DF,
257 MCValue &Target, uint64_t &Value) const {
258 ++stats::evaluateFixup;
260 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
261 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
263 bool IsPCRel = Backend.getFixupKindInfo(
264 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
268 if (Target.getSymB()) {
270 } else if (!Target.getSymA()) {
273 const MCSymbolRefExpr *A = Target.getSymA();
274 const MCSymbol &SA = A->getSymbol();
275 if (A->getKind() != MCSymbolRefExpr::VK_None ||
276 SA.AliasedSymbol().isUndefined()) {
279 const MCSymbolData &DataA = getSymbolData(SA);
281 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
286 IsResolved = Target.isAbsolute();
289 Value = Target.getConstant();
291 if (const MCSymbolRefExpr *A = Target.getSymA()) {
292 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
294 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
296 if (const MCSymbolRefExpr *B = Target.getSymB()) {
297 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
299 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
303 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
304 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
305 assert((ShouldAlignPC ? IsPCRel : true) &&
306 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
309 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
311 // A number of ARM fixups in Thumb mode require that the effective PC
312 // address be determined as the 32-bit aligned version of the actual offset.
313 if (ShouldAlignPC) Offset &= ~0x3;
317 // Let the backend adjust the fixup value if necessary, including whether
318 // we need a relocation.
319 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
325 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
326 const MCFragment &F) const {
327 switch (F.getKind()) {
328 case MCFragment::FT_Data:
329 return cast<MCDataFragment>(F).getContents().size();
330 case MCFragment::FT_Fill:
331 return cast<MCFillFragment>(F).getSize();
332 case MCFragment::FT_Inst:
333 return cast<MCInstFragment>(F).getInstSize();
335 case MCFragment::FT_LEB:
336 return cast<MCLEBFragment>(F).getContents().size();
338 case MCFragment::FT_Align: {
339 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
340 unsigned Offset = Layout.getFragmentOffset(&AF);
341 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
342 // If we are padding with nops, force the padding to be larger than the
344 if (Size > 0 && AF.hasEmitNops()) {
345 while (Size % getBackend().getMinimumNopSize())
346 Size += AF.getAlignment();
348 if (Size > AF.getMaxBytesToEmit())
353 case MCFragment::FT_Org: {
354 MCOrgFragment &OF = cast<MCOrgFragment>(F);
355 int64_t TargetLocation;
356 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
357 report_fatal_error("expected assembly-time absolute expression");
359 // FIXME: We need a way to communicate this error.
360 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
361 int64_t Size = TargetLocation - FragmentOffset;
362 if (Size < 0 || Size >= 0x40000000)
363 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
364 "' (at offset '" + Twine(FragmentOffset) + "')");
368 case MCFragment::FT_Dwarf:
369 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
370 case MCFragment::FT_DwarfFrame:
371 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
374 llvm_unreachable("invalid fragment kind");
377 void MCAsmLayout::LayoutFragment(MCFragment *F) {
378 MCFragment *Prev = F->getPrevNode();
380 // We should never try to recompute something which is up-to-date.
381 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
382 // We should never try to compute the fragment layout if it's predecessor
384 assert((!Prev || isFragmentUpToDate(Prev)) &&
385 "Attempt to compute fragment before it's predecessor!");
387 ++stats::FragmentLayouts;
389 // Compute fragment offset and size.
392 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
395 LastValidFragment[F->getParent()] = F;
398 /// \brief Write the contents of a fragment to the given object writer. Expects
399 /// a MCEncodedFragment.
400 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
401 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
402 OW->WriteBytes(EF.getContents());
405 /// \brief Write the fragment \p F to the output file.
406 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
407 const MCFragment &F) {
408 MCObjectWriter *OW = &Asm.getWriter();
409 uint64_t Start = OW->getStream().tell();
412 ++stats::EmittedFragments;
414 // FIXME: Embed in fragments instead?
415 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
416 switch (F.getKind()) {
417 case MCFragment::FT_Align: {
418 ++stats::EmittedAlignFragments;
419 MCAlignFragment &AF = cast<MCAlignFragment>(F);
420 uint64_t Count = FragmentSize / AF.getValueSize();
422 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
424 // FIXME: This error shouldn't actually occur (the front end should emit
425 // multiple .align directives to enforce the semantics it wants), but is
426 // severe enough that we want to report it. How to handle this?
427 if (Count * AF.getValueSize() != FragmentSize)
428 report_fatal_error("undefined .align directive, value size '" +
429 Twine(AF.getValueSize()) +
430 "' is not a divisor of padding size '" +
431 Twine(FragmentSize) + "'");
433 // See if we are aligning with nops, and if so do that first to try to fill
434 // the Count bytes. Then if that did not fill any bytes or there are any
435 // bytes left to fill use the Value and ValueSize to fill the rest.
436 // If we are aligning with nops, ask that target to emit the right data.
437 if (AF.hasEmitNops()) {
438 if (!Asm.getBackend().writeNopData(Count, OW))
439 report_fatal_error("unable to write nop sequence of " +
440 Twine(Count) + " bytes");
444 // Otherwise, write out in multiples of the value size.
445 for (uint64_t i = 0; i != Count; ++i) {
446 switch (AF.getValueSize()) {
447 default: llvm_unreachable("Invalid size!");
448 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
449 case 2: OW->Write16(uint16_t(AF.getValue())); break;
450 case 4: OW->Write32(uint32_t(AF.getValue())); break;
451 case 8: OW->Write64(uint64_t(AF.getValue())); break;
457 case MCFragment::FT_Data:
458 ++stats::EmittedDataFragments;
459 writeFragmentContents(F, OW);
462 case MCFragment::FT_Inst:
463 ++stats::EmittedInstFragments;
464 writeFragmentContents(F, OW);
467 case MCFragment::FT_Fill: {
468 ++stats::EmittedFillFragments;
469 MCFillFragment &FF = cast<MCFillFragment>(F);
471 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
473 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
474 switch (FF.getValueSize()) {
475 default: llvm_unreachable("Invalid size!");
476 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
477 case 2: OW->Write16(uint16_t(FF.getValue())); break;
478 case 4: OW->Write32(uint32_t(FF.getValue())); break;
479 case 8: OW->Write64(uint64_t(FF.getValue())); break;
485 case MCFragment::FT_LEB: {
486 MCLEBFragment &LF = cast<MCLEBFragment>(F);
487 OW->WriteBytes(LF.getContents().str());
491 case MCFragment::FT_Org: {
492 ++stats::EmittedOrgFragments;
493 MCOrgFragment &OF = cast<MCOrgFragment>(F);
495 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
496 OW->Write8(uint8_t(OF.getValue()));
501 case MCFragment::FT_Dwarf: {
502 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
503 OW->WriteBytes(OF.getContents().str());
506 case MCFragment::FT_DwarfFrame: {
507 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
508 OW->WriteBytes(CF.getContents().str());
513 assert(OW->getStream().tell() - Start == FragmentSize);
516 void MCAssembler::writeSectionData(const MCSectionData *SD,
517 const MCAsmLayout &Layout) const {
518 // Ignore virtual sections.
519 if (SD->getSection().isVirtualSection()) {
520 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
522 // Check that contents are only things legal inside a virtual section.
523 for (MCSectionData::const_iterator it = SD->begin(),
524 ie = SD->end(); it != ie; ++it) {
525 switch (it->getKind()) {
526 default: llvm_unreachable("Invalid fragment in virtual section!");
527 case MCFragment::FT_Data: {
528 // Check that we aren't trying to write a non-zero contents (or fixups)
529 // into a virtual section. This is to support clients which use standard
530 // directives to fill the contents of virtual sections.
531 MCDataFragment &DF = cast<MCDataFragment>(*it);
532 assert(DF.fixup_begin() == DF.fixup_end() &&
533 "Cannot have fixups in virtual section!");
534 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
535 assert(DF.getContents()[i] == 0 &&
536 "Invalid data value for virtual section!");
539 case MCFragment::FT_Align:
540 // Check that we aren't trying to write a non-zero value into a virtual
542 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
543 !cast<MCAlignFragment>(it)->getValue()) &&
544 "Invalid align in virtual section!");
546 case MCFragment::FT_Fill:
547 assert(!cast<MCFillFragment>(it)->getValueSize() &&
548 "Invalid fill in virtual section!");
556 uint64_t Start = getWriter().getStream().tell();
559 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
561 writeFragment(*this, Layout, *it);
563 assert(getWriter().getStream().tell() - Start ==
564 Layout.getSectionAddressSize(SD));
568 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
570 const MCFixup &Fixup) {
571 // Evaluate the fixup.
574 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
575 // The fixup was unresolved, we need a relocation. Inform the object
576 // writer of the relocation, and give it an opportunity to adjust the
577 // fixup value if need be.
578 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
583 void MCAssembler::Finish() {
584 DEBUG_WITH_TYPE("mc-dump", {
585 llvm::errs() << "assembler backend - pre-layout\n--\n";
588 // Create the layout object.
589 MCAsmLayout Layout(*this);
591 // Create dummy fragments and assign section ordinals.
592 unsigned SectionIndex = 0;
593 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
594 // Create dummy fragments to eliminate any empty sections, this simplifies
596 if (it->getFragmentList().empty())
597 new MCDataFragment(it);
599 it->setOrdinal(SectionIndex++);
602 // Assign layout order indices to sections and fragments.
603 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
604 MCSectionData *SD = Layout.getSectionOrder()[i];
605 SD->setLayoutOrder(i);
607 unsigned FragmentIndex = 0;
608 for (MCSectionData::iterator it2 = SD->begin(),
609 ie2 = SD->end(); it2 != ie2; ++it2)
610 it2->setLayoutOrder(FragmentIndex++);
613 // Layout until everything fits.
614 while (layoutOnce(Layout))
617 DEBUG_WITH_TYPE("mc-dump", {
618 llvm::errs() << "assembler backend - post-relaxation\n--\n";
621 // Finalize the layout, including fragment lowering.
622 finishLayout(Layout);
624 DEBUG_WITH_TYPE("mc-dump", {
625 llvm::errs() << "assembler backend - final-layout\n--\n";
628 uint64_t StartOffset = OS.tell();
630 // Allow the object writer a chance to perform post-layout binding (for
631 // example, to set the index fields in the symbol data).
632 getWriter().ExecutePostLayoutBinding(*this, Layout);
634 // Evaluate and apply the fixups, generating relocation entries as necessary.
635 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
636 for (MCSectionData::iterator it2 = it->begin(),
637 ie2 = it->end(); it2 != ie2; ++it2) {
638 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
640 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
641 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
642 MCFixup &Fixup = *it3;
643 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
644 getBackend().applyFixup(Fixup, F->getContents().data(),
645 F->getContents().size(), FixedValue);
651 // Write the object file.
652 getWriter().WriteObject(*this, Layout);
654 stats::ObjectBytes += OS.tell() - StartOffset;
657 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
658 const MCInstFragment *DF,
659 const MCAsmLayout &Layout) const {
660 // If we cannot resolve the fixup value, it requires relaxation.
663 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
666 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
669 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
670 const MCAsmLayout &Layout) const {
671 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
672 // are intentionally pushing out inst fragments, or because we relaxed a
673 // previous instruction to one that doesn't need relaxation.
674 if (!getBackend().mayNeedRelaxation(IF->getInst()))
677 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
678 ie = IF->fixup_end(); it != ie; ++it)
679 if (fixupNeedsRelaxation(*it, IF, Layout))
685 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
686 MCInstFragment &IF) {
687 if (!fragmentNeedsRelaxation(&IF, Layout))
690 ++stats::RelaxedInstructions;
692 // FIXME-PERF: We could immediately lower out instructions if we can tell
693 // they are fully resolved, to avoid retesting on later passes.
695 // Relax the fragment.
698 getBackend().relaxInstruction(IF.getInst(), Relaxed);
700 // Encode the new instruction.
702 // FIXME-PERF: If it matters, we could let the target do this. It can
703 // probably do so more efficiently in many cases.
704 SmallVector<MCFixup, 4> Fixups;
705 SmallString<256> Code;
706 raw_svector_ostream VecOS(Code);
707 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
710 // Update the instruction fragment.
712 IF.getContents() = Code;
713 IF.getFixups() = Fixups;
718 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
720 uint64_t OldSize = LF.getContents().size();
721 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
724 SmallString<8> &Data = LF.getContents();
726 raw_svector_ostream OSE(Data);
728 encodeSLEB128(Value, OSE);
730 encodeULEB128(Value, OSE);
732 return OldSize != LF.getContents().size();
735 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
736 MCDwarfLineAddrFragment &DF) {
737 int64_t AddrDelta = 0;
738 uint64_t OldSize = DF.getContents().size();
739 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
743 LineDelta = DF.getLineDelta();
744 SmallString<8> &Data = DF.getContents();
746 raw_svector_ostream OSE(Data);
747 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
749 return OldSize != Data.size();
752 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
753 MCDwarfCallFrameFragment &DF) {
754 int64_t AddrDelta = 0;
755 uint64_t OldSize = DF.getContents().size();
756 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
759 SmallString<8> &Data = DF.getContents();
761 raw_svector_ostream OSE(Data);
762 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
764 return OldSize != Data.size();
767 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
768 // Holds the first fragment which needed relaxing during this layout. It will
769 // remain NULL if none were relaxed.
770 MCFragment *FirstInvalidFragment = NULL;
772 // Scan for fragments that need relaxation.
773 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
774 // Check if this is a fragment that needs relaxation.
775 bool RelaxedFrag = false;
776 switch(I->getKind()) {
779 case MCFragment::FT_Inst:
780 assert(!getRelaxAll() &&
781 "Did not expect a MCInstFragment in RelaxAll mode");
782 RelaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(I));
784 case MCFragment::FT_Dwarf:
785 RelaxedFrag = relaxDwarfLineAddr(Layout,
786 *cast<MCDwarfLineAddrFragment>(I));
788 case MCFragment::FT_DwarfFrame:
790 relaxDwarfCallFrameFragment(Layout,
791 *cast<MCDwarfCallFrameFragment>(I));
793 case MCFragment::FT_LEB:
794 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
797 if (RelaxedFrag && !FirstInvalidFragment)
798 FirstInvalidFragment = I;
800 if (FirstInvalidFragment) {
801 Layout.invalidateFragmentsAfter(FirstInvalidFragment);
807 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
808 ++stats::RelaxationSteps;
810 bool WasRelaxed = false;
811 for (iterator it = begin(), ie = end(); it != ie; ++it) {
812 MCSectionData &SD = *it;
813 while (layoutSectionOnce(Layout, SD))
820 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
821 // The layout is done. Mark every fragment as valid.
822 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
823 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
831 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
832 OS << "<MCFixup" << " Offset:" << AF.getOffset()
833 << " Value:" << *AF.getValue()
834 << " Kind:" << AF.getKind() << ">";
840 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
841 void MCFragment::dump() {
842 raw_ostream &OS = llvm::errs();
846 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
847 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
848 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
849 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
850 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
851 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
852 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
853 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
856 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
857 << " Offset:" << Offset << ">";
860 case MCFragment::FT_Align: {
861 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
862 if (AF->hasEmitNops())
863 OS << " (emit nops)";
865 OS << " Alignment:" << AF->getAlignment()
866 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
867 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
870 case MCFragment::FT_Data: {
871 const MCDataFragment *DF = cast<MCDataFragment>(this);
874 const SmallVectorImpl<char> &Contents = DF->getContents();
875 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
877 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
879 OS << "] (" << Contents.size() << " bytes)";
881 if (DF->fixup_begin() != DF->fixup_end()) {
884 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
885 ie = DF->fixup_end(); it != ie; ++it) {
886 if (it != DF->fixup_begin()) OS << ",\n ";
893 case MCFragment::FT_Fill: {
894 const MCFillFragment *FF = cast<MCFillFragment>(this);
895 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
896 << " Size:" << FF->getSize();
899 case MCFragment::FT_Inst: {
900 const MCInstFragment *IF = cast<MCInstFragment>(this);
903 IF->getInst().dump_pretty(OS);
906 case MCFragment::FT_Org: {
907 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
909 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
912 case MCFragment::FT_Dwarf: {
913 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
915 OS << " AddrDelta:" << OF->getAddrDelta()
916 << " LineDelta:" << OF->getLineDelta();
919 case MCFragment::FT_DwarfFrame: {
920 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
922 OS << " AddrDelta:" << CF->getAddrDelta();
925 case MCFragment::FT_LEB: {
926 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
928 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
935 void MCSectionData::dump() {
936 raw_ostream &OS = llvm::errs();
938 OS << "<MCSectionData";
939 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
940 for (iterator it = begin(), ie = end(); it != ie; ++it) {
941 if (it != begin()) OS << ",\n ";
947 void MCSymbolData::dump() {
948 raw_ostream &OS = llvm::errs();
950 OS << "<MCSymbolData Symbol:" << getSymbol()
951 << " Fragment:" << getFragment() << " Offset:" << getOffset()
952 << " Flags:" << getFlags() << " Index:" << getIndex();
954 OS << " (common, size:" << getCommonSize()
955 << " align: " << getCommonAlignment() << ")";
958 if (isPrivateExtern())
959 OS << " (private extern)";
963 void MCAssembler::dump() {
964 raw_ostream &OS = llvm::errs();
966 OS << "<MCAssembler\n";
967 OS << " Sections:[\n ";
968 for (iterator it = begin(), ie = end(); it != ie; ++it) {
969 if (it != begin()) OS << ",\n ";
975 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
976 if (it != symbol_begin()) OS << ",\n ";
983 // anchors for MC*Fragment vtables
984 void MCEncodedFragment::anchor() { }
985 void MCDataFragment::anchor() { }
986 void MCInstFragment::anchor() { }
987 void MCAlignFragment::anchor() { }
988 void MCFillFragment::anchor() { }
989 void MCOrgFragment::anchor() { }
990 void MCLEBFragment::anchor() { }
991 void MCDwarfLineAddrFragment::anchor() { }
992 void MCDwarfCallFrameFragment::anchor() { }