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 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
35 #define DEBUG_TYPE "assembler"
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41 "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43 "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45 "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47 "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49 "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51 "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
67 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
68 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
69 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
70 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
71 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
72 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
75 MCAssembler::~MCAssembler() {
78 void MCAssembler::reset() {
81 IndirectSymbols.clear();
83 LinkerOptions.clear();
88 SubsectionsViaSymbols = false;
89 IncrementalLinkerCompatible = false;
92 VersionMinInfo.Major = 0;
94 // reset objects owned by us
98 getLOHContainer().reset();
101 bool MCAssembler::registerSection(MCSection &Section) {
102 if (Section.isRegistered())
104 Sections.push_back(&Section);
105 Section.setIsRegistered(true);
109 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
110 if (ThumbFuncs.count(Symbol))
113 if (!Symbol->isVariable())
116 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
117 // is not clear if that is a bug or a feature.
118 const MCExpr *Expr = Symbol->getVariableValue();
119 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
123 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
126 const MCSymbol &Sym = Ref->getSymbol();
127 if (!isThumbFunc(&Sym))
130 ThumbFuncs.insert(Symbol); // Cache it.
134 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
135 // Non-temporary labels should always be visible to the linker.
136 if (!Symbol.isTemporary())
139 // Absolute temporary labels are never visible.
140 if (!Symbol.isInSection())
143 if (Symbol.isUsedInReloc())
149 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
150 // Linker visible symbols define atoms.
151 if (isSymbolLinkerVisible(S))
154 // Absolute and undefined symbols have no defining atom.
155 if (!S.isInSection())
158 // Non-linker visible symbols in sections which can't be atomized have no
160 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
161 *S.getFragment()->getParent()))
164 // Otherwise, return the atom for the containing fragment.
165 return S.getFragment()->getAtom();
168 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
169 const MCFixup &Fixup, const MCFragment *DF,
170 MCValue &Target, uint64_t &Value) const {
171 ++stats::evaluateFixup;
173 // FIXME: This code has some duplication with recordRelocation. We should
174 // probably merge the two into a single callback that tries to evaluate a
175 // fixup and records a relocation if one is needed.
176 const MCExpr *Expr = Fixup.getValue();
177 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
178 getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
179 // Claim to have completely evaluated the fixup, to prevent any further
180 // processing from being done.
185 bool IsPCRel = Backend.getFixupKindInfo(
186 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
190 if (Target.getSymB()) {
192 } else if (!Target.getSymA()) {
195 const MCSymbolRefExpr *A = Target.getSymA();
196 const MCSymbol &SA = A->getSymbol();
197 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
200 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
201 *this, SA, *DF, false, true);
205 IsResolved = Target.isAbsolute();
208 Value = Target.getConstant();
210 if (const MCSymbolRefExpr *A = Target.getSymA()) {
211 const MCSymbol &Sym = A->getSymbol();
213 Value += Layout.getSymbolOffset(Sym);
215 if (const MCSymbolRefExpr *B = Target.getSymB()) {
216 const MCSymbol &Sym = B->getSymbol();
218 Value -= Layout.getSymbolOffset(Sym);
222 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
223 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
224 assert((ShouldAlignPC ? IsPCRel : true) &&
225 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
228 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
230 // A number of ARM fixups in Thumb mode require that the effective PC
231 // address be determined as the 32-bit aligned version of the actual offset.
232 if (ShouldAlignPC) Offset &= ~0x3;
236 // Let the backend adjust the fixup value if necessary, including whether
237 // we need a relocation.
238 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
244 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
245 const MCFragment &F) const {
246 switch (F.getKind()) {
247 case MCFragment::FT_Data:
248 return cast<MCDataFragment>(F).getContents().size();
249 case MCFragment::FT_Relaxable:
250 return cast<MCRelaxableFragment>(F).getContents().size();
251 case MCFragment::FT_CompactEncodedInst:
252 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
253 case MCFragment::FT_Fill:
254 return cast<MCFillFragment>(F).getSize();
256 case MCFragment::FT_LEB:
257 return cast<MCLEBFragment>(F).getContents().size();
259 case MCFragment::FT_SafeSEH:
262 case MCFragment::FT_Align: {
263 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
264 unsigned Offset = Layout.getFragmentOffset(&AF);
265 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
266 // If we are padding with nops, force the padding to be larger than the
268 if (Size > 0 && AF.hasEmitNops()) {
269 while (Size % getBackend().getMinimumNopSize())
270 Size += AF.getAlignment();
272 if (Size > AF.getMaxBytesToEmit())
277 case MCFragment::FT_Org: {
278 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
280 if (!OF.getOffset().evaluateAsValue(Value, Layout))
281 report_fatal_error("expected assembly-time absolute expression");
283 // FIXME: We need a way to communicate this error.
284 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
285 int64_t TargetLocation = Value.getConstant();
286 if (const MCSymbolRefExpr *A = Value.getSymA()) {
288 if (!Layout.getSymbolOffset(A->getSymbol(), Val))
289 report_fatal_error("expected absolute expression");
290 TargetLocation += Val;
292 int64_t Size = TargetLocation - FragmentOffset;
293 if (Size < 0 || Size >= 0x40000000)
294 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
295 "' (at offset '" + Twine(FragmentOffset) + "')");
299 case MCFragment::FT_Dwarf:
300 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
301 case MCFragment::FT_DwarfFrame:
302 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
303 case MCFragment::FT_Dummy:
304 llvm_unreachable("Should not have been added");
307 llvm_unreachable("invalid fragment kind");
310 void MCAsmLayout::layoutFragment(MCFragment *F) {
311 MCFragment *Prev = F->getPrevNode();
313 // We should never try to recompute something which is valid.
314 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
315 // We should never try to compute the fragment layout if its predecessor
317 assert((!Prev || isFragmentValid(Prev)) &&
318 "Attempt to compute fragment before its predecessor!");
320 ++stats::FragmentLayouts;
322 // Compute fragment offset and size.
324 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
327 LastValidFragment[F->getParent()] = F;
329 // If bundling is enabled and this fragment has instructions in it, it has to
330 // obey the bundling restrictions. With padding, we'll have:
335 // -------------------------------------
336 // Prev |##########| F |
337 // -------------------------------------
342 // The fragment's offset will point to after the padding, and its computed
343 // size won't include the padding.
345 // When the -mc-relax-all flag is used, we optimize bundling by writting the
346 // padding directly into fragments when the instructions are emitted inside
347 // the streamer. When the fragment is larger than the bundle size, we need to
348 // ensure that it's bundle aligned. This means that if we end up with
349 // multiple fragments, we must emit bundle padding between fragments.
351 // ".align N" is an example of a directive that introduces multiple
352 // fragments. We could add a special case to handle ".align N" by emitting
353 // within-fragment padding (which would produce less padding when N is less
354 // than the bundle size), but for now we don't.
356 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
357 assert(isa<MCEncodedFragment>(F) &&
358 "Only MCEncodedFragment implementations have instructions");
359 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
361 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
362 report_fatal_error("Fragment can't be larger than a bundle size");
364 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
366 if (RequiredBundlePadding > UINT8_MAX)
367 report_fatal_error("Padding cannot exceed 255 bytes");
368 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
369 F->Offset += RequiredBundlePadding;
373 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
374 bool New = !Symbol.isRegistered();
378 Symbol.setIsRegistered(true);
379 Symbols.push_back(&Symbol);
383 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
384 MCObjectWriter *OW) const {
385 // Should NOP padding be written out before this fragment?
386 unsigned BundlePadding = F.getBundlePadding();
387 if (BundlePadding > 0) {
388 assert(isBundlingEnabled() &&
389 "Writing bundle padding with disabled bundling");
390 assert(F.hasInstructions() &&
391 "Writing bundle padding for a fragment without instructions");
393 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
394 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
395 // If the padding itself crosses a bundle boundary, it must be emitted
396 // in 2 pieces, since even nop instructions must not cross boundaries.
397 // v--------------v <- BundleAlignSize
398 // v---------v <- BundlePadding
399 // ----------------------------
400 // | Prev |####|####| F |
401 // ----------------------------
402 // ^-------------------^ <- TotalLength
403 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
404 if (!getBackend().writeNopData(DistanceToBoundary, OW))
405 report_fatal_error("unable to write NOP sequence of " +
406 Twine(DistanceToBoundary) + " bytes");
407 BundlePadding -= DistanceToBoundary;
409 if (!getBackend().writeNopData(BundlePadding, OW))
410 report_fatal_error("unable to write NOP sequence of " +
411 Twine(BundlePadding) + " bytes");
415 /// \brief Write the fragment \p F to the output file.
416 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
417 const MCFragment &F) {
418 MCObjectWriter *OW = &Asm.getWriter();
420 // FIXME: Embed in fragments instead?
421 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
423 Asm.writeFragmentPadding(F, FragmentSize, OW);
425 // This variable (and its dummy usage) is to participate in the assert at
426 // the end of the function.
427 uint64_t Start = OW->getStream().tell();
430 ++stats::EmittedFragments;
432 switch (F.getKind()) {
433 case MCFragment::FT_Align: {
434 ++stats::EmittedAlignFragments;
435 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
436 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
438 uint64_t Count = FragmentSize / AF.getValueSize();
440 // FIXME: This error shouldn't actually occur (the front end should emit
441 // multiple .align directives to enforce the semantics it wants), but is
442 // severe enough that we want to report it. How to handle this?
443 if (Count * AF.getValueSize() != FragmentSize)
444 report_fatal_error("undefined .align directive, value size '" +
445 Twine(AF.getValueSize()) +
446 "' is not a divisor of padding size '" +
447 Twine(FragmentSize) + "'");
449 // See if we are aligning with nops, and if so do that first to try to fill
450 // the Count bytes. Then if that did not fill any bytes or there are any
451 // bytes left to fill use the Value and ValueSize to fill the rest.
452 // If we are aligning with nops, ask that target to emit the right data.
453 if (AF.hasEmitNops()) {
454 if (!Asm.getBackend().writeNopData(Count, OW))
455 report_fatal_error("unable to write nop sequence of " +
456 Twine(Count) + " bytes");
460 // Otherwise, write out in multiples of the value size.
461 for (uint64_t i = 0; i != Count; ++i) {
462 switch (AF.getValueSize()) {
463 default: llvm_unreachable("Invalid size!");
464 case 1: OW->write8 (uint8_t (AF.getValue())); break;
465 case 2: OW->write16(uint16_t(AF.getValue())); break;
466 case 4: OW->write32(uint32_t(AF.getValue())); break;
467 case 8: OW->write64(uint64_t(AF.getValue())); break;
473 case MCFragment::FT_Data:
474 ++stats::EmittedDataFragments;
475 OW->writeBytes(cast<MCDataFragment>(F).getContents());
478 case MCFragment::FT_Relaxable:
479 ++stats::EmittedRelaxableFragments;
480 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
483 case MCFragment::FT_CompactEncodedInst:
484 ++stats::EmittedCompactEncodedInstFragments;
485 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
488 case MCFragment::FT_Fill: {
489 ++stats::EmittedFillFragments;
490 const MCFillFragment &FF = cast<MCFillFragment>(F);
492 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
494 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
495 switch (FF.getValueSize()) {
496 default: llvm_unreachable("Invalid size!");
497 case 1: OW->write8 (uint8_t (FF.getValue())); break;
498 case 2: OW->write16(uint16_t(FF.getValue())); break;
499 case 4: OW->write32(uint32_t(FF.getValue())); break;
500 case 8: OW->write64(uint64_t(FF.getValue())); break;
506 case MCFragment::FT_LEB: {
507 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
508 OW->writeBytes(LF.getContents());
512 case MCFragment::FT_SafeSEH: {
513 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
514 OW->write32(SF.getSymbol()->getIndex());
518 case MCFragment::FT_Org: {
519 ++stats::EmittedOrgFragments;
520 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
522 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
523 OW->write8(uint8_t(OF.getValue()));
528 case MCFragment::FT_Dwarf: {
529 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
530 OW->writeBytes(OF.getContents());
533 case MCFragment::FT_DwarfFrame: {
534 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
535 OW->writeBytes(CF.getContents());
538 case MCFragment::FT_Dummy:
539 llvm_unreachable("Should not have been added");
542 assert(OW->getStream().tell() - Start == FragmentSize &&
543 "The stream should advance by fragment size");
546 void MCAssembler::writeSectionData(const MCSection *Sec,
547 const MCAsmLayout &Layout) const {
548 // Ignore virtual sections.
549 if (Sec->isVirtualSection()) {
550 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
552 // Check that contents are only things legal inside a virtual section.
553 for (const MCFragment &F : *Sec) {
554 switch (F.getKind()) {
555 default: llvm_unreachable("Invalid fragment in virtual section!");
556 case MCFragment::FT_Data: {
557 // Check that we aren't trying to write a non-zero contents (or fixups)
558 // into a virtual section. This is to support clients which use standard
559 // directives to fill the contents of virtual sections.
560 const MCDataFragment &DF = cast<MCDataFragment>(F);
561 assert(DF.fixup_begin() == DF.fixup_end() &&
562 "Cannot have fixups in virtual section!");
563 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
564 if (DF.getContents()[i]) {
565 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
566 report_fatal_error("non-zero initializer found in section '" +
567 ELFSec->getSectionName() + "'");
569 report_fatal_error("non-zero initializer found in virtual section");
573 case MCFragment::FT_Align:
574 // Check that we aren't trying to write a non-zero value into a virtual
576 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
577 cast<MCAlignFragment>(F).getValue() == 0) &&
578 "Invalid align in virtual section!");
580 case MCFragment::FT_Fill:
581 assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
582 cast<MCFillFragment>(F).getValue() == 0) &&
583 "Invalid fill in virtual section!");
591 uint64_t Start = getWriter().getStream().tell();
594 for (const MCFragment &F : *Sec)
595 writeFragment(*this, Layout, F);
597 assert(getWriter().getStream().tell() - Start ==
598 Layout.getSectionAddressSize(Sec));
601 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
603 const MCFixup &Fixup) {
604 // Evaluate the fixup.
607 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
608 MCFixupKindInfo::FKF_IsPCRel;
609 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
610 // The fixup was unresolved, we need a relocation. Inform the object
611 // writer of the relocation, and give it an opportunity to adjust the
612 // fixup value if need be.
613 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
616 return std::make_pair(FixedValue, IsPCRel);
619 void MCAssembler::layout(MCAsmLayout &Layout) {
620 DEBUG_WITH_TYPE("mc-dump", {
621 llvm::errs() << "assembler backend - pre-layout\n--\n";
624 // Create dummy fragments and assign section ordinals.
625 unsigned SectionIndex = 0;
626 for (MCSection &Sec : *this) {
627 // Create dummy fragments to eliminate any empty sections, this simplifies
629 if (Sec.getFragmentList().empty())
630 new MCDataFragment(&Sec);
632 Sec.setOrdinal(SectionIndex++);
635 // Assign layout order indices to sections and fragments.
636 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
637 MCSection *Sec = Layout.getSectionOrder()[i];
638 Sec->setLayoutOrder(i);
640 unsigned FragmentIndex = 0;
641 for (MCFragment &Frag : *Sec)
642 Frag.setLayoutOrder(FragmentIndex++);
645 // Layout until everything fits.
646 while (layoutOnce(Layout))
649 DEBUG_WITH_TYPE("mc-dump", {
650 llvm::errs() << "assembler backend - post-relaxation\n--\n";
653 // Finalize the layout, including fragment lowering.
654 finishLayout(Layout);
656 DEBUG_WITH_TYPE("mc-dump", {
657 llvm::errs() << "assembler backend - final-layout\n--\n";
660 // Allow the object writer a chance to perform post-layout binding (for
661 // example, to set the index fields in the symbol data).
662 getWriter().executePostLayoutBinding(*this, Layout);
664 // Evaluate and apply the fixups, generating relocation entries as necessary.
665 for (MCSection &Sec : *this) {
666 for (MCFragment &Frag : Sec) {
667 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
668 // Data and relaxable fragments both have fixups. So only process
670 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
671 // being templated makes this tricky.
672 if (!F || isa<MCCompactEncodedInstFragment>(F))
674 ArrayRef<MCFixup> Fixups;
675 MutableArrayRef<char> Contents;
676 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
677 Fixups = FragWithFixups->getFixups();
678 Contents = FragWithFixups->getContents();
679 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
680 Fixups = FragWithFixups->getFixups();
681 Contents = FragWithFixups->getContents();
683 llvm_unreachable("Unknown fragment with fixups!");
684 for (const MCFixup &Fixup : Fixups) {
687 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
688 getBackend().applyFixup(Fixup, Contents.data(),
689 Contents.size(), FixedValue, IsPCRel);
695 void MCAssembler::Finish() {
696 // Create the layout object.
697 MCAsmLayout Layout(*this);
700 raw_ostream &OS = getWriter().getStream();
701 uint64_t StartOffset = OS.tell();
703 // Write the object file.
704 getWriter().writeObject(*this, Layout);
706 stats::ObjectBytes += OS.tell() - StartOffset;
709 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
710 const MCRelaxableFragment *DF,
711 const MCAsmLayout &Layout) const {
714 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
715 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
719 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
720 const MCAsmLayout &Layout) const {
721 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
722 // are intentionally pushing out inst fragments, or because we relaxed a
723 // previous instruction to one that doesn't need relaxation.
724 if (!getBackend().mayNeedRelaxation(F->getInst()))
727 for (const MCFixup &Fixup : F->getFixups())
728 if (fixupNeedsRelaxation(Fixup, F, Layout))
734 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
735 MCRelaxableFragment &F) {
736 if (!fragmentNeedsRelaxation(&F, Layout))
739 ++stats::RelaxedInstructions;
741 // FIXME-PERF: We could immediately lower out instructions if we can tell
742 // they are fully resolved, to avoid retesting on later passes.
744 // Relax the fragment.
747 getBackend().relaxInstruction(F.getInst(), Relaxed);
749 // Encode the new instruction.
751 // FIXME-PERF: If it matters, we could let the target do this. It can
752 // probably do so more efficiently in many cases.
753 SmallVector<MCFixup, 4> Fixups;
754 SmallString<256> Code;
755 raw_svector_ostream VecOS(Code);
756 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
758 // Update the fragment.
760 F.getContents() = Code;
761 F.getFixups() = Fixups;
766 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
767 uint64_t OldSize = LF.getContents().size();
769 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
771 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
772 SmallString<8> &Data = LF.getContents();
774 raw_svector_ostream OSE(Data);
776 encodeSLEB128(Value, OSE);
778 encodeULEB128(Value, OSE);
779 return OldSize != LF.getContents().size();
782 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
783 MCDwarfLineAddrFragment &DF) {
784 MCContext &Context = Layout.getAssembler().getContext();
785 uint64_t OldSize = DF.getContents().size();
787 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
788 assert(Abs && "We created a line delta with an invalid expression");
791 LineDelta = DF.getLineDelta();
792 SmallString<8> &Data = DF.getContents();
794 raw_svector_ostream OSE(Data);
795 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
797 return OldSize != Data.size();
800 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
801 MCDwarfCallFrameFragment &DF) {
802 MCContext &Context = Layout.getAssembler().getContext();
803 uint64_t OldSize = DF.getContents().size();
805 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
806 assert(Abs && "We created call frame with an invalid expression");
808 SmallString<8> &Data = DF.getContents();
810 raw_svector_ostream OSE(Data);
811 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
812 return OldSize != Data.size();
815 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
816 // Holds the first fragment which needed relaxing during this layout. It will
817 // remain NULL if none were relaxed.
818 // When a fragment is relaxed, all the fragments following it should get
819 // invalidated because their offset is going to change.
820 MCFragment *FirstRelaxedFragment = nullptr;
822 // Attempt to relax all the fragments in the section.
823 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
824 // Check if this is a fragment that needs relaxation.
825 bool RelaxedFrag = false;
826 switch(I->getKind()) {
829 case MCFragment::FT_Relaxable:
830 assert(!getRelaxAll() &&
831 "Did not expect a MCRelaxableFragment in RelaxAll mode");
832 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
834 case MCFragment::FT_Dwarf:
835 RelaxedFrag = relaxDwarfLineAddr(Layout,
836 *cast<MCDwarfLineAddrFragment>(I));
838 case MCFragment::FT_DwarfFrame:
840 relaxDwarfCallFrameFragment(Layout,
841 *cast<MCDwarfCallFrameFragment>(I));
843 case MCFragment::FT_LEB:
844 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
847 if (RelaxedFrag && !FirstRelaxedFragment)
848 FirstRelaxedFragment = &*I;
850 if (FirstRelaxedFragment) {
851 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
857 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
858 ++stats::RelaxationSteps;
860 bool WasRelaxed = false;
861 for (iterator it = begin(), ie = end(); it != ie; ++it) {
862 MCSection &Sec = *it;
863 while (layoutSectionOnce(Layout, Sec))
870 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
871 // The layout is done. Mark every fragment as valid.
872 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
873 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());