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 (Size > AF.getMaxBytesToEmit())
333 case MCFragment::FT_Org: {
334 MCOrgFragment &OF = cast<MCOrgFragment>(F);
335 int64_t TargetLocation;
336 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
337 report_fatal_error("expected assembly-time absolute expression");
339 // FIXME: We need a way to communicate this error.
340 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
341 int64_t Size = TargetLocation - FragmentOffset;
342 if (Size < 0 || Size >= 0x40000000)
343 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
344 "' (at offset '" + Twine(FragmentOffset) + "')");
348 case MCFragment::FT_Dwarf:
349 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
350 case MCFragment::FT_DwarfFrame:
351 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
354 llvm_unreachable("invalid fragment kind");
357 void MCAsmLayout::LayoutFragment(MCFragment *F) {
358 MCFragment *Prev = F->getPrevNode();
360 // We should never try to recompute something which is up-to-date.
361 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
362 // We should never try to compute the fragment layout if it's predecessor
364 assert((!Prev || isFragmentUpToDate(Prev)) &&
365 "Attempt to compute fragment before it's predecessor!");
367 ++stats::FragmentLayouts;
369 // Compute fragment offset and size.
372 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
375 LastValidFragment[F->getParent()] = F;
378 /// WriteFragmentData - Write the \arg F data to the output file.
379 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
380 const MCFragment &F) {
381 MCObjectWriter *OW = &Asm.getWriter();
382 uint64_t Start = OW->getStream().tell();
385 ++stats::EmittedFragments;
387 // FIXME: Embed in fragments instead?
388 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
389 switch (F.getKind()) {
390 case MCFragment::FT_Align: {
391 MCAlignFragment &AF = cast<MCAlignFragment>(F);
392 uint64_t Count = FragmentSize / AF.getValueSize();
394 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
396 // FIXME: This error shouldn't actually occur (the front end should emit
397 // multiple .align directives to enforce the semantics it wants), but is
398 // severe enough that we want to report it. How to handle this?
399 if (Count * AF.getValueSize() != FragmentSize)
400 report_fatal_error("undefined .align directive, value size '" +
401 Twine(AF.getValueSize()) +
402 "' is not a divisor of padding size '" +
403 Twine(FragmentSize) + "'");
405 // See if we are aligning with nops, and if so do that first to try to fill
406 // the Count bytes. Then if that did not fill any bytes or there are any
407 // bytes left to fill use the Value and ValueSize to fill the rest.
408 // If we are aligning with nops, ask that target to emit the right data.
409 if (AF.hasEmitNops()) {
410 if (!Asm.getBackend().writeNopData(Count, OW))
411 report_fatal_error("unable to write nop sequence of " +
412 Twine(Count) + " bytes");
416 // Otherwise, write out in multiples of the value size.
417 for (uint64_t i = 0; i != Count; ++i) {
418 switch (AF.getValueSize()) {
419 default: llvm_unreachable("Invalid size!");
420 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
421 case 2: OW->Write16(uint16_t(AF.getValue())); break;
422 case 4: OW->Write32(uint32_t(AF.getValue())); break;
423 case 8: OW->Write64(uint64_t(AF.getValue())); break;
429 case MCFragment::FT_Data: {
430 MCDataFragment &DF = cast<MCDataFragment>(F);
431 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
432 OW->WriteBytes(DF.getContents().str());
436 case MCFragment::FT_Fill: {
437 MCFillFragment &FF = cast<MCFillFragment>(F);
439 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
441 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
442 switch (FF.getValueSize()) {
443 default: llvm_unreachable("Invalid size!");
444 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
445 case 2: OW->Write16(uint16_t(FF.getValue())); break;
446 case 4: OW->Write32(uint32_t(FF.getValue())); break;
447 case 8: OW->Write64(uint64_t(FF.getValue())); break;
453 case MCFragment::FT_Inst: {
454 MCInstFragment &IF = cast<MCInstFragment>(F);
455 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
459 case MCFragment::FT_LEB: {
460 MCLEBFragment &LF = cast<MCLEBFragment>(F);
461 OW->WriteBytes(LF.getContents().str());
465 case MCFragment::FT_Org: {
466 MCOrgFragment &OF = cast<MCOrgFragment>(F);
468 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
469 OW->Write8(uint8_t(OF.getValue()));
474 case MCFragment::FT_Dwarf: {
475 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
476 OW->WriteBytes(OF.getContents().str());
479 case MCFragment::FT_DwarfFrame: {
480 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
481 OW->WriteBytes(CF.getContents().str());
486 assert(OW->getStream().tell() - Start == FragmentSize);
489 void MCAssembler::writeSectionData(const MCSectionData *SD,
490 const MCAsmLayout &Layout) const {
491 // Ignore virtual sections.
492 if (SD->getSection().isVirtualSection()) {
493 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
495 // Check that contents are only things legal inside a virtual section.
496 for (MCSectionData::const_iterator it = SD->begin(),
497 ie = SD->end(); it != ie; ++it) {
498 switch (it->getKind()) {
499 default: llvm_unreachable("Invalid fragment in virtual section!");
500 case MCFragment::FT_Data: {
501 // Check that we aren't trying to write a non-zero contents (or fixups)
502 // into a virtual section. This is to support clients which use standard
503 // directives to fill the contents of virtual sections.
504 MCDataFragment &DF = cast<MCDataFragment>(*it);
505 assert(DF.fixup_begin() == DF.fixup_end() &&
506 "Cannot have fixups in virtual section!");
507 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
508 assert(DF.getContents()[i] == 0 &&
509 "Invalid data value for virtual section!");
512 case MCFragment::FT_Align:
513 // Check that we aren't trying to write a non-zero value into a virtual
515 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
516 !cast<MCAlignFragment>(it)->getValue()) &&
517 "Invalid align in virtual section!");
519 case MCFragment::FT_Fill:
520 assert(!cast<MCFillFragment>(it)->getValueSize() &&
521 "Invalid fill in virtual section!");
529 uint64_t Start = getWriter().getStream().tell();
532 for (MCSectionData::const_iterator it = SD->begin(),
533 ie = SD->end(); it != ie; ++it)
534 WriteFragmentData(*this, Layout, *it);
536 assert(getWriter().getStream().tell() - Start ==
537 Layout.getSectionAddressSize(SD));
541 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
543 const MCFixup &Fixup) {
544 // Evaluate the fixup.
547 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
548 // The fixup was unresolved, we need a relocation. Inform the object
549 // writer of the relocation, and give it an opportunity to adjust the
550 // fixup value if need be.
551 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
556 void MCAssembler::Finish() {
557 DEBUG_WITH_TYPE("mc-dump", {
558 llvm::errs() << "assembler backend - pre-layout\n--\n";
561 // Create the layout object.
562 MCAsmLayout Layout(*this);
564 // Create dummy fragments and assign section ordinals.
565 unsigned SectionIndex = 0;
566 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
567 // Create dummy fragments to eliminate any empty sections, this simplifies
569 if (it->getFragmentList().empty())
570 new MCDataFragment(it);
572 it->setOrdinal(SectionIndex++);
575 // Assign layout order indices to sections and fragments.
576 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
577 MCSectionData *SD = Layout.getSectionOrder()[i];
578 SD->setLayoutOrder(i);
580 unsigned FragmentIndex = 0;
581 for (MCSectionData::iterator it2 = SD->begin(),
582 ie2 = SD->end(); it2 != ie2; ++it2)
583 it2->setLayoutOrder(FragmentIndex++);
586 // Layout until everything fits.
587 while (layoutOnce(Layout))
590 DEBUG_WITH_TYPE("mc-dump", {
591 llvm::errs() << "assembler backend - post-relaxation\n--\n";
594 // Finalize the layout, including fragment lowering.
595 finishLayout(Layout);
597 DEBUG_WITH_TYPE("mc-dump", {
598 llvm::errs() << "assembler backend - final-layout\n--\n";
601 uint64_t StartOffset = OS.tell();
603 // Allow the object writer a chance to perform post-layout binding (for
604 // example, to set the index fields in the symbol data).
605 getWriter().ExecutePostLayoutBinding(*this, Layout);
607 // Evaluate and apply the fixups, generating relocation entries as necessary.
608 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
609 for (MCSectionData::iterator it2 = it->begin(),
610 ie2 = it->end(); it2 != ie2; ++it2) {
611 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
613 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
614 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
615 MCFixup &Fixup = *it3;
616 uint64_t FixedValue = handleFixup(Layout, *DF, Fixup);
617 getBackend().applyFixup(Fixup, DF->getContents().data(),
618 DF->getContents().size(), FixedValue);
621 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
623 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
624 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
625 MCFixup &Fixup = *it3;
626 uint64_t FixedValue = handleFixup(Layout, *IF, Fixup);
627 getBackend().applyFixup(Fixup, IF->getCode().data(),
628 IF->getCode().size(), FixedValue);
634 // Write the object file.
635 getWriter().WriteObject(*this, Layout);
637 stats::ObjectBytes += OS.tell() - StartOffset;
640 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
641 const MCInstFragment *DF,
642 const MCAsmLayout &Layout) const {
646 // If we cannot resolve the fixup value, it requires relaxation.
649 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
652 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
655 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
656 const MCAsmLayout &Layout) const {
657 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
658 // are intentionally pushing out inst fragments, or because we relaxed a
659 // previous instruction to one that doesn't need relaxation.
660 if (!getBackend().mayNeedRelaxation(IF->getInst()))
663 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
664 ie = IF->fixup_end(); it != ie; ++it)
665 if (fixupNeedsRelaxation(*it, IF, Layout))
671 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
672 MCInstFragment &IF) {
673 if (!fragmentNeedsRelaxation(&IF, Layout))
676 ++stats::RelaxedInstructions;
678 // FIXME-PERF: We could immediately lower out instructions if we can tell
679 // they are fully resolved, to avoid retesting on later passes.
681 // Relax the fragment.
684 getBackend().relaxInstruction(IF.getInst(), Relaxed);
686 // Encode the new instruction.
688 // FIXME-PERF: If it matters, we could let the target do this. It can
689 // probably do so more efficiently in many cases.
690 SmallVector<MCFixup, 4> Fixups;
691 SmallString<256> Code;
692 raw_svector_ostream VecOS(Code);
693 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
696 // Update the instruction fragment.
699 IF.getFixups().clear();
700 // FIXME: Eliminate copy.
701 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
702 IF.getFixups().push_back(Fixups[i]);
707 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
709 uint64_t OldSize = LF.getContents().size();
710 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
713 SmallString<8> &Data = LF.getContents();
715 raw_svector_ostream OSE(Data);
717 encodeSLEB128(Value, OSE);
719 encodeULEB128(Value, OSE);
721 return OldSize != LF.getContents().size();
724 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
725 MCDwarfLineAddrFragment &DF) {
726 int64_t AddrDelta = 0;
727 uint64_t OldSize = DF.getContents().size();
728 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
732 LineDelta = DF.getLineDelta();
733 SmallString<8> &Data = DF.getContents();
735 raw_svector_ostream OSE(Data);
736 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
738 return OldSize != Data.size();
741 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
742 MCDwarfCallFrameFragment &DF) {
743 int64_t AddrDelta = 0;
744 uint64_t OldSize = DF.getContents().size();
745 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
748 SmallString<8> &Data = DF.getContents();
750 raw_svector_ostream OSE(Data);
751 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
753 return OldSize != Data.size();
756 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
758 MCFragment *FirstInvalidFragment = NULL;
759 // Scan for fragments that need relaxation.
760 for (MCSectionData::iterator it2 = SD.begin(),
761 ie2 = SD.end(); it2 != ie2; ++it2) {
762 // Check if this is an fragment that needs relaxation.
763 bool relaxedFrag = false;
764 switch(it2->getKind()) {
767 case MCFragment::FT_Inst:
768 relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
770 case MCFragment::FT_Dwarf:
771 relaxedFrag = relaxDwarfLineAddr(Layout,
772 *cast<MCDwarfLineAddrFragment>(it2));
774 case MCFragment::FT_DwarfFrame:
776 relaxDwarfCallFrameFragment(Layout,
777 *cast<MCDwarfCallFrameFragment>(it2));
779 case MCFragment::FT_LEB:
780 relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
783 // Update the layout, and remember that we relaxed.
784 if (relaxedFrag && !FirstInvalidFragment)
785 FirstInvalidFragment = it2;
787 if (FirstInvalidFragment) {
788 Layout.Invalidate(FirstInvalidFragment);
794 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
795 ++stats::RelaxationSteps;
797 bool WasRelaxed = false;
798 for (iterator it = begin(), ie = end(); it != ie; ++it) {
799 MCSectionData &SD = *it;
800 while(layoutSectionOnce(Layout, SD))
807 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
808 // The layout is done. Mark every fragment as valid.
809 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
810 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
818 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
819 OS << "<MCFixup" << " Offset:" << AF.getOffset()
820 << " Value:" << *AF.getValue()
821 << " Kind:" << AF.getKind() << ">";
827 void MCFragment::dump() {
828 raw_ostream &OS = llvm::errs();
832 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
833 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
834 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
835 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
836 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
837 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
838 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
839 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
842 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
843 << " Offset:" << Offset << ">";
846 case MCFragment::FT_Align: {
847 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
848 if (AF->hasEmitNops())
849 OS << " (emit nops)";
851 OS << " Alignment:" << AF->getAlignment()
852 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
853 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
856 case MCFragment::FT_Data: {
857 const MCDataFragment *DF = cast<MCDataFragment>(this);
860 const SmallVectorImpl<char> &Contents = DF->getContents();
861 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
863 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
865 OS << "] (" << Contents.size() << " bytes)";
867 if (!DF->getFixups().empty()) {
870 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
871 ie = DF->fixup_end(); it != ie; ++it) {
872 if (it != DF->fixup_begin()) OS << ",\n ";
879 case MCFragment::FT_Fill: {
880 const MCFillFragment *FF = cast<MCFillFragment>(this);
881 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
882 << " Size:" << FF->getSize();
885 case MCFragment::FT_Inst: {
886 const MCInstFragment *IF = cast<MCInstFragment>(this);
889 IF->getInst().dump_pretty(OS);
892 case MCFragment::FT_Org: {
893 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
895 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
898 case MCFragment::FT_Dwarf: {
899 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
901 OS << " AddrDelta:" << OF->getAddrDelta()
902 << " LineDelta:" << OF->getLineDelta();
905 case MCFragment::FT_DwarfFrame: {
906 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
908 OS << " AddrDelta:" << CF->getAddrDelta();
911 case MCFragment::FT_LEB: {
912 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
914 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
921 void MCSectionData::dump() {
922 raw_ostream &OS = llvm::errs();
924 OS << "<MCSectionData";
925 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
926 for (iterator it = begin(), ie = end(); it != ie; ++it) {
927 if (it != begin()) OS << ",\n ";
933 void MCSymbolData::dump() {
934 raw_ostream &OS = llvm::errs();
936 OS << "<MCSymbolData Symbol:" << getSymbol()
937 << " Fragment:" << getFragment() << " Offset:" << getOffset()
938 << " Flags:" << getFlags() << " Index:" << getIndex();
940 OS << " (common, size:" << getCommonSize()
941 << " align: " << getCommonAlignment() << ")";
944 if (isPrivateExtern())
945 OS << " (private extern)";
949 void MCAssembler::dump() {
950 raw_ostream &OS = llvm::errs();
952 OS << "<MCAssembler\n";
953 OS << " Sections:[\n ";
954 for (iterator it = begin(), ie = end(); it != ie; ++it) {
955 if (it != begin()) OS << ",\n ";
961 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
962 if (it != symbol_begin()) OS << ",\n ";
968 // anchors for MC*Fragment vtables
969 void MCDataFragment::anchor() { }
970 void MCInstFragment::anchor() { }
971 void MCAlignFragment::anchor() { }
972 void MCFillFragment::anchor() { }
973 void MCOrgFragment::anchor() { }
974 void MCLEBFragment::anchor() { }
975 void MCDwarfLineAddrFragment::anchor() { }
976 void MCDwarfCallFrameFragment::anchor() { }