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/MC/MCAsmLayout.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSection.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Target/TargetAsmBackend.h"
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
36 STATISTIC(EvaluateFixup, "Number of evaluated fixups");
37 STATISTIC(FragmentLayouts, "Number of fragment layouts");
38 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
39 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
40 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
44 // FIXME FIXME FIXME: There are number of places in this file where we convert
45 // what is a 64-bit assembler value used for computation into a value in the
46 // object file, which may truncate it. We should detect that truncation where
47 // invalid and report errors back.
51 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
52 : Assembler(Asm), LastValidFragment()
54 // Compute the section layout order. Virtual sections must go last.
55 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
56 if (!it->getSection().isVirtualSection())
57 SectionOrder.push_back(&*it);
58 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
59 if (it->getSection().isVirtualSection())
60 SectionOrder.push_back(&*it);
63 bool MCAsmLayout::isFragmentUpToDate(const MCFragment *F) const {
64 const MCSectionData &SD = *F->getParent();
65 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
68 assert(LastValid->getParent() == F->getParent());
69 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
72 void MCAsmLayout::Invalidate(MCFragment *F) {
73 // If this fragment wasn't already up-to-date, we don't need to do anything.
74 if (!isFragmentUpToDate(F))
77 // Otherwise, reset the last valid fragment to this fragment.
78 const MCSectionData &SD = *F->getParent();
79 LastValidFragment[&SD] = F;
82 void MCAsmLayout::EnsureValid(const MCFragment *F) const {
83 MCSectionData &SD = *F->getParent();
85 MCFragment *Cur = LastValidFragment[&SD];
89 Cur = Cur->getNextNode();
91 // Advance the layout position until the fragment is up-to-date.
92 while (!isFragmentUpToDate(F)) {
93 const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
94 Cur = Cur->getNextNode();
98 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
100 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
104 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
105 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
106 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
109 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
110 // The size is the last fragment's end offset.
111 const MCFragment &F = SD->getFragmentList().back();
112 return getFragmentOffset(&F) + getAssembler().ComputeFragmentSize(F);
115 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
116 // Virtual sections have no file size.
117 if (SD->getSection().isVirtualSection())
120 // Otherwise, the file size is the same as the address space size.
121 return getSectionAddressSize(SD);
126 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
129 MCFragment::~MCFragment() {
132 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
133 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
136 Parent->getFragmentList().push_back(this);
141 MCSectionData::MCSectionData() : Section(0) {}
143 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
144 : Section(&_Section),
145 Ordinal(~UINT32_C(0)),
147 HasInstructions(false)
150 A->getSectionList().push_back(this);
155 MCSymbolData::MCSymbolData() : Symbol(0) {}
157 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
158 uint64_t _Offset, MCAssembler *A)
159 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
160 IsExternal(false), IsPrivateExtern(false),
161 CommonSize(0), SymbolSize(0), CommonAlign(0),
165 A->getSymbolList().push_back(this);
170 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
171 MCCodeEmitter &_Emitter, raw_ostream &_OS)
172 : Context(_Context), Backend(_Backend), Emitter(_Emitter),
173 OS(_OS), RelaxAll(false), SubsectionsViaSymbols(false)
177 MCAssembler::~MCAssembler() {
180 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
181 // Non-temporary labels should always be visible to the linker.
182 if (!Symbol.isTemporary())
185 // Absolute temporary labels are never visible.
186 if (!Symbol.isInSection())
189 // Otherwise, check if the section requires symbols even for temporary labels.
190 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
193 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
194 // Linker visible symbols define atoms.
195 if (isSymbolLinkerVisible(SD->getSymbol()))
198 // Absolute and undefined symbols have no defining atom.
199 if (!SD->getFragment())
202 // Non-linker visible symbols in sections which can't be atomized have no
204 if (!getBackend().isSectionAtomizable(
205 SD->getFragment()->getParent()->getSection()))
208 // Otherwise, return the atom for the containing fragment.
209 return SD->getFragment()->getAtom();
212 bool MCAssembler::EvaluateFixup(const MCObjectWriter &Writer,
213 const MCAsmLayout &Layout,
214 const MCFixup &Fixup, const MCFragment *DF,
215 MCValue &Target, uint64_t &Value) const {
216 ++stats::EvaluateFixup;
218 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
219 report_fatal_error("expected relocatable expression");
221 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
222 // doesn't support small relocations, but then under what criteria does the
223 // assembler allow symbol differences?
225 Value = Target.getConstant();
227 bool IsPCRel = Emitter.getFixupKindInfo(
228 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
229 bool IsResolved = true;
230 bool IsThumb = false;
231 if (const MCSymbolRefExpr *A = Target.getSymA()) {
232 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
234 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
237 if (isThumbFunc(&Sym))
240 if (const MCSymbolRefExpr *B = Target.getSymB()) {
241 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
243 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
249 IsResolved = Writer.IsFixupFullyResolved(*this, Target, IsPCRel, DF);
252 bool ShouldAlignPC = Emitter.getFixupKindInfo(
253 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsAligned;
254 // PC should be aligned to a 4-byte value.
256 Value -= Layout.getFragmentOffset(DF) + (Fixup.getOffset() & ~0x3);
258 Value -= Layout.getFragmentOffset(DF) + Fixup.getOffset();
261 // ARM fixups based from a thumb function address need to have the low
262 // bit set. The actual value is always at least 16-bit aligned, so the
263 // low bit is normally clear and available for use as an ISA flag for
271 uint64_t MCAssembler::ComputeFragmentSize(const MCFragment &F) const {
272 switch (F.getKind()) {
273 case MCFragment::FT_Data:
274 return cast<MCDataFragment>(F).getContents().size();
275 case MCFragment::FT_Fill:
276 return cast<MCFillFragment>(F).getSize();
277 case MCFragment::FT_Inst:
278 return cast<MCInstFragment>(F).getInstSize();
280 case MCFragment::FT_LEB:
281 return cast<MCLEBFragment>(F).getContents().size();
283 case MCFragment::FT_Align:
284 return cast<MCAlignFragment>(F).getSize();
286 case MCFragment::FT_Org:
287 return cast<MCOrgFragment>(F).getSize();
289 case MCFragment::FT_Dwarf:
290 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
293 assert(0 && "invalid fragment kind");
297 void MCAsmLayout::LayoutFragment(MCFragment *F) {
298 MCFragment *Prev = F->getPrevNode();
300 // We should never try to recompute something which is up-to-date.
301 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
302 // We should never try to compute the fragment layout if it's predecessor
304 assert((!Prev || isFragmentUpToDate(Prev)) &&
305 "Attempt to compute fragment before it's predecessor!");
307 ++stats::FragmentLayouts;
309 // Compute fragment offset and size.
312 Offset += Prev->Offset + getAssembler().ComputeFragmentSize(*Prev);
315 LastValidFragment[F->getParent()] = F;
318 /// WriteFragmentData - Write the \arg F data to the output file.
319 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
320 const MCFragment &F, MCObjectWriter *OW) {
321 uint64_t Start = OW->getStream().tell();
324 ++stats::EmittedFragments;
326 // FIXME: Embed in fragments instead?
327 uint64_t FragmentSize = Asm.ComputeFragmentSize(F);
328 switch (F.getKind()) {
329 case MCFragment::FT_Align: {
330 MCAlignFragment &AF = cast<MCAlignFragment>(F);
331 uint64_t Count = FragmentSize / AF.getValueSize();
333 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
335 // FIXME: This error shouldn't actually occur (the front end should emit
336 // multiple .align directives to enforce the semantics it wants), but is
337 // severe enough that we want to report it. How to handle this?
338 if (Count * AF.getValueSize() != FragmentSize)
339 report_fatal_error("undefined .align directive, value size '" +
340 Twine(AF.getValueSize()) +
341 "' is not a divisor of padding size '" +
342 Twine(FragmentSize) + "'");
344 // See if we are aligning with nops, and if so do that first to try to fill
345 // the Count bytes. Then if that did not fill any bytes or there are any
346 // bytes left to fill use the the Value and ValueSize to fill the rest.
347 // If we are aligning with nops, ask that target to emit the right data.
348 if (AF.hasEmitNops()) {
349 if (!Asm.getBackend().WriteNopData(Count, OW))
350 report_fatal_error("unable to write nop sequence of " +
351 Twine(Count) + " bytes");
355 // Otherwise, write out in multiples of the value size.
356 for (uint64_t i = 0; i != Count; ++i) {
357 switch (AF.getValueSize()) {
359 assert(0 && "Invalid size!");
360 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
361 case 2: OW->Write16(uint16_t(AF.getValue())); break;
362 case 4: OW->Write32(uint32_t(AF.getValue())); break;
363 case 8: OW->Write64(uint64_t(AF.getValue())); break;
369 case MCFragment::FT_Data: {
370 MCDataFragment &DF = cast<MCDataFragment>(F);
371 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
372 OW->WriteBytes(DF.getContents().str());
376 case MCFragment::FT_Fill: {
377 MCFillFragment &FF = cast<MCFillFragment>(F);
379 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
381 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
382 switch (FF.getValueSize()) {
384 assert(0 && "Invalid size!");
385 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
386 case 2: OW->Write16(uint16_t(FF.getValue())); break;
387 case 4: OW->Write32(uint32_t(FF.getValue())); break;
388 case 8: OW->Write64(uint64_t(FF.getValue())); break;
394 case MCFragment::FT_Inst: {
395 MCInstFragment &IF = cast<MCInstFragment>(F);
396 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
400 case MCFragment::FT_LEB: {
401 MCLEBFragment &LF = cast<MCLEBFragment>(F);
402 OW->WriteBytes(LF.getContents().str());
406 case MCFragment::FT_Org: {
407 MCOrgFragment &OF = cast<MCOrgFragment>(F);
409 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
410 OW->Write8(uint8_t(OF.getValue()));
415 case MCFragment::FT_Dwarf: {
416 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
417 OW->WriteBytes(OF.getContents().str());
422 assert(OW->getStream().tell() - Start == FragmentSize);
425 void MCAssembler::WriteSectionData(const MCSectionData *SD,
426 const MCAsmLayout &Layout,
427 MCObjectWriter *OW) const {
428 // Ignore virtual sections.
429 if (SD->getSection().isVirtualSection()) {
430 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
432 // Check that contents are only things legal inside a virtual section.
433 for (MCSectionData::const_iterator it = SD->begin(),
434 ie = SD->end(); it != ie; ++it) {
435 switch (it->getKind()) {
437 assert(0 && "Invalid fragment in virtual section!");
438 case MCFragment::FT_Data: {
439 // Check that we aren't trying to write a non-zero contents (or fixups)
440 // into a virtual section. This is to support clients which use standard
441 // directives to fill the contents of virtual sections.
442 MCDataFragment &DF = cast<MCDataFragment>(*it);
443 assert(DF.fixup_begin() == DF.fixup_end() &&
444 "Cannot have fixups in virtual section!");
445 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
446 assert(DF.getContents()[i] == 0 &&
447 "Invalid data value for virtual section!");
450 case MCFragment::FT_Align:
451 // Check that we aren't trying to write a non-zero value into a virtual
453 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
454 !cast<MCAlignFragment>(it)->getValue()) &&
455 "Invalid align in virtual section!");
457 case MCFragment::FT_Fill:
458 assert(!cast<MCFillFragment>(it)->getValueSize() &&
459 "Invalid fill in virtual section!");
467 uint64_t Start = OW->getStream().tell();
470 for (MCSectionData::const_iterator it = SD->begin(),
471 ie = SD->end(); it != ie; ++it)
472 WriteFragmentData(*this, Layout, *it, OW);
474 assert(OW->getStream().tell() - Start == Layout.getSectionAddressSize(SD));
478 uint64_t MCAssembler::HandleFixup(MCObjectWriter &Writer,
479 const MCAsmLayout &Layout,
481 const MCFixup &Fixup) {
482 // Evaluate the fixup.
485 if (!EvaluateFixup(Writer, Layout, Fixup, &F, Target, FixedValue)) {
486 // The fixup was unresolved, we need a relocation. Inform the object
487 // writer of the relocation, and give it an opportunity to adjust the
488 // fixup value if need be.
489 Writer.RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
494 void MCAssembler::Finish(MCObjectWriter *Writer) {
495 DEBUG_WITH_TYPE("mc-dump", {
496 llvm::errs() << "assembler backend - pre-layout\n--\n";
499 // Create the layout object.
500 MCAsmLayout Layout(*this);
504 // Create dummy fragments and assign section ordinals.
505 unsigned SectionIndex = 0;
506 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
507 // Create dummy fragments to eliminate any empty sections, this simplifies
509 if (it->getFragmentList().empty())
510 new MCDataFragment(it);
512 it->setOrdinal(SectionIndex++);
515 // Assign layout order indices to sections and fragments.
516 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
517 MCSectionData *SD = Layout.getSectionOrder()[i];
518 SD->setLayoutOrder(i);
520 unsigned FragmentIndex = 0;
521 for (MCSectionData::iterator it2 = SD->begin(),
522 ie2 = SD->end(); it2 != ie2; ++it2)
523 it2->setLayoutOrder(FragmentIndex++);
526 llvm::OwningPtr<MCObjectWriter> OwnWriter(0);
528 //no custom Writer_ : create the default one life-managed by OwningPtr
529 OwnWriter.reset(getBackend().createObjectWriter(OS));
530 Writer = OwnWriter.get();
532 report_fatal_error("unable to create object writer!");
535 // Layout until everything fits.
536 while (LayoutOnce(*Writer, Layout))
539 DEBUG_WITH_TYPE("mc-dump", {
540 llvm::errs() << "assembler backend - post-relaxation\n--\n";
543 // Finalize the layout, including fragment lowering.
544 FinishLayout(Layout);
546 DEBUG_WITH_TYPE("mc-dump", {
547 llvm::errs() << "assembler backend - final-layout\n--\n";
550 uint64_t StartOffset = OS.tell();
552 // Allow the object writer a chance to perform post-layout binding (for
553 // example, to set the index fields in the symbol data).
554 Writer->ExecutePostLayoutBinding(*this, Layout);
556 // Evaluate and apply the fixups, generating relocation entries as necessary.
557 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
558 for (MCSectionData::iterator it2 = it->begin(),
559 ie2 = it->end(); it2 != ie2; ++it2) {
560 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
562 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
563 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
564 MCFixup &Fixup = *it3;
565 uint64_t FixedValue = HandleFixup(*Writer, Layout, *DF, Fixup);
566 getBackend().ApplyFixup(Fixup, DF->getContents().data(),
567 DF->getContents().size(), FixedValue);
570 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
572 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
573 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
574 MCFixup &Fixup = *it3;
575 uint64_t FixedValue = HandleFixup(*Writer, Layout, *IF, Fixup);
576 getBackend().ApplyFixup(Fixup, IF->getCode().data(),
577 IF->getCode().size(), FixedValue);
583 // Write the object file.
584 Writer->WriteObject(*this, Layout);
586 stats::ObjectBytes += OS.tell() - StartOffset;
589 bool MCAssembler::FixupNeedsRelaxation(const MCObjectWriter &Writer,
590 const MCFixup &Fixup,
591 const MCFragment *DF,
592 const MCAsmLayout &Layout) const {
596 // If we cannot resolve the fixup value, it requires relaxation.
599 if (!EvaluateFixup(Writer, Layout, Fixup, DF, Target, Value))
602 // Otherwise, relax if the value is too big for a (signed) i8.
604 // FIXME: This is target dependent!
605 return int64_t(Value) != int64_t(int8_t(Value));
608 bool MCAssembler::FragmentNeedsRelaxation(const MCObjectWriter &Writer,
609 const MCInstFragment *IF,
610 const MCAsmLayout &Layout) const {
611 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
612 // are intentionally pushing out inst fragments, or because we relaxed a
613 // previous instruction to one that doesn't need relaxation.
614 if (!getBackend().MayNeedRelaxation(IF->getInst()))
617 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
618 ie = IF->fixup_end(); it != ie; ++it)
619 if (FixupNeedsRelaxation(Writer, *it, IF, Layout))
625 bool MCAssembler::RelaxInstruction(const MCObjectWriter &Writer,
627 MCInstFragment &IF) {
628 if (!FragmentNeedsRelaxation(Writer, &IF, Layout))
631 ++stats::RelaxedInstructions;
633 // FIXME-PERF: We could immediately lower out instructions if we can tell
634 // they are fully resolved, to avoid retesting on later passes.
636 // Relax the fragment.
639 getBackend().RelaxInstruction(IF.getInst(), Relaxed);
641 // Encode the new instruction.
643 // FIXME-PERF: If it matters, we could let the target do this. It can
644 // probably do so more efficiently in many cases.
645 SmallVector<MCFixup, 4> Fixups;
646 SmallString<256> Code;
647 raw_svector_ostream VecOS(Code);
648 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
651 // Update the instruction fragment.
654 IF.getFixups().clear();
655 // FIXME: Eliminate copy.
656 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
657 IF.getFixups().push_back(Fixups[i]);
662 bool MCAssembler::RelaxOrg(const MCObjectWriter &Writer,
665 int64_t TargetLocation;
666 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
667 report_fatal_error("expected assembly-time absolute expression");
669 // FIXME: We need a way to communicate this error.
670 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
671 int64_t Offset = TargetLocation - FragmentOffset;
672 if (Offset < 0 || Offset >= 0x40000000)
673 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
674 "' (at offset '" + Twine(FragmentOffset) + "')");
676 unsigned OldSize = OF.getSize();
678 return OldSize != OF.getSize();
681 bool MCAssembler::RelaxLEB(const MCObjectWriter &Writer,
685 uint64_t OldSize = LF.getContents().size();
686 LF.getValue().EvaluateAsAbsolute(Value, Layout);
687 SmallString<8> &Data = LF.getContents();
689 raw_svector_ostream OSE(Data);
691 MCObjectWriter::EncodeSLEB128(Value, OSE);
693 MCObjectWriter::EncodeULEB128(Value, OSE);
695 return OldSize != LF.getContents().size();
698 bool MCAssembler::RelaxDwarfLineAddr(const MCObjectWriter &Writer,
700 MCDwarfLineAddrFragment &DF) {
701 int64_t AddrDelta = 0;
702 uint64_t OldSize = DF.getContents().size();
703 DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
705 LineDelta = DF.getLineDelta();
706 SmallString<8> &Data = DF.getContents();
708 raw_svector_ostream OSE(Data);
709 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
711 return OldSize != Data.size();
714 bool MCAssembler::RelaxAlignment(const MCObjectWriter &Writer,
716 MCAlignFragment &AF) {
717 unsigned Offset = Layout.getFragmentOffset(&AF);
718 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
719 if (Size > AF.getMaxBytesToEmit())
721 unsigned OldSize = AF.getSize();
723 return OldSize != Size;
726 bool MCAssembler::LayoutOnce(const MCObjectWriter &Writer,
727 MCAsmLayout &Layout) {
728 ++stats::RelaxationSteps;
730 // Scan for fragments that need relaxation.
731 bool WasRelaxed = false;
732 for (iterator it = begin(), ie = end(); it != ie; ++it) {
733 MCSectionData &SD = *it;
734 MCFragment *FirstInvalidFragment = NULL;
736 for (MCSectionData::iterator it2 = SD.begin(),
737 ie2 = SD.end(); it2 != ie2; ++it2) {
738 // Check if this is an fragment that needs relaxation.
739 bool relaxedFrag = false;
740 switch(it2->getKind()) {
743 case MCFragment::FT_Align:
744 relaxedFrag = RelaxAlignment(Writer, Layout,
745 *cast<MCAlignFragment>(it2));
747 case MCFragment::FT_Inst:
748 relaxedFrag = RelaxInstruction(Writer, Layout,
749 *cast<MCInstFragment>(it2));
751 case MCFragment::FT_Org:
752 relaxedFrag = RelaxOrg(Writer, Layout, *cast<MCOrgFragment>(it2));
754 case MCFragment::FT_Dwarf:
755 relaxedFrag = RelaxDwarfLineAddr(Writer, Layout,
756 *cast<MCDwarfLineAddrFragment>(it2));
758 case MCFragment::FT_LEB:
759 relaxedFrag = RelaxLEB(Writer, Layout, *cast<MCLEBFragment>(it2));
762 // Update the layout, and remember that we relaxed.
763 if (relaxedFrag && !FirstInvalidFragment)
764 FirstInvalidFragment = it2;
765 WasRelaxed |= relaxedFrag;
767 if (FirstInvalidFragment)
768 Layout.Invalidate(FirstInvalidFragment);
774 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
775 // The layout is done. Mark every fragment as valid.
776 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
777 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
785 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
786 OS << "<MCFixup" << " Offset:" << AF.getOffset()
787 << " Value:" << *AF.getValue()
788 << " Kind:" << AF.getKind() << ">";
794 void MCFragment::dump() {
795 raw_ostream &OS = llvm::errs();
799 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
800 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
801 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
802 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
803 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
804 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
805 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
808 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
809 << " Offset:" << Offset << ">";
812 case MCFragment::FT_Align: {
813 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
814 if (AF->hasEmitNops())
815 OS << " (emit nops)";
817 OS << " Alignment:" << AF->getAlignment()
818 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
819 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
822 case MCFragment::FT_Data: {
823 const MCDataFragment *DF = cast<MCDataFragment>(this);
826 const SmallVectorImpl<char> &Contents = DF->getContents();
827 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
829 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
831 OS << "] (" << Contents.size() << " bytes)";
833 if (!DF->getFixups().empty()) {
836 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
837 ie = DF->fixup_end(); it != ie; ++it) {
838 if (it != DF->fixup_begin()) OS << ",\n ";
845 case MCFragment::FT_Fill: {
846 const MCFillFragment *FF = cast<MCFillFragment>(this);
847 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
848 << " Size:" << FF->getSize();
851 case MCFragment::FT_Inst: {
852 const MCInstFragment *IF = cast<MCInstFragment>(this);
855 IF->getInst().dump_pretty(OS);
858 case MCFragment::FT_Org: {
859 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
861 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
864 case MCFragment::FT_Dwarf: {
865 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
867 OS << " AddrDelta:" << OF->getAddrDelta()
868 << " LineDelta:" << OF->getLineDelta();
871 case MCFragment::FT_LEB: {
872 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
874 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
881 void MCSectionData::dump() {
882 raw_ostream &OS = llvm::errs();
884 OS << "<MCSectionData";
885 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
886 for (iterator it = begin(), ie = end(); it != ie; ++it) {
887 if (it != begin()) OS << ",\n ";
893 void MCSymbolData::dump() {
894 raw_ostream &OS = llvm::errs();
896 OS << "<MCSymbolData Symbol:" << getSymbol()
897 << " Fragment:" << getFragment() << " Offset:" << getOffset()
898 << " Flags:" << getFlags() << " Index:" << getIndex();
900 OS << " (common, size:" << getCommonSize()
901 << " align: " << getCommonAlignment() << ")";
904 if (isPrivateExtern())
905 OS << " (private extern)";
909 void MCAssembler::dump() {
910 raw_ostream &OS = llvm::errs();
912 OS << "<MCAssembler\n";
913 OS << " Sections:[\n ";
914 for (iterator it = begin(), ie = end(); it != ie; ++it) {
915 if (it != begin()) OS << ",\n ";
921 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
922 if (it != symbol_begin()) OS << ",\n ";