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)
206 MCAssembler::~MCAssembler() {
209 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
210 // Non-temporary labels should always be visible to the linker.
211 if (!Symbol.isTemporary())
214 // Absolute temporary labels are never visible.
215 if (!Symbol.isInSection())
218 // Otherwise, check if the section requires symbols even for temporary labels.
219 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
222 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
223 // Linker visible symbols define atoms.
224 if (isSymbolLinkerVisible(SD->getSymbol()))
227 // Absolute and undefined symbols have no defining atom.
228 if (!SD->getFragment())
231 // Non-linker visible symbols in sections which can't be atomized have no
233 if (!getBackend().isSectionAtomizable(
234 SD->getFragment()->getParent()->getSection()))
237 // Otherwise, return the atom for the containing fragment.
238 return SD->getFragment()->getAtom();
241 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
242 const MCFixup &Fixup, const MCFragment *DF,
243 MCValue &Target, uint64_t &Value) const {
244 ++stats::evaluateFixup;
246 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
247 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
249 bool IsPCRel = Backend.getFixupKindInfo(
250 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
254 if (Target.getSymB()) {
256 } else if (!Target.getSymA()) {
259 const MCSymbolRefExpr *A = Target.getSymA();
260 const MCSymbol &SA = A->getSymbol();
261 if (A->getKind() != MCSymbolRefExpr::VK_None ||
262 SA.AliasedSymbol().isUndefined()) {
265 const MCSymbolData &DataA = getSymbolData(SA);
267 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
272 IsResolved = Target.isAbsolute();
275 Value = Target.getConstant();
277 if (const MCSymbolRefExpr *A = Target.getSymA()) {
278 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
280 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
282 if (const MCSymbolRefExpr *B = Target.getSymB()) {
283 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
285 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
289 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
290 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
291 assert((ShouldAlignPC ? IsPCRel : true) &&
292 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
295 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
297 // A number of ARM fixups in Thumb mode require that the effective PC
298 // address be determined as the 32-bit aligned version of the actual offset.
299 if (ShouldAlignPC) Offset &= ~0x3;
303 // Let the backend adjust the fixup value if necessary, including whether
304 // we need a relocation.
305 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
311 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
312 const MCFragment &F) const {
313 switch (F.getKind()) {
314 case MCFragment::FT_Data:
315 return cast<MCDataFragment>(F).getContents().size();
316 case MCFragment::FT_Fill:
317 return cast<MCFillFragment>(F).getSize();
318 case MCFragment::FT_Inst:
319 return cast<MCInstFragment>(F).getInstSize();
321 case MCFragment::FT_LEB:
322 return cast<MCLEBFragment>(F).getContents().size();
324 case MCFragment::FT_Align: {
325 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
326 unsigned Offset = Layout.getFragmentOffset(&AF);
327 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
328 // If we are padding with nops, force the padding to be larger than the
330 if (Size > 0 && AF.hasEmitNops()) {
331 while (Size % getBackend().getMinimumNopSize())
332 Size += AF.getAlignment();
334 if (Size > AF.getMaxBytesToEmit())
339 case MCFragment::FT_Org: {
340 MCOrgFragment &OF = cast<MCOrgFragment>(F);
341 int64_t TargetLocation;
342 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
343 report_fatal_error("expected assembly-time absolute expression");
345 // FIXME: We need a way to communicate this error.
346 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
347 int64_t Size = TargetLocation - FragmentOffset;
348 if (Size < 0 || Size >= 0x40000000)
349 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
350 "' (at offset '" + Twine(FragmentOffset) + "')");
354 case MCFragment::FT_Dwarf:
355 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
356 case MCFragment::FT_DwarfFrame:
357 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
360 llvm_unreachable("invalid fragment kind");
363 void MCAsmLayout::LayoutFragment(MCFragment *F) {
364 MCFragment *Prev = F->getPrevNode();
366 // We should never try to recompute something which is up-to-date.
367 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
368 // We should never try to compute the fragment layout if it's predecessor
370 assert((!Prev || isFragmentUpToDate(Prev)) &&
371 "Attempt to compute fragment before it's predecessor!");
373 ++stats::FragmentLayouts;
375 // Compute fragment offset and size.
378 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
381 LastValidFragment[F->getParent()] = F;
384 /// WriteFragmentData - Write the \arg F data to the output file.
385 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
386 const MCFragment &F) {
387 MCObjectWriter *OW = &Asm.getWriter();
388 uint64_t Start = OW->getStream().tell();
391 ++stats::EmittedFragments;
393 // FIXME: Embed in fragments instead?
394 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
395 switch (F.getKind()) {
396 case MCFragment::FT_Align: {
397 MCAlignFragment &AF = cast<MCAlignFragment>(F);
398 uint64_t Count = FragmentSize / AF.getValueSize();
400 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
402 // FIXME: This error shouldn't actually occur (the front end should emit
403 // multiple .align directives to enforce the semantics it wants), but is
404 // severe enough that we want to report it. How to handle this?
405 if (Count * AF.getValueSize() != FragmentSize)
406 report_fatal_error("undefined .align directive, value size '" +
407 Twine(AF.getValueSize()) +
408 "' is not a divisor of padding size '" +
409 Twine(FragmentSize) + "'");
411 // See if we are aligning with nops, and if so do that first to try to fill
412 // the Count bytes. Then if that did not fill any bytes or there are any
413 // bytes left to fill use the Value and ValueSize to fill the rest.
414 // If we are aligning with nops, ask that target to emit the right data.
415 if (AF.hasEmitNops()) {
416 if (!Asm.getBackend().writeNopData(Count, OW))
417 report_fatal_error("unable to write nop sequence of " +
418 Twine(Count) + " bytes");
422 // Otherwise, write out in multiples of the value size.
423 for (uint64_t i = 0; i != Count; ++i) {
424 switch (AF.getValueSize()) {
425 default: llvm_unreachable("Invalid size!");
426 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
427 case 2: OW->Write16(uint16_t(AF.getValue())); break;
428 case 4: OW->Write32(uint32_t(AF.getValue())); break;
429 case 8: OW->Write64(uint64_t(AF.getValue())); break;
435 case MCFragment::FT_Data: {
436 MCDataFragment &DF = cast<MCDataFragment>(F);
437 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
438 OW->WriteBytes(DF.getContents().str());
442 case MCFragment::FT_Fill: {
443 MCFillFragment &FF = cast<MCFillFragment>(F);
445 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
447 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
448 switch (FF.getValueSize()) {
449 default: llvm_unreachable("Invalid size!");
450 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
451 case 2: OW->Write16(uint16_t(FF.getValue())); break;
452 case 4: OW->Write32(uint32_t(FF.getValue())); break;
453 case 8: OW->Write64(uint64_t(FF.getValue())); break;
459 case MCFragment::FT_Inst: {
460 MCInstFragment &IF = cast<MCInstFragment>(F);
461 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
465 case MCFragment::FT_LEB: {
466 MCLEBFragment &LF = cast<MCLEBFragment>(F);
467 OW->WriteBytes(LF.getContents().str());
471 case MCFragment::FT_Org: {
472 MCOrgFragment &OF = cast<MCOrgFragment>(F);
474 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
475 OW->Write8(uint8_t(OF.getValue()));
480 case MCFragment::FT_Dwarf: {
481 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
482 OW->WriteBytes(OF.getContents().str());
485 case MCFragment::FT_DwarfFrame: {
486 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
487 OW->WriteBytes(CF.getContents().str());
492 assert(OW->getStream().tell() - Start == FragmentSize);
495 void MCAssembler::writeSectionData(const MCSectionData *SD,
496 const MCAsmLayout &Layout) const {
497 // Ignore virtual sections.
498 if (SD->getSection().isVirtualSection()) {
499 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
501 // Check that contents are only things legal inside a virtual section.
502 for (MCSectionData::const_iterator it = SD->begin(),
503 ie = SD->end(); it != ie; ++it) {
504 switch (it->getKind()) {
505 default: llvm_unreachable("Invalid fragment in virtual section!");
506 case MCFragment::FT_Data: {
507 // Check that we aren't trying to write a non-zero contents (or fixups)
508 // into a virtual section. This is to support clients which use standard
509 // directives to fill the contents of virtual sections.
510 MCDataFragment &DF = cast<MCDataFragment>(*it);
511 assert(DF.fixup_begin() == DF.fixup_end() &&
512 "Cannot have fixups in virtual section!");
513 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
514 assert(DF.getContents()[i] == 0 &&
515 "Invalid data value for virtual section!");
518 case MCFragment::FT_Align:
519 // Check that we aren't trying to write a non-zero value into a virtual
521 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
522 !cast<MCAlignFragment>(it)->getValue()) &&
523 "Invalid align in virtual section!");
525 case MCFragment::FT_Fill:
526 assert(!cast<MCFillFragment>(it)->getValueSize() &&
527 "Invalid fill in virtual section!");
535 uint64_t Start = getWriter().getStream().tell();
538 for (MCSectionData::const_iterator it = SD->begin(),
539 ie = SD->end(); it != ie; ++it)
540 WriteFragmentData(*this, Layout, *it);
542 assert(getWriter().getStream().tell() - Start ==
543 Layout.getSectionAddressSize(SD));
547 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
549 const MCFixup &Fixup) {
550 // Evaluate the fixup.
553 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
554 // The fixup was unresolved, we need a relocation. Inform the object
555 // writer of the relocation, and give it an opportunity to adjust the
556 // fixup value if need be.
557 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
562 void MCAssembler::Finish() {
563 DEBUG_WITH_TYPE("mc-dump", {
564 llvm::errs() << "assembler backend - pre-layout\n--\n";
567 // Create the layout object.
568 MCAsmLayout Layout(*this);
570 // Create dummy fragments and assign section ordinals.
571 unsigned SectionIndex = 0;
572 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
573 // Create dummy fragments to eliminate any empty sections, this simplifies
575 if (it->getFragmentList().empty())
576 new MCDataFragment(it);
578 it->setOrdinal(SectionIndex++);
581 // Assign layout order indices to sections and fragments.
582 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
583 MCSectionData *SD = Layout.getSectionOrder()[i];
584 SD->setLayoutOrder(i);
586 unsigned FragmentIndex = 0;
587 for (MCSectionData::iterator it2 = SD->begin(),
588 ie2 = SD->end(); it2 != ie2; ++it2)
589 it2->setLayoutOrder(FragmentIndex++);
592 // Layout until everything fits.
593 while (layoutOnce(Layout))
596 DEBUG_WITH_TYPE("mc-dump", {
597 llvm::errs() << "assembler backend - post-relaxation\n--\n";
600 // Finalize the layout, including fragment lowering.
601 finishLayout(Layout);
603 DEBUG_WITH_TYPE("mc-dump", {
604 llvm::errs() << "assembler backend - final-layout\n--\n";
607 uint64_t StartOffset = OS.tell();
609 // Allow the object writer a chance to perform post-layout binding (for
610 // example, to set the index fields in the symbol data).
611 getWriter().ExecutePostLayoutBinding(*this, Layout);
613 // Evaluate and apply the fixups, generating relocation entries as necessary.
614 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
615 for (MCSectionData::iterator it2 = it->begin(),
616 ie2 = it->end(); it2 != ie2; ++it2) {
617 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
619 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
620 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
621 MCFixup &Fixup = *it3;
622 uint64_t FixedValue = handleFixup(Layout, *DF, Fixup);
623 getBackend().applyFixup(Fixup, DF->getContents().data(),
624 DF->getContents().size(), FixedValue);
627 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
629 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
630 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
631 MCFixup &Fixup = *it3;
632 uint64_t FixedValue = handleFixup(Layout, *IF, Fixup);
633 getBackend().applyFixup(Fixup, IF->getCode().data(),
634 IF->getCode().size(), FixedValue);
640 // Write the object file.
641 getWriter().WriteObject(*this, Layout);
643 stats::ObjectBytes += OS.tell() - StartOffset;
646 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
647 const MCInstFragment *DF,
648 const MCAsmLayout &Layout) const {
652 // If we cannot resolve the fixup value, it requires relaxation.
655 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
658 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
661 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
662 const MCAsmLayout &Layout) const {
663 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
664 // are intentionally pushing out inst fragments, or because we relaxed a
665 // previous instruction to one that doesn't need relaxation.
666 if (!getBackend().mayNeedRelaxation(IF->getInst()))
669 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
670 ie = IF->fixup_end(); it != ie; ++it)
671 if (fixupNeedsRelaxation(*it, IF, Layout))
677 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
678 MCInstFragment &IF) {
679 if (!fragmentNeedsRelaxation(&IF, Layout))
682 ++stats::RelaxedInstructions;
684 // FIXME-PERF: We could immediately lower out instructions if we can tell
685 // they are fully resolved, to avoid retesting on later passes.
687 // Relax the fragment.
690 getBackend().relaxInstruction(IF.getInst(), Relaxed);
692 // Encode the new instruction.
694 // FIXME-PERF: If it matters, we could let the target do this. It can
695 // probably do so more efficiently in many cases.
696 SmallVector<MCFixup, 4> Fixups;
697 SmallString<256> Code;
698 raw_svector_ostream VecOS(Code);
699 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
702 // Update the instruction fragment.
705 IF.getFixups().clear();
706 // FIXME: Eliminate copy.
707 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
708 IF.getFixups().push_back(Fixups[i]);
713 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
715 uint64_t OldSize = LF.getContents().size();
716 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
719 SmallString<8> &Data = LF.getContents();
721 raw_svector_ostream OSE(Data);
723 encodeSLEB128(Value, OSE);
725 encodeULEB128(Value, OSE);
727 return OldSize != LF.getContents().size();
730 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
731 MCDwarfLineAddrFragment &DF) {
732 int64_t AddrDelta = 0;
733 uint64_t OldSize = DF.getContents().size();
734 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
738 LineDelta = DF.getLineDelta();
739 SmallString<8> &Data = DF.getContents();
741 raw_svector_ostream OSE(Data);
742 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
744 return OldSize != Data.size();
747 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
748 MCDwarfCallFrameFragment &DF) {
749 int64_t AddrDelta = 0;
750 uint64_t OldSize = DF.getContents().size();
751 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
754 SmallString<8> &Data = DF.getContents();
756 raw_svector_ostream OSE(Data);
757 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
759 return OldSize != Data.size();
762 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
764 MCFragment *FirstInvalidFragment = NULL;
765 // Scan for fragments that need relaxation.
766 for (MCSectionData::iterator it2 = SD.begin(),
767 ie2 = SD.end(); it2 != ie2; ++it2) {
768 // Check if this is an fragment that needs relaxation.
769 bool relaxedFrag = false;
770 switch(it2->getKind()) {
773 case MCFragment::FT_Inst:
774 relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
776 case MCFragment::FT_Dwarf:
777 relaxedFrag = relaxDwarfLineAddr(Layout,
778 *cast<MCDwarfLineAddrFragment>(it2));
780 case MCFragment::FT_DwarfFrame:
782 relaxDwarfCallFrameFragment(Layout,
783 *cast<MCDwarfCallFrameFragment>(it2));
785 case MCFragment::FT_LEB:
786 relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
789 // Update the layout, and remember that we relaxed.
790 if (relaxedFrag && !FirstInvalidFragment)
791 FirstInvalidFragment = it2;
793 if (FirstInvalidFragment) {
794 Layout.Invalidate(FirstInvalidFragment);
800 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
801 ++stats::RelaxationSteps;
803 bool WasRelaxed = false;
804 for (iterator it = begin(), ie = end(); it != ie; ++it) {
805 MCSectionData &SD = *it;
806 while(layoutSectionOnce(Layout, SD))
813 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
814 // The layout is done. Mark every fragment as valid.
815 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
816 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
824 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
825 OS << "<MCFixup" << " Offset:" << AF.getOffset()
826 << " Value:" << *AF.getValue()
827 << " Kind:" << AF.getKind() << ">";
833 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
834 void MCFragment::dump() {
835 raw_ostream &OS = llvm::errs();
839 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
840 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
841 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
842 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
843 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
844 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
845 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
846 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
849 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
850 << " Offset:" << Offset << ">";
853 case MCFragment::FT_Align: {
854 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
855 if (AF->hasEmitNops())
856 OS << " (emit nops)";
858 OS << " Alignment:" << AF->getAlignment()
859 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
860 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
863 case MCFragment::FT_Data: {
864 const MCDataFragment *DF = cast<MCDataFragment>(this);
867 const SmallVectorImpl<char> &Contents = DF->getContents();
868 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
870 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
872 OS << "] (" << Contents.size() << " bytes)";
874 if (!DF->getFixups().empty()) {
877 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
878 ie = DF->fixup_end(); it != ie; ++it) {
879 if (it != DF->fixup_begin()) OS << ",\n ";
886 case MCFragment::FT_Fill: {
887 const MCFillFragment *FF = cast<MCFillFragment>(this);
888 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
889 << " Size:" << FF->getSize();
892 case MCFragment::FT_Inst: {
893 const MCInstFragment *IF = cast<MCInstFragment>(this);
896 IF->getInst().dump_pretty(OS);
899 case MCFragment::FT_Org: {
900 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
902 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
905 case MCFragment::FT_Dwarf: {
906 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
908 OS << " AddrDelta:" << OF->getAddrDelta()
909 << " LineDelta:" << OF->getLineDelta();
912 case MCFragment::FT_DwarfFrame: {
913 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
915 OS << " AddrDelta:" << CF->getAddrDelta();
918 case MCFragment::FT_LEB: {
919 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
921 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
928 void MCSectionData::dump() {
929 raw_ostream &OS = llvm::errs();
931 OS << "<MCSectionData";
932 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
933 for (iterator it = begin(), ie = end(); it != ie; ++it) {
934 if (it != begin()) OS << ",\n ";
940 void MCSymbolData::dump() {
941 raw_ostream &OS = llvm::errs();
943 OS << "<MCSymbolData Symbol:" << getSymbol()
944 << " Fragment:" << getFragment() << " Offset:" << getOffset()
945 << " Flags:" << getFlags() << " Index:" << getIndex();
947 OS << " (common, size:" << getCommonSize()
948 << " align: " << getCommonAlignment() << ")";
951 if (isPrivateExtern())
952 OS << " (private extern)";
956 void MCAssembler::dump() {
957 raw_ostream &OS = llvm::errs();
959 OS << "<MCAssembler\n";
960 OS << " Sections:[\n ";
961 for (iterator it = begin(), ie = end(); it != ie; ++it) {
962 if (it != begin()) OS << ",\n ";
968 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
969 if (it != symbol_begin()) OS << ",\n ";
976 // anchors for MC*Fragment vtables
977 void MCDataFragment::anchor() { }
978 void MCInstFragment::anchor() { }
979 void MCAlignFragment::anchor() { }
980 void MCFillFragment::anchor() { }
981 void MCOrgFragment::anchor() { }
982 void MCLEBFragment::anchor() { }
983 void MCDwarfLineAddrFragment::anchor() { }
984 void MCDwarfCallFrameFragment::anchor() { }