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/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCFixupKindInfo.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/LEB128.h"
36 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
37 STATISTIC(evaluateFixup, "Number of evaluated fixups");
38 STATISTIC(FragmentLayouts, "Number of fragment layouts");
39 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
40 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
41 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
45 // FIXME FIXME FIXME: There are number of places in this file where we convert
46 // what is a 64-bit assembler value used for computation into a value in the
47 // object file, which may truncate it. We should detect that truncation where
48 // invalid and report errors back.
52 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
53 : Assembler(Asm), LastValidFragment()
55 // Compute the section layout order. Virtual sections must go last.
56 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
57 if (!it->getSection().isVirtualSection())
58 SectionOrder.push_back(&*it);
59 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
60 if (it->getSection().isVirtualSection())
61 SectionOrder.push_back(&*it);
64 bool MCAsmLayout::isFragmentUpToDate(const MCFragment *F) const {
65 const MCSectionData &SD = *F->getParent();
66 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
69 assert(LastValid->getParent() == F->getParent());
70 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
73 void MCAsmLayout::Invalidate(MCFragment *F) {
74 // If this fragment wasn't already up-to-date, we don't need to do anything.
75 if (!isFragmentUpToDate(F))
78 // Otherwise, reset the last valid fragment to this fragment.
79 const MCSectionData &SD = *F->getParent();
80 LastValidFragment[&SD] = F;
83 void MCAsmLayout::EnsureValid(const MCFragment *F) const {
84 MCSectionData &SD = *F->getParent();
86 MCFragment *Cur = LastValidFragment[&SD];
90 Cur = Cur->getNextNode();
92 // Advance the layout position until the fragment is up-to-date.
93 while (!isFragmentUpToDate(F)) {
94 const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
95 Cur = Cur->getNextNode();
99 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
101 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
105 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
106 const MCSymbol &S = SD->getSymbol();
108 // If this is a variable, then recursively evaluate now.
109 if (S.isVariable()) {
111 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
112 report_fatal_error("unable to evaluate offset for variable '" +
115 // Verify that any used symbols are defined.
116 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
117 report_fatal_error("unable to evaluate offset to undefined symbol '" +
118 Target.getSymA()->getSymbol().getName() + "'");
119 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
120 report_fatal_error("unable to evaluate offset to undefined symbol '" +
121 Target.getSymB()->getSymbol().getName() + "'");
123 uint64_t Offset = Target.getConstant();
124 if (Target.getSymA())
125 Offset += getSymbolOffset(&Assembler.getSymbolData(
126 Target.getSymA()->getSymbol()));
127 if (Target.getSymB())
128 Offset -= getSymbolOffset(&Assembler.getSymbolData(
129 Target.getSymB()->getSymbol()));
133 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
134 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
137 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
138 // The size is the last fragment's end offset.
139 const MCFragment &F = SD->getFragmentList().back();
140 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
143 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
144 // Virtual sections have no file size.
145 if (SD->getSection().isVirtualSection())
148 // Otherwise, the file size is the same as the address space size.
149 return getSectionAddressSize(SD);
154 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
157 MCFragment::~MCFragment() {
160 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
161 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
164 Parent->getFragmentList().push_back(this);
169 MCSectionData::MCSectionData() : Section(0) {}
171 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
172 : Section(&_Section),
173 Ordinal(~UINT32_C(0)),
175 HasInstructions(false)
178 A->getSectionList().push_back(this);
183 MCSymbolData::MCSymbolData() : Symbol(0) {}
185 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
186 uint64_t _Offset, MCAssembler *A)
187 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
188 IsExternal(false), IsPrivateExtern(false),
189 CommonSize(0), SymbolSize(0), CommonAlign(0),
193 A->getSymbolList().push_back(this);
198 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
199 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
201 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
202 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false) {
205 MCAssembler::~MCAssembler() {
208 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
209 // Non-temporary labels should always be visible to the linker.
210 if (!Symbol.isTemporary())
213 // Absolute temporary labels are never visible.
214 if (!Symbol.isInSection())
217 // Otherwise, check if the section requires symbols even for temporary labels.
218 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
221 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
222 // Linker visible symbols define atoms.
223 if (isSymbolLinkerVisible(SD->getSymbol()))
226 // Absolute and undefined symbols have no defining atom.
227 if (!SD->getFragment())
230 // Non-linker visible symbols in sections which can't be atomized have no
232 if (!getBackend().isSectionAtomizable(
233 SD->getFragment()->getParent()->getSection()))
236 // Otherwise, return the atom for the containing fragment.
237 return SD->getFragment()->getAtom();
240 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
241 const MCFixup &Fixup, const MCFragment *DF,
242 MCValue &Target, uint64_t &Value) const {
243 ++stats::evaluateFixup;
245 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
246 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
248 bool IsPCRel = Backend.getFixupKindInfo(
249 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
253 if (Target.getSymB()) {
255 } else if (!Target.getSymA()) {
258 const MCSymbolRefExpr *A = Target.getSymA();
259 const MCSymbol &SA = A->getSymbol();
260 if (A->getKind() != MCSymbolRefExpr::VK_None ||
261 SA.AliasedSymbol().isUndefined()) {
264 const MCSymbolData &DataA = getSymbolData(SA);
266 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
271 IsResolved = Target.isAbsolute();
274 Value = Target.getConstant();
276 if (const MCSymbolRefExpr *A = Target.getSymA()) {
277 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
279 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
281 if (const MCSymbolRefExpr *B = Target.getSymB()) {
282 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
284 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
288 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
289 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
290 assert((ShouldAlignPC ? IsPCRel : true) &&
291 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
294 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
296 // A number of ARM fixups in Thumb mode require that the effective PC
297 // address be determined as the 32-bit aligned version of the actual offset.
298 if (ShouldAlignPC) Offset &= ~0x3;
302 // Let the backend adjust the fixup value if necessary, including whether
303 // we need a relocation.
304 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
310 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
311 const MCFragment &F) const {
312 switch (F.getKind()) {
313 case MCFragment::FT_Data:
314 return cast<MCDataFragment>(F).getContents().size();
315 case MCFragment::FT_Fill:
316 return cast<MCFillFragment>(F).getSize();
317 case MCFragment::FT_Inst:
318 return cast<MCInstFragment>(F).getInstSize();
320 case MCFragment::FT_LEB:
321 return cast<MCLEBFragment>(F).getContents().size();
323 case MCFragment::FT_Align: {
324 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
325 unsigned Offset = Layout.getFragmentOffset(&AF);
326 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
327 // If we are padding with nops, force the padding to be larger than the
329 if (Size > 0 && AF.hasEmitNops()) {
330 while (Size % getBackend().getMinimumNopSize())
331 Size += AF.getAlignment();
333 if (Size > AF.getMaxBytesToEmit())
338 case MCFragment::FT_Org: {
339 MCOrgFragment &OF = cast<MCOrgFragment>(F);
340 int64_t TargetLocation;
341 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
342 report_fatal_error("expected assembly-time absolute expression");
344 // FIXME: We need a way to communicate this error.
345 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
346 int64_t Size = TargetLocation - FragmentOffset;
347 if (Size < 0 || Size >= 0x40000000)
348 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
349 "' (at offset '" + Twine(FragmentOffset) + "')");
353 case MCFragment::FT_Dwarf:
354 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
355 case MCFragment::FT_DwarfFrame:
356 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
359 llvm_unreachable("invalid fragment kind");
362 void MCAsmLayout::LayoutFragment(MCFragment *F) {
363 MCFragment *Prev = F->getPrevNode();
365 // We should never try to recompute something which is up-to-date.
366 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
367 // We should never try to compute the fragment layout if it's predecessor
369 assert((!Prev || isFragmentUpToDate(Prev)) &&
370 "Attempt to compute fragment before it's predecessor!");
372 ++stats::FragmentLayouts;
374 // Compute fragment offset and size.
377 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
380 LastValidFragment[F->getParent()] = F;
383 /// WriteFragmentData - Write the \p F data to the output file.
384 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
385 const MCFragment &F) {
386 MCObjectWriter *OW = &Asm.getWriter();
387 uint64_t Start = OW->getStream().tell();
390 ++stats::EmittedFragments;
392 // FIXME: Embed in fragments instead?
393 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
394 switch (F.getKind()) {
395 case MCFragment::FT_Align: {
396 MCAlignFragment &AF = cast<MCAlignFragment>(F);
397 uint64_t Count = FragmentSize / AF.getValueSize();
399 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
401 // FIXME: This error shouldn't actually occur (the front end should emit
402 // multiple .align directives to enforce the semantics it wants), but is
403 // severe enough that we want to report it. How to handle this?
404 if (Count * AF.getValueSize() != FragmentSize)
405 report_fatal_error("undefined .align directive, value size '" +
406 Twine(AF.getValueSize()) +
407 "' is not a divisor of padding size '" +
408 Twine(FragmentSize) + "'");
410 // See if we are aligning with nops, and if so do that first to try to fill
411 // the Count bytes. Then if that did not fill any bytes or there are any
412 // bytes left to fill use the Value and ValueSize to fill the rest.
413 // If we are aligning with nops, ask that target to emit the right data.
414 if (AF.hasEmitNops()) {
415 if (!Asm.getBackend().writeNopData(Count, OW))
416 report_fatal_error("unable to write nop sequence of " +
417 Twine(Count) + " bytes");
421 // Otherwise, write out in multiples of the value size.
422 for (uint64_t i = 0; i != Count; ++i) {
423 switch (AF.getValueSize()) {
424 default: llvm_unreachable("Invalid size!");
425 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
426 case 2: OW->Write16(uint16_t(AF.getValue())); break;
427 case 4: OW->Write32(uint32_t(AF.getValue())); break;
428 case 8: OW->Write64(uint64_t(AF.getValue())); break;
434 case MCFragment::FT_Data: {
435 MCDataFragment &DF = cast<MCDataFragment>(F);
436 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
437 OW->WriteBytes(DF.getContents().str());
441 case MCFragment::FT_Fill: {
442 MCFillFragment &FF = cast<MCFillFragment>(F);
444 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
446 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
447 switch (FF.getValueSize()) {
448 default: llvm_unreachable("Invalid size!");
449 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
450 case 2: OW->Write16(uint16_t(FF.getValue())); break;
451 case 4: OW->Write32(uint32_t(FF.getValue())); break;
452 case 8: OW->Write64(uint64_t(FF.getValue())); break;
458 case MCFragment::FT_Inst: {
459 MCInstFragment &IF = cast<MCInstFragment>(F);
460 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
464 case MCFragment::FT_LEB: {
465 MCLEBFragment &LF = cast<MCLEBFragment>(F);
466 OW->WriteBytes(LF.getContents().str());
470 case MCFragment::FT_Org: {
471 MCOrgFragment &OF = cast<MCOrgFragment>(F);
473 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
474 OW->Write8(uint8_t(OF.getValue()));
479 case MCFragment::FT_Dwarf: {
480 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
481 OW->WriteBytes(OF.getContents().str());
484 case MCFragment::FT_DwarfFrame: {
485 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
486 OW->WriteBytes(CF.getContents().str());
491 assert(OW->getStream().tell() - Start == FragmentSize);
494 void MCAssembler::writeSectionData(const MCSectionData *SD,
495 const MCAsmLayout &Layout) const {
496 // Ignore virtual sections.
497 if (SD->getSection().isVirtualSection()) {
498 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
500 // Check that contents are only things legal inside a virtual section.
501 for (MCSectionData::const_iterator it = SD->begin(),
502 ie = SD->end(); it != ie; ++it) {
503 switch (it->getKind()) {
504 default: llvm_unreachable("Invalid fragment in virtual section!");
505 case MCFragment::FT_Data: {
506 // Check that we aren't trying to write a non-zero contents (or fixups)
507 // into a virtual section. This is to support clients which use standard
508 // directives to fill the contents of virtual sections.
509 MCDataFragment &DF = cast<MCDataFragment>(*it);
510 assert(DF.fixup_begin() == DF.fixup_end() &&
511 "Cannot have fixups in virtual section!");
512 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
513 assert(DF.getContents()[i] == 0 &&
514 "Invalid data value for virtual section!");
517 case MCFragment::FT_Align:
518 // Check that we aren't trying to write a non-zero value into a virtual
520 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
521 !cast<MCAlignFragment>(it)->getValue()) &&
522 "Invalid align in virtual section!");
524 case MCFragment::FT_Fill:
525 assert(!cast<MCFillFragment>(it)->getValueSize() &&
526 "Invalid fill in virtual section!");
534 uint64_t Start = getWriter().getStream().tell();
537 for (MCSectionData::const_iterator it = SD->begin(),
538 ie = SD->end(); it != ie; ++it)
539 WriteFragmentData(*this, Layout, *it);
541 assert(getWriter().getStream().tell() - Start ==
542 Layout.getSectionAddressSize(SD));
546 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
548 const MCFixup &Fixup) {
549 // Evaluate the fixup.
552 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
553 // The fixup was unresolved, we need a relocation. Inform the object
554 // writer of the relocation, and give it an opportunity to adjust the
555 // fixup value if need be.
556 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
561 void MCAssembler::Finish() {
562 DEBUG_WITH_TYPE("mc-dump", {
563 llvm::errs() << "assembler backend - pre-layout\n--\n";
566 // Create the layout object.
567 MCAsmLayout Layout(*this);
569 // Create dummy fragments and assign section ordinals.
570 unsigned SectionIndex = 0;
571 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
572 // Create dummy fragments to eliminate any empty sections, this simplifies
574 if (it->getFragmentList().empty())
575 new MCDataFragment(it);
577 it->setOrdinal(SectionIndex++);
580 // Assign layout order indices to sections and fragments.
581 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
582 MCSectionData *SD = Layout.getSectionOrder()[i];
583 SD->setLayoutOrder(i);
585 unsigned FragmentIndex = 0;
586 for (MCSectionData::iterator it2 = SD->begin(),
587 ie2 = SD->end(); it2 != ie2; ++it2)
588 it2->setLayoutOrder(FragmentIndex++);
591 // Layout until everything fits.
592 while (layoutOnce(Layout))
595 DEBUG_WITH_TYPE("mc-dump", {
596 llvm::errs() << "assembler backend - post-relaxation\n--\n";
599 // Finalize the layout, including fragment lowering.
600 finishLayout(Layout);
602 DEBUG_WITH_TYPE("mc-dump", {
603 llvm::errs() << "assembler backend - final-layout\n--\n";
606 uint64_t StartOffset = OS.tell();
608 // Allow the object writer a chance to perform post-layout binding (for
609 // example, to set the index fields in the symbol data).
610 getWriter().ExecutePostLayoutBinding(*this, Layout);
612 // Evaluate and apply the fixups, generating relocation entries as necessary.
613 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
614 for (MCSectionData::iterator it2 = it->begin(),
615 ie2 = it->end(); it2 != ie2; ++it2) {
616 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
618 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
619 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
620 MCFixup &Fixup = *it3;
621 uint64_t FixedValue = handleFixup(Layout, *DF, Fixup);
622 getBackend().applyFixup(Fixup, DF->getContents().data(),
623 DF->getContents().size(), FixedValue);
626 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
628 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
629 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
630 MCFixup &Fixup = *it3;
631 uint64_t FixedValue = handleFixup(Layout, *IF, Fixup);
632 getBackend().applyFixup(Fixup, IF->getCode().data(),
633 IF->getCode().size(), FixedValue);
639 // Write the object file.
640 getWriter().WriteObject(*this, Layout);
642 stats::ObjectBytes += OS.tell() - StartOffset;
645 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
646 const MCInstFragment *DF,
647 const MCAsmLayout &Layout) const {
651 // If we cannot resolve the fixup value, it requires relaxation.
654 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
657 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
660 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
661 const MCAsmLayout &Layout) const {
662 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
663 // are intentionally pushing out inst fragments, or because we relaxed a
664 // previous instruction to one that doesn't need relaxation.
665 if (!getBackend().mayNeedRelaxation(IF->getInst()))
668 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
669 ie = IF->fixup_end(); it != ie; ++it)
670 if (fixupNeedsRelaxation(*it, IF, Layout))
676 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
677 MCInstFragment &IF) {
678 if (!fragmentNeedsRelaxation(&IF, Layout))
681 ++stats::RelaxedInstructions;
683 // FIXME-PERF: We could immediately lower out instructions if we can tell
684 // they are fully resolved, to avoid retesting on later passes.
686 // Relax the fragment.
689 getBackend().relaxInstruction(IF.getInst(), Relaxed);
691 // Encode the new instruction.
693 // FIXME-PERF: If it matters, we could let the target do this. It can
694 // probably do so more efficiently in many cases.
695 SmallVector<MCFixup, 4> Fixups;
696 SmallString<256> Code;
697 raw_svector_ostream VecOS(Code);
698 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
701 // Update the instruction fragment.
704 IF.getFixups().clear();
705 // FIXME: Eliminate copy.
706 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
707 IF.getFixups().push_back(Fixups[i]);
712 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
714 uint64_t OldSize = LF.getContents().size();
715 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
718 SmallString<8> &Data = LF.getContents();
720 raw_svector_ostream OSE(Data);
722 encodeSLEB128(Value, OSE);
724 encodeULEB128(Value, OSE);
726 return OldSize != LF.getContents().size();
729 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
730 MCDwarfLineAddrFragment &DF) {
731 int64_t AddrDelta = 0;
732 uint64_t OldSize = DF.getContents().size();
733 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
737 LineDelta = DF.getLineDelta();
738 SmallString<8> &Data = DF.getContents();
740 raw_svector_ostream OSE(Data);
741 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
743 return OldSize != Data.size();
746 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
747 MCDwarfCallFrameFragment &DF) {
748 int64_t AddrDelta = 0;
749 uint64_t OldSize = DF.getContents().size();
750 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
753 SmallString<8> &Data = DF.getContents();
755 raw_svector_ostream OSE(Data);
756 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
758 return OldSize != Data.size();
761 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
763 MCFragment *FirstInvalidFragment = NULL;
764 // Scan for fragments that need relaxation.
765 for (MCSectionData::iterator it2 = SD.begin(),
766 ie2 = SD.end(); it2 != ie2; ++it2) {
767 // Check if this is an fragment that needs relaxation.
768 bool relaxedFrag = false;
769 switch(it2->getKind()) {
772 case MCFragment::FT_Inst:
773 relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
775 case MCFragment::FT_Dwarf:
776 relaxedFrag = relaxDwarfLineAddr(Layout,
777 *cast<MCDwarfLineAddrFragment>(it2));
779 case MCFragment::FT_DwarfFrame:
781 relaxDwarfCallFrameFragment(Layout,
782 *cast<MCDwarfCallFrameFragment>(it2));
784 case MCFragment::FT_LEB:
785 relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
788 // Update the layout, and remember that we relaxed.
789 if (relaxedFrag && !FirstInvalidFragment)
790 FirstInvalidFragment = it2;
792 if (FirstInvalidFragment) {
793 Layout.Invalidate(FirstInvalidFragment);
799 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
800 ++stats::RelaxationSteps;
802 bool WasRelaxed = false;
803 for (iterator it = begin(), ie = end(); it != ie; ++it) {
804 MCSectionData &SD = *it;
805 while(layoutSectionOnce(Layout, SD))
812 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
813 // The layout is done. Mark every fragment as valid.
814 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
815 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
823 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
824 OS << "<MCFixup" << " Offset:" << AF.getOffset()
825 << " Value:" << *AF.getValue()
826 << " Kind:" << AF.getKind() << ">";
832 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
833 void MCFragment::dump() {
834 raw_ostream &OS = llvm::errs();
838 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
839 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
840 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
841 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
842 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
843 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
844 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
845 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
848 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
849 << " Offset:" << Offset << ">";
852 case MCFragment::FT_Align: {
853 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
854 if (AF->hasEmitNops())
855 OS << " (emit nops)";
857 OS << " Alignment:" << AF->getAlignment()
858 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
859 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
862 case MCFragment::FT_Data: {
863 const MCDataFragment *DF = cast<MCDataFragment>(this);
866 const SmallVectorImpl<char> &Contents = DF->getContents();
867 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
869 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
871 OS << "] (" << Contents.size() << " bytes)";
873 if (!DF->getFixups().empty()) {
876 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
877 ie = DF->fixup_end(); it != ie; ++it) {
878 if (it != DF->fixup_begin()) OS << ",\n ";
885 case MCFragment::FT_Fill: {
886 const MCFillFragment *FF = cast<MCFillFragment>(this);
887 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
888 << " Size:" << FF->getSize();
891 case MCFragment::FT_Inst: {
892 const MCInstFragment *IF = cast<MCInstFragment>(this);
895 IF->getInst().dump_pretty(OS);
898 case MCFragment::FT_Org: {
899 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
901 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
904 case MCFragment::FT_Dwarf: {
905 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
907 OS << " AddrDelta:" << OF->getAddrDelta()
908 << " LineDelta:" << OF->getLineDelta();
911 case MCFragment::FT_DwarfFrame: {
912 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
914 OS << " AddrDelta:" << CF->getAddrDelta();
917 case MCFragment::FT_LEB: {
918 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
920 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
927 void MCSectionData::dump() {
928 raw_ostream &OS = llvm::errs();
930 OS << "<MCSectionData";
931 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
932 for (iterator it = begin(), ie = end(); it != ie; ++it) {
933 if (it != begin()) OS << ",\n ";
939 void MCSymbolData::dump() {
940 raw_ostream &OS = llvm::errs();
942 OS << "<MCSymbolData Symbol:" << getSymbol()
943 << " Fragment:" << getFragment() << " Offset:" << getOffset()
944 << " Flags:" << getFlags() << " Index:" << getIndex();
946 OS << " (common, size:" << getCommonSize()
947 << " align: " << getCommonAlignment() << ")";
950 if (isPrivateExtern())
951 OS << " (private extern)";
955 void MCAssembler::dump() {
956 raw_ostream &OS = llvm::errs();
958 OS << "<MCAssembler\n";
959 OS << " Sections:[\n ";
960 for (iterator it = begin(), ie = end(); it != ie; ++it) {
961 if (it != begin()) OS << ",\n ";
967 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
968 if (it != symbol_begin()) OS << ",\n ";
975 // anchors for MC*Fragment vtables
976 void MCDataFragment::anchor() { }
977 void MCInstFragment::anchor() { }
978 void MCAlignFragment::anchor() { }
979 void MCFillFragment::anchor() { }
980 void MCOrgFragment::anchor() { }
981 void MCLEBFragment::anchor() { }
982 void MCDwarfLineAddrFragment::anchor() { }
983 void MCDwarfCallFrameFragment::anchor() { }