[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / llvm / lib / MC / MCAssembler.cpp
blob55558820b670d916cca4e2373bc5c7917c9045c2
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCAssembler.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Statistic.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCAsmLayout.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCCodeView.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/Alignment.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/EndianStream.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/LEB128.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <tuple>
42 #include <utility>
44 using namespace llvm;
46 namespace llvm {
47 class MCSubtargetInfo;
50 #define DEBUG_TYPE "assembler"
52 namespace {
53 namespace stats {
55 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
56 STATISTIC(EmittedRelaxableFragments,
57 "Number of emitted assembler fragments - relaxable");
58 STATISTIC(EmittedDataFragments,
59 "Number of emitted assembler fragments - data");
60 STATISTIC(EmittedCompactEncodedInstFragments,
61 "Number of emitted assembler fragments - compact encoded inst");
62 STATISTIC(EmittedAlignFragments,
63 "Number of emitted assembler fragments - align");
64 STATISTIC(EmittedFillFragments,
65 "Number of emitted assembler fragments - fill");
66 STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
67 STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
68 STATISTIC(evaluateFixup, "Number of evaluated fixups");
69 STATISTIC(FragmentLayouts, "Number of fragment layouts");
70 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
71 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
72 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
74 } // end namespace stats
75 } // end anonymous namespace
77 // FIXME FIXME FIXME: There are number of places in this file where we convert
78 // what is a 64-bit assembler value used for computation into a value in the
79 // object file, which may truncate it. We should detect that truncation where
80 // invalid and report errors back.
82 /* *** */
84 MCAssembler::MCAssembler(MCContext &Context,
85 std::unique_ptr<MCAsmBackend> Backend,
86 std::unique_ptr<MCCodeEmitter> Emitter,
87 std::unique_ptr<MCObjectWriter> Writer)
88 : Context(Context), Backend(std::move(Backend)),
89 Emitter(std::move(Emitter)), Writer(std::move(Writer)),
90 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
91 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
92 VersionInfo.Major = 0; // Major version == 0 for "none specified"
93 DarwinTargetVariantVersionInfo.Major = 0;
96 MCAssembler::~MCAssembler() = default;
98 void MCAssembler::reset() {
99 Sections.clear();
100 Symbols.clear();
101 IndirectSymbols.clear();
102 DataRegions.clear();
103 LinkerOptions.clear();
104 FileNames.clear();
105 ThumbFuncs.clear();
106 BundleAlignSize = 0;
107 RelaxAll = false;
108 SubsectionsViaSymbols = false;
109 IncrementalLinkerCompatible = false;
110 ELFHeaderEFlags = 0;
111 LOHContainer.reset();
112 VersionInfo.Major = 0;
113 VersionInfo.SDKVersion = VersionTuple();
114 DarwinTargetVariantVersionInfo.Major = 0;
115 DarwinTargetVariantVersionInfo.SDKVersion = VersionTuple();
117 // reset objects owned by us
118 if (getBackendPtr())
119 getBackendPtr()->reset();
120 if (getEmitterPtr())
121 getEmitterPtr()->reset();
122 if (getWriterPtr())
123 getWriterPtr()->reset();
124 getLOHContainer().reset();
127 bool MCAssembler::registerSection(MCSection &Section) {
128 if (Section.isRegistered())
129 return false;
130 Sections.push_back(&Section);
131 Section.setIsRegistered(true);
132 return true;
135 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
136 if (ThumbFuncs.count(Symbol))
137 return true;
139 if (!Symbol->isVariable())
140 return false;
142 const MCExpr *Expr = Symbol->getVariableValue();
144 MCValue V;
145 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
146 return false;
148 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
149 return false;
151 const MCSymbolRefExpr *Ref = V.getSymA();
152 if (!Ref)
153 return false;
155 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
156 return false;
158 const MCSymbol &Sym = Ref->getSymbol();
159 if (!isThumbFunc(&Sym))
160 return false;
162 ThumbFuncs.insert(Symbol); // Cache it.
163 return true;
166 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
167 // Non-temporary labels should always be visible to the linker.
168 if (!Symbol.isTemporary())
169 return true;
171 if (Symbol.isUsedInReloc())
172 return true;
174 return false;
177 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
178 // Linker visible symbols define atoms.
179 if (isSymbolLinkerVisible(S))
180 return &S;
182 // Absolute and undefined symbols have no defining atom.
183 if (!S.isInSection())
184 return nullptr;
186 // Non-linker visible symbols in sections which can't be atomized have no
187 // defining atom.
188 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
189 *S.getFragment()->getParent()))
190 return nullptr;
192 // Otherwise, return the atom for the containing fragment.
193 return S.getFragment()->getAtom();
196 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
197 const MCFixup &Fixup, const MCFragment *DF,
198 MCValue &Target, uint64_t &Value,
199 bool &WasForced) const {
200 ++stats::evaluateFixup;
202 // FIXME: This code has some duplication with recordRelocation. We should
203 // probably merge the two into a single callback that tries to evaluate a
204 // fixup and records a relocation if one is needed.
206 // On error claim to have completely evaluated the fixup, to prevent any
207 // further processing from being done.
208 const MCExpr *Expr = Fixup.getValue();
209 MCContext &Ctx = getContext();
210 Value = 0;
211 WasForced = false;
212 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
213 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
214 return true;
216 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
217 if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
218 Ctx.reportError(Fixup.getLoc(),
219 "unsupported subtraction of qualified symbol");
220 return true;
224 assert(getBackendPtr() && "Expected assembler backend");
225 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
226 MCFixupKindInfo::FKF_IsTarget;
228 if (IsTarget)
229 return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
230 Value, WasForced);
232 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
233 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
234 MCFixupKindInfo::FKF_IsPCRel;
236 bool IsResolved = false;
237 if (IsPCRel) {
238 if (Target.getSymB()) {
239 IsResolved = false;
240 } else if (!Target.getSymA()) {
241 IsResolved = false;
242 } else {
243 const MCSymbolRefExpr *A = Target.getSymA();
244 const MCSymbol &SA = A->getSymbol();
245 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
246 IsResolved = false;
247 } else if (auto *Writer = getWriterPtr()) {
248 IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
249 Writer->isSymbolRefDifferenceFullyResolvedImpl(
250 *this, SA, *DF, false, true);
253 } else {
254 IsResolved = Target.isAbsolute();
257 Value = Target.getConstant();
259 if (const MCSymbolRefExpr *A = Target.getSymA()) {
260 const MCSymbol &Sym = A->getSymbol();
261 if (Sym.isDefined())
262 Value += Layout.getSymbolOffset(Sym);
264 if (const MCSymbolRefExpr *B = Target.getSymB()) {
265 const MCSymbol &Sym = B->getSymbol();
266 if (Sym.isDefined())
267 Value -= Layout.getSymbolOffset(Sym);
270 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
271 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
272 assert((ShouldAlignPC ? IsPCRel : true) &&
273 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
275 if (IsPCRel) {
276 uint64_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
278 // A number of ARM fixups in Thumb mode require that the effective PC
279 // address be determined as the 32-bit aligned version of the actual offset.
280 if (ShouldAlignPC) Offset &= ~0x3;
281 Value -= Offset;
284 // Let the backend force a relocation if needed.
285 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
286 IsResolved = false;
287 WasForced = true;
290 // A linker relaxation target may emit ADD/SUB relocations for A-B+C. Let
291 // recordRelocation handle non-VK_None cases like A@plt-B+C.
292 if (!IsResolved && Target.getSymA() && Target.getSymB() &&
293 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_None &&
294 getBackend().handleAddSubRelocations(Layout, *DF, Fixup, Target, Value))
295 return true;
297 return IsResolved;
300 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
301 const MCFragment &F) const {
302 assert(getBackendPtr() && "Requires assembler backend");
303 switch (F.getKind()) {
304 case MCFragment::FT_Data:
305 return cast<MCDataFragment>(F).getContents().size();
306 case MCFragment::FT_Relaxable:
307 return cast<MCRelaxableFragment>(F).getContents().size();
308 case MCFragment::FT_CompactEncodedInst:
309 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
310 case MCFragment::FT_Fill: {
311 auto &FF = cast<MCFillFragment>(F);
312 int64_t NumValues = 0;
313 if (!FF.getNumValues().evaluateKnownAbsolute(NumValues, Layout)) {
314 getContext().reportError(FF.getLoc(),
315 "expected assembly-time absolute expression");
316 return 0;
318 int64_t Size = NumValues * FF.getValueSize();
319 if (Size < 0) {
320 getContext().reportError(FF.getLoc(), "invalid number of bytes");
321 return 0;
323 return Size;
326 case MCFragment::FT_Nops:
327 return cast<MCNopsFragment>(F).getNumBytes();
329 case MCFragment::FT_LEB:
330 return cast<MCLEBFragment>(F).getContents().size();
332 case MCFragment::FT_BoundaryAlign:
333 return cast<MCBoundaryAlignFragment>(F).getSize();
335 case MCFragment::FT_SymbolId:
336 return 4;
338 case MCFragment::FT_Align: {
339 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
340 unsigned Offset = Layout.getFragmentOffset(&AF);
341 unsigned Size = offsetToAlignment(Offset, AF.getAlignment());
343 // Insert extra Nops for code alignment if the target define
344 // shouldInsertExtraNopBytesForCodeAlign target hook.
345 if (AF.getParent()->useCodeAlign() && AF.hasEmitNops() &&
346 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
347 return Size;
349 // If we are padding with nops, force the padding to be larger than the
350 // minimum nop size.
351 if (Size > 0 && AF.hasEmitNops()) {
352 while (Size % getBackend().getMinimumNopSize())
353 Size += AF.getAlignment().value();
355 if (Size > AF.getMaxBytesToEmit())
356 return 0;
357 return Size;
360 case MCFragment::FT_Org: {
361 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
362 MCValue Value;
363 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
364 getContext().reportError(OF.getLoc(),
365 "expected assembly-time absolute expression");
366 return 0;
369 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
370 int64_t TargetLocation = Value.getConstant();
371 if (const MCSymbolRefExpr *A = Value.getSymA()) {
372 uint64_t Val;
373 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
374 getContext().reportError(OF.getLoc(), "expected absolute expression");
375 return 0;
377 TargetLocation += Val;
379 int64_t Size = TargetLocation - FragmentOffset;
380 if (Size < 0 || Size >= 0x40000000) {
381 getContext().reportError(
382 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
383 "' (at offset '" + Twine(FragmentOffset) + "')");
384 return 0;
386 return Size;
389 case MCFragment::FT_Dwarf:
390 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
391 case MCFragment::FT_DwarfFrame:
392 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
393 case MCFragment::FT_CVInlineLines:
394 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
395 case MCFragment::FT_CVDefRange:
396 return cast<MCCVDefRangeFragment>(F).getContents().size();
397 case MCFragment::FT_PseudoProbe:
398 return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
399 case MCFragment::FT_Dummy:
400 llvm_unreachable("Should not have been added");
403 llvm_unreachable("invalid fragment kind");
406 void MCAsmLayout::layoutFragment(MCFragment *F) {
407 MCFragment *Prev = F->getPrevNode();
409 // We should never try to recompute something which is valid.
410 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
411 // We should never try to compute the fragment layout if its predecessor
412 // isn't valid.
413 assert((!Prev || isFragmentValid(Prev)) &&
414 "Attempt to compute fragment before its predecessor!");
416 assert(!F->IsBeingLaidOut && "Already being laid out!");
417 F->IsBeingLaidOut = true;
419 ++stats::FragmentLayouts;
421 // Compute fragment offset and size.
422 if (Prev)
423 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
424 else
425 F->Offset = 0;
426 F->IsBeingLaidOut = false;
427 LastValidFragment[F->getParent()] = F;
429 // If bundling is enabled and this fragment has instructions in it, it has to
430 // obey the bundling restrictions. With padding, we'll have:
433 // BundlePadding
434 // |||
435 // -------------------------------------
436 // Prev |##########| F |
437 // -------------------------------------
438 // ^
439 // |
440 // F->Offset
442 // The fragment's offset will point to after the padding, and its computed
443 // size won't include the padding.
445 // When the -mc-relax-all flag is used, we optimize bundling by writting the
446 // padding directly into fragments when the instructions are emitted inside
447 // the streamer. When the fragment is larger than the bundle size, we need to
448 // ensure that it's bundle aligned. This means that if we end up with
449 // multiple fragments, we must emit bundle padding between fragments.
451 // ".align N" is an example of a directive that introduces multiple
452 // fragments. We could add a special case to handle ".align N" by emitting
453 // within-fragment padding (which would produce less padding when N is less
454 // than the bundle size), but for now we don't.
456 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
457 assert(isa<MCEncodedFragment>(F) &&
458 "Only MCEncodedFragment implementations have instructions");
459 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
460 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
462 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
463 report_fatal_error("Fragment can't be larger than a bundle size");
465 uint64_t RequiredBundlePadding =
466 computeBundlePadding(Assembler, EF, EF->Offset, FSize);
467 if (RequiredBundlePadding > UINT8_MAX)
468 report_fatal_error("Padding cannot exceed 255 bytes");
469 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
470 EF->Offset += RequiredBundlePadding;
474 bool MCAssembler::registerSymbol(const MCSymbol &Symbol) {
475 bool Changed = !Symbol.isRegistered();
476 if (Changed) {
477 Symbol.setIsRegistered(true);
478 Symbols.push_back(&Symbol);
480 return Changed;
483 void MCAssembler::writeFragmentPadding(raw_ostream &OS,
484 const MCEncodedFragment &EF,
485 uint64_t FSize) const {
486 assert(getBackendPtr() && "Expected assembler backend");
487 // Should NOP padding be written out before this fragment?
488 unsigned BundlePadding = EF.getBundlePadding();
489 if (BundlePadding > 0) {
490 assert(isBundlingEnabled() &&
491 "Writing bundle padding with disabled bundling");
492 assert(EF.hasInstructions() &&
493 "Writing bundle padding for a fragment without instructions");
495 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
496 const MCSubtargetInfo *STI = EF.getSubtargetInfo();
497 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
498 // If the padding itself crosses a bundle boundary, it must be emitted
499 // in 2 pieces, since even nop instructions must not cross boundaries.
500 // v--------------v <- BundleAlignSize
501 // v---------v <- BundlePadding
502 // ----------------------------
503 // | Prev |####|####| F |
504 // ----------------------------
505 // ^-------------------^ <- TotalLength
506 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
507 if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
508 report_fatal_error("unable to write NOP sequence of " +
509 Twine(DistanceToBoundary) + " bytes");
510 BundlePadding -= DistanceToBoundary;
512 if (!getBackend().writeNopData(OS, BundlePadding, STI))
513 report_fatal_error("unable to write NOP sequence of " +
514 Twine(BundlePadding) + " bytes");
518 /// Write the fragment \p F to the output file.
519 static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
520 const MCAsmLayout &Layout, const MCFragment &F) {
521 // FIXME: Embed in fragments instead?
522 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
524 llvm::endianness Endian = Asm.getBackend().Endian;
526 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
527 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
529 // This variable (and its dummy usage) is to participate in the assert at
530 // the end of the function.
531 uint64_t Start = OS.tell();
532 (void) Start;
534 ++stats::EmittedFragments;
536 switch (F.getKind()) {
537 case MCFragment::FT_Align: {
538 ++stats::EmittedAlignFragments;
539 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
540 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
542 uint64_t Count = FragmentSize / AF.getValueSize();
544 // FIXME: This error shouldn't actually occur (the front end should emit
545 // multiple .align directives to enforce the semantics it wants), but is
546 // severe enough that we want to report it. How to handle this?
547 if (Count * AF.getValueSize() != FragmentSize)
548 report_fatal_error("undefined .align directive, value size '" +
549 Twine(AF.getValueSize()) +
550 "' is not a divisor of padding size '" +
551 Twine(FragmentSize) + "'");
553 // See if we are aligning with nops, and if so do that first to try to fill
554 // the Count bytes. Then if that did not fill any bytes or there are any
555 // bytes left to fill use the Value and ValueSize to fill the rest.
556 // If we are aligning with nops, ask that target to emit the right data.
557 if (AF.hasEmitNops()) {
558 if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
559 report_fatal_error("unable to write nop sequence of " +
560 Twine(Count) + " bytes");
561 break;
564 // Otherwise, write out in multiples of the value size.
565 for (uint64_t i = 0; i != Count; ++i) {
566 switch (AF.getValueSize()) {
567 default: llvm_unreachable("Invalid size!");
568 case 1: OS << char(AF.getValue()); break;
569 case 2:
570 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
571 break;
572 case 4:
573 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
574 break;
575 case 8:
576 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
577 break;
580 break;
583 case MCFragment::FT_Data:
584 ++stats::EmittedDataFragments;
585 OS << cast<MCDataFragment>(F).getContents();
586 break;
588 case MCFragment::FT_Relaxable:
589 ++stats::EmittedRelaxableFragments;
590 OS << cast<MCRelaxableFragment>(F).getContents();
591 break;
593 case MCFragment::FT_CompactEncodedInst:
594 ++stats::EmittedCompactEncodedInstFragments;
595 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
596 break;
598 case MCFragment::FT_Fill: {
599 ++stats::EmittedFillFragments;
600 const MCFillFragment &FF = cast<MCFillFragment>(F);
601 uint64_t V = FF.getValue();
602 unsigned VSize = FF.getValueSize();
603 const unsigned MaxChunkSize = 16;
604 char Data[MaxChunkSize];
605 assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
606 // Duplicate V into Data as byte vector to reduce number of
607 // writes done. As such, do endian conversion here.
608 for (unsigned I = 0; I != VSize; ++I) {
609 unsigned index = Endian == llvm::endianness::little ? I : (VSize - I - 1);
610 Data[I] = uint8_t(V >> (index * 8));
612 for (unsigned I = VSize; I < MaxChunkSize; ++I)
613 Data[I] = Data[I - VSize];
615 // Set to largest multiple of VSize in Data.
616 const unsigned NumPerChunk = MaxChunkSize / VSize;
617 // Set ChunkSize to largest multiple of VSize in Data
618 const unsigned ChunkSize = VSize * NumPerChunk;
620 // Do copies by chunk.
621 StringRef Ref(Data, ChunkSize);
622 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
623 OS << Ref;
625 // do remainder if needed.
626 unsigned TrailingCount = FragmentSize % ChunkSize;
627 if (TrailingCount)
628 OS.write(Data, TrailingCount);
629 break;
632 case MCFragment::FT_Nops: {
633 ++stats::EmittedNopsFragments;
634 const MCNopsFragment &NF = cast<MCNopsFragment>(F);
636 int64_t NumBytes = NF.getNumBytes();
637 int64_t ControlledNopLength = NF.getControlledNopLength();
638 int64_t MaximumNopLength =
639 Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
641 assert(NumBytes > 0 && "Expected positive NOPs fragment size");
642 assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
644 if (ControlledNopLength > MaximumNopLength) {
645 Asm.getContext().reportError(NF.getLoc(),
646 "illegal NOP size " +
647 std::to_string(ControlledNopLength) +
648 ". (expected within [0, " +
649 std::to_string(MaximumNopLength) + "])");
650 // Clamp the NOP length as reportError does not stop the execution
651 // immediately.
652 ControlledNopLength = MaximumNopLength;
655 // Use maximum value if the size of each NOP is not specified
656 if (!ControlledNopLength)
657 ControlledNopLength = MaximumNopLength;
659 while (NumBytes) {
660 uint64_t NumBytesToEmit =
661 (uint64_t)std::min(NumBytes, ControlledNopLength);
662 assert(NumBytesToEmit && "try to emit empty NOP instruction");
663 if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
664 NF.getSubtargetInfo())) {
665 report_fatal_error("unable to write nop sequence of the remaining " +
666 Twine(NumBytesToEmit) + " bytes");
667 break;
669 NumBytes -= NumBytesToEmit;
671 break;
674 case MCFragment::FT_LEB: {
675 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
676 OS << LF.getContents();
677 break;
680 case MCFragment::FT_BoundaryAlign: {
681 const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
682 if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
683 report_fatal_error("unable to write nop sequence of " +
684 Twine(FragmentSize) + " bytes");
685 break;
688 case MCFragment::FT_SymbolId: {
689 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
690 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
691 break;
694 case MCFragment::FT_Org: {
695 ++stats::EmittedOrgFragments;
696 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
698 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
699 OS << char(OF.getValue());
701 break;
704 case MCFragment::FT_Dwarf: {
705 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
706 OS << OF.getContents();
707 break;
709 case MCFragment::FT_DwarfFrame: {
710 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
711 OS << CF.getContents();
712 break;
714 case MCFragment::FT_CVInlineLines: {
715 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
716 OS << OF.getContents();
717 break;
719 case MCFragment::FT_CVDefRange: {
720 const auto &DRF = cast<MCCVDefRangeFragment>(F);
721 OS << DRF.getContents();
722 break;
724 case MCFragment::FT_PseudoProbe: {
725 const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
726 OS << PF.getContents();
727 break;
729 case MCFragment::FT_Dummy:
730 llvm_unreachable("Should not have been added");
733 assert(OS.tell() - Start == FragmentSize &&
734 "The stream should advance by fragment size");
737 void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
738 const MCAsmLayout &Layout) const {
739 assert(getBackendPtr() && "Expected assembler backend");
741 // Ignore virtual sections.
742 if (Sec->isVirtualSection()) {
743 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
745 // Check that contents are only things legal inside a virtual section.
746 for (const MCFragment &F : *Sec) {
747 switch (F.getKind()) {
748 default: llvm_unreachable("Invalid fragment in virtual section!");
749 case MCFragment::FT_Data: {
750 // Check that we aren't trying to write a non-zero contents (or fixups)
751 // into a virtual section. This is to support clients which use standard
752 // directives to fill the contents of virtual sections.
753 const MCDataFragment &DF = cast<MCDataFragment>(F);
754 if (DF.fixup_begin() != DF.fixup_end())
755 getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
756 " section '" + Sec->getName() +
757 "' cannot have fixups");
758 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
759 if (DF.getContents()[i]) {
760 getContext().reportError(SMLoc(),
761 Sec->getVirtualSectionKind() +
762 " section '" + Sec->getName() +
763 "' cannot have non-zero initializers");
764 break;
766 break;
768 case MCFragment::FT_Align:
769 // Check that we aren't trying to write a non-zero value into a virtual
770 // section.
771 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
772 cast<MCAlignFragment>(F).getValue() == 0) &&
773 "Invalid align in virtual section!");
774 break;
775 case MCFragment::FT_Fill:
776 assert((cast<MCFillFragment>(F).getValue() == 0) &&
777 "Invalid fill in virtual section!");
778 break;
779 case MCFragment::FT_Org:
780 break;
784 return;
787 uint64_t Start = OS.tell();
788 (void)Start;
790 for (const MCFragment &F : *Sec)
791 writeFragment(OS, *this, Layout, F);
793 assert(getContext().hadError() ||
794 OS.tell() - Start == Layout.getSectionAddressSize(Sec));
797 std::tuple<MCValue, uint64_t, bool>
798 MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
799 const MCFixup &Fixup) {
800 // Evaluate the fixup.
801 MCValue Target;
802 uint64_t FixedValue;
803 bool WasForced;
804 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
805 WasForced);
806 if (!IsResolved) {
807 // The fixup was unresolved, we need a relocation. Inform the object
808 // writer of the relocation, and give it an opportunity to adjust the
809 // fixup value if need be.
810 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
812 return std::make_tuple(Target, FixedValue, IsResolved);
815 void MCAssembler::layout(MCAsmLayout &Layout) {
816 assert(getBackendPtr() && "Expected assembler backend");
817 DEBUG_WITH_TYPE("mc-dump", {
818 errs() << "assembler backend - pre-layout\n--\n";
819 dump(); });
821 // Create dummy fragments and assign section ordinals.
822 unsigned SectionIndex = 0;
823 for (MCSection &Sec : *this) {
824 // Create dummy fragments to eliminate any empty sections, this simplifies
825 // layout.
826 if (Sec.getFragmentList().empty())
827 new MCDataFragment(&Sec);
829 Sec.setOrdinal(SectionIndex++);
832 // Assign layout order indices to sections and fragments.
833 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
834 MCSection *Sec = Layout.getSectionOrder()[i];
835 Sec->setLayoutOrder(i);
837 unsigned FragmentIndex = 0;
838 for (MCFragment &Frag : *Sec)
839 Frag.setLayoutOrder(FragmentIndex++);
842 // Layout until everything fits.
843 while (layoutOnce(Layout)) {
844 if (getContext().hadError())
845 return;
846 // Size of fragments in one section can depend on the size of fragments in
847 // another. If any fragment has changed size, we have to re-layout (and
848 // as a result possibly further relax) all.
849 for (MCSection &Sec : *this)
850 Layout.invalidateFragmentsFrom(&*Sec.begin());
853 DEBUG_WITH_TYPE("mc-dump", {
854 errs() << "assembler backend - post-relaxation\n--\n";
855 dump(); });
857 // Finalize the layout, including fragment lowering.
858 finishLayout(Layout);
860 DEBUG_WITH_TYPE("mc-dump", {
861 errs() << "assembler backend - final-layout\n--\n";
862 dump(); });
864 // Allow the object writer a chance to perform post-layout binding (for
865 // example, to set the index fields in the symbol data).
866 getWriter().executePostLayoutBinding(*this, Layout);
868 // Evaluate and apply the fixups, generating relocation entries as necessary.
869 for (MCSection &Sec : *this) {
870 for (MCFragment &Frag : Sec) {
871 ArrayRef<MCFixup> Fixups;
872 MutableArrayRef<char> Contents;
873 const MCSubtargetInfo *STI = nullptr;
875 // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
876 switch (Frag.getKind()) {
877 default:
878 continue;
879 case MCFragment::FT_Align: {
880 MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
881 // Insert fixup type for code alignment if the target define
882 // shouldInsertFixupForCodeAlign target hook.
883 if (Sec.useCodeAlign() && AF.hasEmitNops())
884 getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
885 continue;
887 case MCFragment::FT_Data: {
888 MCDataFragment &DF = cast<MCDataFragment>(Frag);
889 Fixups = DF.getFixups();
890 Contents = DF.getContents();
891 STI = DF.getSubtargetInfo();
892 assert(!DF.hasInstructions() || STI != nullptr);
893 break;
895 case MCFragment::FT_Relaxable: {
896 MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
897 Fixups = RF.getFixups();
898 Contents = RF.getContents();
899 STI = RF.getSubtargetInfo();
900 assert(!RF.hasInstructions() || STI != nullptr);
901 break;
903 case MCFragment::FT_CVDefRange: {
904 MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
905 Fixups = CF.getFixups();
906 Contents = CF.getContents();
907 break;
909 case MCFragment::FT_Dwarf: {
910 MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
911 Fixups = DF.getFixups();
912 Contents = DF.getContents();
913 break;
915 case MCFragment::FT_DwarfFrame: {
916 MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
917 Fixups = DF.getFixups();
918 Contents = DF.getContents();
919 break;
921 case MCFragment::FT_PseudoProbe: {
922 MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
923 Fixups = PF.getFixups();
924 Contents = PF.getContents();
925 break;
928 for (const MCFixup &Fixup : Fixups) {
929 uint64_t FixedValue;
930 bool IsResolved;
931 MCValue Target;
932 std::tie(Target, FixedValue, IsResolved) =
933 handleFixup(Layout, Frag, Fixup);
934 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
935 IsResolved, STI);
941 void MCAssembler::Finish() {
942 // Create the layout object.
943 MCAsmLayout Layout(*this);
944 layout(Layout);
946 // Write the object file.
947 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
950 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
951 const MCRelaxableFragment *DF,
952 const MCAsmLayout &Layout) const {
953 assert(getBackendPtr() && "Expected assembler backend");
954 MCValue Target;
955 uint64_t Value;
956 bool WasForced;
957 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
958 if (Target.getSymA() &&
959 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
960 Fixup.getKind() == FK_Data_1)
961 return false;
962 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
963 Layout, WasForced);
966 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
967 const MCAsmLayout &Layout) const {
968 assert(getBackendPtr() && "Expected assembler backend");
969 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
970 // are intentionally pushing out inst fragments, or because we relaxed a
971 // previous instruction to one that doesn't need relaxation.
972 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
973 return false;
975 for (const MCFixup &Fixup : F->getFixups())
976 if (fixupNeedsRelaxation(Fixup, F, Layout))
977 return true;
979 return false;
982 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
983 MCRelaxableFragment &F) {
984 assert(getEmitterPtr() &&
985 "Expected CodeEmitter defined for relaxInstruction");
986 if (!fragmentNeedsRelaxation(&F, Layout))
987 return false;
989 ++stats::RelaxedInstructions;
991 // FIXME-PERF: We could immediately lower out instructions if we can tell
992 // they are fully resolved, to avoid retesting on later passes.
994 // Relax the fragment.
996 MCInst Relaxed = F.getInst();
997 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
999 // Encode the new instruction.
1000 F.setInst(Relaxed);
1001 F.getFixups().clear();
1002 F.getContents().clear();
1003 getEmitter().encodeInstruction(Relaxed, F.getContents(), F.getFixups(),
1004 *F.getSubtargetInfo());
1005 return true;
1008 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1009 uint64_t OldSize = LF.getContents().size();
1010 int64_t Value;
1011 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1012 if (!Abs) {
1013 getContext().reportError(LF.getValue().getLoc(),
1014 Twine(LF.isSigned() ? ".s" : ".u") +
1015 "leb128 expression is not absolute");
1017 SmallString<8> &Data = LF.getContents();
1018 Data.clear();
1019 raw_svector_ostream OSE(Data);
1020 // The compiler can generate EH table assembly that is impossible to assemble
1021 // without either adding padding to an LEB fragment or adding extra padding
1022 // to a later alignment fragment. To accommodate such tables, relaxation can
1023 // only increase an LEB fragment size here, not decrease it. See PR35809.
1024 if (LF.isSigned())
1025 encodeSLEB128(Value, OSE, OldSize);
1026 else
1027 encodeULEB128(Value, OSE, OldSize);
1028 return OldSize != LF.getContents().size();
1031 /// Check if the branch crosses the boundary.
1033 /// \param StartAddr start address of the fused/unfused branch.
1034 /// \param Size size of the fused/unfused branch.
1035 /// \param BoundaryAlignment alignment requirement of the branch.
1036 /// \returns true if the branch cross the boundary.
1037 static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
1038 Align BoundaryAlignment) {
1039 uint64_t EndAddr = StartAddr + Size;
1040 return (StartAddr >> Log2(BoundaryAlignment)) !=
1041 ((EndAddr - 1) >> Log2(BoundaryAlignment));
1044 /// Check if the branch is against the boundary.
1046 /// \param StartAddr start address of the fused/unfused branch.
1047 /// \param Size size of the fused/unfused branch.
1048 /// \param BoundaryAlignment alignment requirement of the branch.
1049 /// \returns true if the branch is against the boundary.
1050 static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
1051 Align BoundaryAlignment) {
1052 uint64_t EndAddr = StartAddr + Size;
1053 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1056 /// Check if the branch needs padding.
1058 /// \param StartAddr start address of the fused/unfused branch.
1059 /// \param Size size of the fused/unfused branch.
1060 /// \param BoundaryAlignment alignment requirement of the branch.
1061 /// \returns true if the branch needs padding.
1062 static bool needPadding(uint64_t StartAddr, uint64_t Size,
1063 Align BoundaryAlignment) {
1064 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1065 isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1068 bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1069 MCBoundaryAlignFragment &BF) {
1070 // BoundaryAlignFragment that doesn't need to align any fragment should not be
1071 // relaxed.
1072 if (!BF.getLastFragment())
1073 return false;
1075 uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1076 uint64_t AlignedSize = 0;
1077 for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1078 F = F->getPrevNode())
1079 AlignedSize += computeFragmentSize(Layout, *F);
1081 Align BoundaryAlignment = BF.getAlignment();
1082 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1083 ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1084 : 0U;
1085 if (NewSize == BF.getSize())
1086 return false;
1087 BF.setSize(NewSize);
1088 Layout.invalidateFragmentsFrom(&BF);
1089 return true;
1092 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1093 MCDwarfLineAddrFragment &DF) {
1095 bool WasRelaxed;
1096 if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
1097 return WasRelaxed;
1099 MCContext &Context = Layout.getAssembler().getContext();
1100 uint64_t OldSize = DF.getContents().size();
1101 int64_t AddrDelta;
1102 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1103 assert(Abs && "We created a line delta with an invalid expression");
1104 (void)Abs;
1105 int64_t LineDelta;
1106 LineDelta = DF.getLineDelta();
1107 SmallVectorImpl<char> &Data = DF.getContents();
1108 Data.clear();
1109 DF.getFixups().clear();
1111 MCDwarfLineAddr::encode(Context, getDWARFLinetableParams(), LineDelta,
1112 AddrDelta, Data);
1113 return OldSize != Data.size();
1116 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1117 MCDwarfCallFrameFragment &DF) {
1118 bool WasRelaxed;
1119 if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
1120 return WasRelaxed;
1122 MCContext &Context = Layout.getAssembler().getContext();
1123 int64_t Value;
1124 bool Abs = DF.getAddrDelta().evaluateAsAbsolute(Value, Layout);
1125 if (!Abs) {
1126 getContext().reportError(DF.getAddrDelta().getLoc(),
1127 "invalid CFI advance_loc expression");
1128 DF.setAddrDelta(MCConstantExpr::create(0, Context));
1129 return false;
1132 SmallVectorImpl<char> &Data = DF.getContents();
1133 uint64_t OldSize = Data.size();
1134 Data.clear();
1135 DF.getFixups().clear();
1137 MCDwarfFrameEmitter::encodeAdvanceLoc(Context, Value, Data);
1138 return OldSize != Data.size();
1141 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1142 MCCVInlineLineTableFragment &F) {
1143 unsigned OldSize = F.getContents().size();
1144 getContext().getCVContext().encodeInlineLineTable(Layout, F);
1145 return OldSize != F.getContents().size();
1148 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1149 MCCVDefRangeFragment &F) {
1150 unsigned OldSize = F.getContents().size();
1151 getContext().getCVContext().encodeDefRange(Layout, F);
1152 return OldSize != F.getContents().size();
1155 bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
1156 MCPseudoProbeAddrFragment &PF) {
1157 uint64_t OldSize = PF.getContents().size();
1158 int64_t AddrDelta;
1159 bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1160 assert(Abs && "We created a pseudo probe with an invalid expression");
1161 (void)Abs;
1162 SmallVectorImpl<char> &Data = PF.getContents();
1163 Data.clear();
1164 raw_svector_ostream OSE(Data);
1165 PF.getFixups().clear();
1167 // AddrDelta is a signed integer
1168 encodeSLEB128(AddrDelta, OSE, OldSize);
1169 return OldSize != Data.size();
1172 bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1173 switch(F.getKind()) {
1174 default:
1175 return false;
1176 case MCFragment::FT_Relaxable:
1177 assert(!getRelaxAll() &&
1178 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1179 return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1180 case MCFragment::FT_Dwarf:
1181 return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1182 case MCFragment::FT_DwarfFrame:
1183 return relaxDwarfCallFrameFragment(Layout,
1184 cast<MCDwarfCallFrameFragment>(F));
1185 case MCFragment::FT_LEB:
1186 return relaxLEB(Layout, cast<MCLEBFragment>(F));
1187 case MCFragment::FT_BoundaryAlign:
1188 return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1189 case MCFragment::FT_CVInlineLines:
1190 return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1191 case MCFragment::FT_CVDefRange:
1192 return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1193 case MCFragment::FT_PseudoProbe:
1194 return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
1198 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1199 // Holds the first fragment which needed relaxing during this layout. It will
1200 // remain NULL if none were relaxed.
1201 // When a fragment is relaxed, all the fragments following it should get
1202 // invalidated because their offset is going to change.
1203 MCFragment *FirstRelaxedFragment = nullptr;
1205 // Attempt to relax all the fragments in the section.
1206 for (MCFragment &Frag : Sec) {
1207 // Check if this is a fragment that needs relaxation.
1208 bool RelaxedFrag = relaxFragment(Layout, Frag);
1209 if (RelaxedFrag && !FirstRelaxedFragment)
1210 FirstRelaxedFragment = &Frag;
1212 if (FirstRelaxedFragment) {
1213 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1214 return true;
1216 return false;
1219 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1220 ++stats::RelaxationSteps;
1222 bool WasRelaxed = false;
1223 for (MCSection &Sec : *this) {
1224 while (layoutSectionOnce(Layout, Sec))
1225 WasRelaxed = true;
1228 return WasRelaxed;
1231 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1232 assert(getBackendPtr() && "Expected assembler backend");
1233 // The layout is done. Mark every fragment as valid.
1234 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1235 MCSection &Section = *Layout.getSectionOrder()[i];
1236 Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1237 computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1239 getBackend().finishLayout(*this, Layout);
1242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1243 LLVM_DUMP_METHOD void MCAssembler::dump() const{
1244 raw_ostream &OS = errs();
1246 OS << "<MCAssembler\n";
1247 OS << " Sections:[\n ";
1248 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1249 if (it != begin()) OS << ",\n ";
1250 it->dump();
1252 OS << "],\n";
1253 OS << " Symbols:[";
1255 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1256 if (it != symbol_begin()) OS << ",\n ";
1257 OS << "(";
1258 it->dump();
1259 OS << ", Index:" << it->getIndex() << ", ";
1260 OS << ")";
1262 OS << "]>\n";
1264 #endif