LLVM 19.0.0git
MCAssembler.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/Statistic.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
17#include "llvm/MC/MCAsmInfo.h"
19#include "llvm/MC/MCCodeView.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCDwarf.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCFixup.h"
25#include "llvm/MC/MCFragment.h"
26#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/MC/MCValue.h"
33#include "llvm/Support/Debug.h"
36#include "llvm/Support/LEB128.h"
38#include <cassert>
39#include <cstdint>
40#include <tuple>
41#include <utility>
42
43using namespace llvm;
44
45namespace llvm {
46class MCSubtargetInfo;
47}
48
49#define DEBUG_TYPE "assembler"
50
51namespace {
52namespace stats {
53
54STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
55STATISTIC(EmittedRelaxableFragments,
56 "Number of emitted assembler fragments - relaxable");
57STATISTIC(EmittedDataFragments,
58 "Number of emitted assembler fragments - data");
59STATISTIC(EmittedCompactEncodedInstFragments,
60 "Number of emitted assembler fragments - compact encoded inst");
61STATISTIC(EmittedAlignFragments,
62 "Number of emitted assembler fragments - align");
63STATISTIC(EmittedFillFragments,
64 "Number of emitted assembler fragments - fill");
65STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
66STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
67STATISTIC(evaluateFixup, "Number of evaluated fixups");
68STATISTIC(ObjectBytes, "Number of emitted object file bytes");
69STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
70STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
71
72} // end namespace stats
73} // end anonymous namespace
74
75// FIXME FIXME FIXME: There are number of places in this file where we convert
76// what is a 64-bit assembler value used for computation into a value in the
77// object file, which may truncate it. We should detect that truncation where
78// invalid and report errors back.
79
80/* *** */
81
83 std::unique_ptr<MCAsmBackend> Backend,
84 std::unique_ptr<MCCodeEmitter> Emitter,
85 std::unique_ptr<MCObjectWriter> Writer)
86 : Context(Context), Backend(std::move(Backend)),
87 Emitter(std::move(Emitter)), Writer(std::move(Writer)) {
88 VersionInfo.Major = 0; // Major version == 0 for "none specified"
89 DarwinTargetVariantVersionInfo.Major = 0;
90}
91
93
95 RelaxAll = false;
96 SubsectionsViaSymbols = false;
97 IncrementalLinkerCompatible = false;
98 Sections.clear();
99 Symbols.clear();
100 LinkerOptions.clear();
101 FileNames.clear();
102 ThumbFuncs.clear();
103 BundleAlignSize = 0;
104 ELFHeaderEFlags = 0;
105 LOHContainer.reset();
106 VersionInfo.Major = 0;
107 VersionInfo.SDKVersion = VersionTuple();
108 DarwinTargetVariantVersionInfo.Major = 0;
109 DarwinTargetVariantVersionInfo.SDKVersion = VersionTuple();
110
111 // reset objects owned by us
112 if (getBackendPtr())
113 getBackendPtr()->reset();
114 if (getEmitterPtr())
115 getEmitterPtr()->reset();
116 if (getWriterPtr())
117 getWriterPtr()->reset();
119}
120
122 if (Section.isRegistered())
123 return false;
124 assert(Section.curFragList()->Head && "allocInitialFragment not called");
125 Sections.push_back(&Section);
126 Section.setIsRegistered(true);
127 return true;
128}
129
130bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
131 if (ThumbFuncs.count(Symbol))
132 return true;
133
134 if (!Symbol->isVariable())
135 return false;
136
137 const MCExpr *Expr = Symbol->getVariableValue();
138
139 MCValue V;
140 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
141 return false;
142
143 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
144 return false;
145
146 const MCSymbolRefExpr *Ref = V.getSymA();
147 if (!Ref)
148 return false;
149
150 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
151 return false;
152
153 const MCSymbol &Sym = Ref->getSymbol();
154 if (!isThumbFunc(&Sym))
155 return false;
156
157 ThumbFuncs.insert(Symbol); // Cache it.
158 return true;
159}
160
161bool MCAssembler::evaluateFixup(const MCFixup &Fixup, const MCFragment *DF,
162 MCValue &Target, const MCSubtargetInfo *STI,
163 uint64_t &Value, bool &WasForced) const {
164 ++stats::evaluateFixup;
165
166 // FIXME: This code has some duplication with recordRelocation. We should
167 // probably merge the two into a single callback that tries to evaluate a
168 // fixup and records a relocation if one is needed.
169
170 // On error claim to have completely evaluated the fixup, to prevent any
171 // further processing from being done.
172 const MCExpr *Expr = Fixup.getValue();
173 MCContext &Ctx = getContext();
174 Value = 0;
175 WasForced = false;
176 if (!Expr->evaluateAsRelocatable(Target, this, &Fixup)) {
177 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
178 return true;
179 }
180 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
181 if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
182 Ctx.reportError(Fixup.getLoc(),
183 "unsupported subtraction of qualified symbol");
184 return true;
185 }
186 }
187
188 assert(getBackendPtr() && "Expected assembler backend");
189 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
191
192 if (IsTarget)
193 return getBackend().evaluateTargetFixup(*this, Fixup, DF, Target, STI,
194 Value, WasForced);
195
196 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
197 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
199
200 bool IsResolved = false;
201 if (IsPCRel) {
202 if (Target.getSymB()) {
203 IsResolved = false;
204 } else if (!Target.getSymA()) {
205 IsResolved = false;
206 } else {
207 const MCSymbolRefExpr *A = Target.getSymA();
208 const MCSymbol &SA = A->getSymbol();
209 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
210 IsResolved = false;
211 } else if (auto *Writer = getWriterPtr()) {
212 IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
213 Writer->isSymbolRefDifferenceFullyResolvedImpl(
214 *this, SA, *DF, false, true);
215 }
216 }
217 } else {
218 IsResolved = Target.isAbsolute();
219 }
220
221 Value = Target.getConstant();
222
223 if (const MCSymbolRefExpr *A = Target.getSymA()) {
224 const MCSymbol &Sym = A->getSymbol();
225 if (Sym.isDefined())
227 }
228 if (const MCSymbolRefExpr *B = Target.getSymB()) {
229 const MCSymbol &Sym = B->getSymbol();
230 if (Sym.isDefined())
232 }
233
234 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
236 assert((ShouldAlignPC ? IsPCRel : true) &&
237 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
238
239 if (IsPCRel) {
240 uint64_t Offset = getFragmentOffset(*DF) + Fixup.getOffset();
241
242 // A number of ARM fixups in Thumb mode require that the effective PC
243 // address be determined as the 32-bit aligned version of the actual offset.
244 if (ShouldAlignPC) Offset &= ~0x3;
245 Value -= Offset;
246 }
247
248 // Let the backend force a relocation if needed.
249 if (IsResolved &&
250 getBackend().shouldForceRelocation(*this, Fixup, Target, STI)) {
251 IsResolved = false;
252 WasForced = true;
253 }
254
255 // A linker relaxation target may emit ADD/SUB relocations for A-B+C. Let
256 // recordRelocation handle non-VK_None cases like A@plt-B+C.
257 if (!IsResolved && Target.getSymA() && Target.getSymB() &&
258 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_None &&
259 getBackend().handleAddSubRelocations(*this, *DF, Fixup, Target, Value))
260 return true;
261
262 return IsResolved;
263}
264
266 assert(getBackendPtr() && "Requires assembler backend");
267 switch (F.getKind()) {
269 return cast<MCDataFragment>(F).getContents().size();
271 return cast<MCRelaxableFragment>(F).getContents().size();
273 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
274 case MCFragment::FT_Fill: {
275 auto &FF = cast<MCFillFragment>(F);
276 int64_t NumValues = 0;
277 if (!FF.getNumValues().evaluateKnownAbsolute(NumValues, *this)) {
278 getContext().reportError(FF.getLoc(),
279 "expected assembly-time absolute expression");
280 return 0;
281 }
282 int64_t Size = NumValues * FF.getValueSize();
283 if (Size < 0) {
284 getContext().reportError(FF.getLoc(), "invalid number of bytes");
285 return 0;
286 }
287 return Size;
288 }
289
291 return cast<MCNopsFragment>(F).getNumBytes();
292
294 return cast<MCLEBFragment>(F).getContents().size();
295
297 return cast<MCBoundaryAlignFragment>(F).getSize();
298
300 return 4;
301
303 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
304 unsigned Offset = getFragmentOffset(AF);
305 unsigned Size = offsetToAlignment(Offset, AF.getAlignment());
306
307 // Insert extra Nops for code alignment if the target define
308 // shouldInsertExtraNopBytesForCodeAlign target hook.
309 if (AF.getParent()->useCodeAlign() && AF.hasEmitNops() &&
310 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
311 return Size;
312
313 // If we are padding with nops, force the padding to be larger than the
314 // minimum nop size.
315 if (Size > 0 && AF.hasEmitNops()) {
316 while (Size % getBackend().getMinimumNopSize())
317 Size += AF.getAlignment().value();
318 }
319 if (Size > AF.getMaxBytesToEmit())
320 return 0;
321 return Size;
322 }
323
324 case MCFragment::FT_Org: {
325 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
327 if (!OF.getOffset().evaluateAsValue(Value, *this)) {
329 "expected assembly-time absolute expression");
330 return 0;
331 }
332
333 uint64_t FragmentOffset = getFragmentOffset(OF);
334 int64_t TargetLocation = Value.getConstant();
335 if (const MCSymbolRefExpr *A = Value.getSymA()) {
336 uint64_t Val;
337 if (!getSymbolOffset(A->getSymbol(), Val)) {
338 getContext().reportError(OF.getLoc(), "expected absolute expression");
339 return 0;
340 }
341 TargetLocation += Val;
342 }
343 int64_t Size = TargetLocation - FragmentOffset;
344 if (Size < 0 || Size >= 0x40000000) {
346 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
347 "' (at offset '" + Twine(FragmentOffset) + "')");
348 return 0;
349 }
350 return Size;
351 }
352
354 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
356 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
358 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
360 return cast<MCCVDefRangeFragment>(F).getContents().size();
362 return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
364 llvm_unreachable("Should not have been added");
365 }
366
367 llvm_unreachable("invalid fragment kind");
368}
369
370// Compute the amount of padding required before the fragment \p F to
371// obey bundling restrictions, where \p FOffset is the fragment's offset in
372// its section and \p FSize is the fragment's size.
373static uint64_t computeBundlePadding(unsigned BundleSize,
374 const MCEncodedFragment *F,
375 uint64_t FOffset, uint64_t FSize) {
376 uint64_t OffsetInBundle = FOffset & (BundleSize - 1);
377 uint64_t EndOfFragment = OffsetInBundle + FSize;
378
379 // There are two kinds of bundling restrictions:
380 //
381 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
382 // *end* on a bundle boundary.
383 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
384 // would, add padding until the end of the bundle so that the fragment
385 // will start in a new one.
386 if (F->alignToBundleEnd()) {
387 // Three possibilities here:
388 //
389 // A) The fragment just happens to end at a bundle boundary, so we're good.
390 // B) The fragment ends before the current bundle boundary: pad it just
391 // enough to reach the boundary.
392 // C) The fragment ends after the current bundle boundary: pad it until it
393 // reaches the end of the next bundle boundary.
394 //
395 // Note: this code could be made shorter with some modulo trickery, but it's
396 // intentionally kept in its more explicit form for simplicity.
397 if (EndOfFragment == BundleSize)
398 return 0;
399 else if (EndOfFragment < BundleSize)
400 return BundleSize - EndOfFragment;
401 else { // EndOfFragment > BundleSize
402 return 2 * BundleSize - EndOfFragment;
403 }
404 } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
405 return BundleSize - OffsetInBundle;
406 else
407 return 0;
408}
409
411 // If bundling is enabled and this fragment has instructions in it, it has to
412 // obey the bundling restrictions. With padding, we'll have:
413 //
414 //
415 // BundlePadding
416 // |||
417 // -------------------------------------
418 // Prev |##########| F |
419 // -------------------------------------
420 // ^
421 // |
422 // F->Offset
423 //
424 // The fragment's offset will point to after the padding, and its computed
425 // size won't include the padding.
426 //
427 // ".align N" is an example of a directive that introduces multiple
428 // fragments. We could add a special case to handle ".align N" by emitting
429 // within-fragment padding (which would produce less padding when N is less
430 // than the bundle size), but for now we don't.
431 //
432 assert(isa<MCEncodedFragment>(F) &&
433 "Only MCEncodedFragment implementations have instructions");
434 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
435 uint64_t FSize = computeFragmentSize(*EF);
436
437 if (FSize > getBundleAlignSize())
438 report_fatal_error("Fragment can't be larger than a bundle size");
439
440 uint64_t RequiredBundlePadding =
441 computeBundlePadding(getBundleAlignSize(), EF, EF->Offset, FSize);
442 if (RequiredBundlePadding > UINT8_MAX)
443 report_fatal_error("Padding cannot exceed 255 bytes");
444 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
445 EF->Offset += RequiredBundlePadding;
446 if (auto *DF = dyn_cast_or_null<MCDataFragment>(Prev))
447 if (DF->getContents().empty())
448 DF->Offset = EF->Offset;
449}
450
452 if (Sec.hasLayout())
453 return;
454 Sec.setHasLayout(true);
455 MCFragment *Prev = nullptr;
456 uint64_t Offset = 0;
457 for (MCFragment &F : Sec) {
458 F.Offset = Offset;
459 if (isBundlingEnabled() && F.hasInstructions()) {
460 layoutBundle(Prev, &F);
461 Offset = F.Offset;
462 }
464 Prev = &F;
465 }
466}
467
469 ensureValid(*F.getParent());
470 return F.Offset;
471}
472
473// Simple getSymbolOffset helper for the non-variable case.
474static bool getLabelOffset(const MCAssembler &Asm, const MCSymbol &S,
475 bool ReportError, uint64_t &Val) {
476 if (!S.getFragment()) {
477 if (ReportError)
478 report_fatal_error("unable to evaluate offset to undefined symbol '" +
479 S.getName() + "'");
480 return false;
481 }
482 Val = Asm.getFragmentOffset(*S.getFragment()) + S.getOffset();
483 return true;
484}
485
486static bool getSymbolOffsetImpl(const MCAssembler &Asm, const MCSymbol &S,
487 bool ReportError, uint64_t &Val) {
488 if (!S.isVariable())
489 return getLabelOffset(Asm, S, ReportError, Val);
490
491 // If SD is a variable, evaluate it.
494 report_fatal_error("unable to evaluate offset for variable '" +
495 S.getName() + "'");
496
497 uint64_t Offset = Target.getConstant();
498
499 const MCSymbolRefExpr *A = Target.getSymA();
500 if (A) {
501 uint64_t ValA;
502 // FIXME: On most platforms, `Target`'s component symbols are labels from
503 // having been simplified during evaluation, but on Mach-O they can be
504 // variables due to PR19203. This, and the line below for `B` can be
505 // restored to call `getLabelOffset` when PR19203 is fixed.
506 if (!getSymbolOffsetImpl(Asm, A->getSymbol(), ReportError, ValA))
507 return false;
508 Offset += ValA;
509 }
510
511 const MCSymbolRefExpr *B = Target.getSymB();
512 if (B) {
513 uint64_t ValB;
514 if (!getSymbolOffsetImpl(Asm, B->getSymbol(), ReportError, ValB))
515 return false;
516 Offset -= ValB;
517 }
518
519 Val = Offset;
520 return true;
521}
522
524 return getSymbolOffsetImpl(*this, S, false, Val);
525}
526
528 uint64_t Val;
529 getSymbolOffsetImpl(*this, S, true, Val);
530 return Val;
531}
532
533const MCSymbol *MCAssembler::getBaseSymbol(const MCSymbol &Symbol) const {
534 assert(HasLayout);
535 if (!Symbol.isVariable())
536 return &Symbol;
537
538 const MCExpr *Expr = Symbol.getVariableValue();
540 if (!Expr->evaluateAsValue(Value, *this)) {
541 getContext().reportError(Expr->getLoc(),
542 "expression could not be evaluated");
543 return nullptr;
544 }
545
546 const MCSymbolRefExpr *RefB = Value.getSymB();
547 if (RefB) {
549 Expr->getLoc(),
550 Twine("symbol '") + RefB->getSymbol().getName() +
551 "' could not be evaluated in a subtraction expression");
552 return nullptr;
553 }
554
555 const MCSymbolRefExpr *A = Value.getSymA();
556 if (!A)
557 return nullptr;
558
559 const MCSymbol &ASym = A->getSymbol();
560 if (ASym.isCommon()) {
561 getContext().reportError(Expr->getLoc(),
562 "Common symbol '" + ASym.getName() +
563 "' cannot be used in assignment expr");
564 return nullptr;
565 }
566
567 return &ASym;
568}
569
571 assert(HasLayout);
572 // The size is the last fragment's end offset.
573 const MCFragment &F = *Sec.curFragList()->Tail;
575}
576
578 // Virtual sections have no file size.
579 if (Sec.isVirtualSection())
580 return 0;
581 return getSectionAddressSize(Sec);
582}
583
585 bool Changed = !Symbol.isRegistered();
586 if (Changed) {
587 Symbol.setIsRegistered(true);
588 Symbols.push_back(&Symbol);
589 }
590 return Changed;
591}
592
594 const MCEncodedFragment &EF,
595 uint64_t FSize) const {
596 assert(getBackendPtr() && "Expected assembler backend");
597 // Should NOP padding be written out before this fragment?
598 unsigned BundlePadding = EF.getBundlePadding();
599 if (BundlePadding > 0) {
601 "Writing bundle padding with disabled bundling");
602 assert(EF.hasInstructions() &&
603 "Writing bundle padding for a fragment without instructions");
604
605 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
606 const MCSubtargetInfo *STI = EF.getSubtargetInfo();
607 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
608 // If the padding itself crosses a bundle boundary, it must be emitted
609 // in 2 pieces, since even nop instructions must not cross boundaries.
610 // v--------------v <- BundleAlignSize
611 // v---------v <- BundlePadding
612 // ----------------------------
613 // | Prev |####|####| F |
614 // ----------------------------
615 // ^-------------------^ <- TotalLength
616 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
617 if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
618 report_fatal_error("unable to write NOP sequence of " +
619 Twine(DistanceToBoundary) + " bytes");
620 BundlePadding -= DistanceToBoundary;
621 }
622 if (!getBackend().writeNopData(OS, BundlePadding, STI))
623 report_fatal_error("unable to write NOP sequence of " +
624 Twine(BundlePadding) + " bytes");
625 }
626}
627
628/// Write the fragment \p F to the output file.
629static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
630 const MCFragment &F) {
631 // FIXME: Embed in fragments instead?
632 uint64_t FragmentSize = Asm.computeFragmentSize(F);
633
634 llvm::endianness Endian = Asm.getBackend().Endian;
635
636 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
637 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
638
639 // This variable (and its dummy usage) is to participate in the assert at
640 // the end of the function.
641 uint64_t Start = OS.tell();
642 (void) Start;
643
644 ++stats::EmittedFragments;
645
646 switch (F.getKind()) {
648 ++stats::EmittedAlignFragments;
649 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
650 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
651
652 uint64_t Count = FragmentSize / AF.getValueSize();
653
654 // FIXME: This error shouldn't actually occur (the front end should emit
655 // multiple .align directives to enforce the semantics it wants), but is
656 // severe enough that we want to report it. How to handle this?
657 if (Count * AF.getValueSize() != FragmentSize)
658 report_fatal_error("undefined .align directive, value size '" +
659 Twine(AF.getValueSize()) +
660 "' is not a divisor of padding size '" +
661 Twine(FragmentSize) + "'");
662
663 // See if we are aligning with nops, and if so do that first to try to fill
664 // the Count bytes. Then if that did not fill any bytes or there are any
665 // bytes left to fill use the Value and ValueSize to fill the rest.
666 // If we are aligning with nops, ask that target to emit the right data.
667 if (AF.hasEmitNops()) {
668 if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
669 report_fatal_error("unable to write nop sequence of " +
670 Twine(Count) + " bytes");
671 break;
672 }
673
674 // Otherwise, write out in multiples of the value size.
675 for (uint64_t i = 0; i != Count; ++i) {
676 switch (AF.getValueSize()) {
677 default: llvm_unreachable("Invalid size!");
678 case 1: OS << char(AF.getValue()); break;
679 case 2:
680 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
681 break;
682 case 4:
683 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
684 break;
685 case 8:
686 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
687 break;
688 }
689 }
690 break;
691 }
692
694 ++stats::EmittedDataFragments;
695 OS << cast<MCDataFragment>(F).getContents();
696 break;
697
699 ++stats::EmittedRelaxableFragments;
700 OS << cast<MCRelaxableFragment>(F).getContents();
701 break;
702
704 ++stats::EmittedCompactEncodedInstFragments;
705 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
706 break;
707
708 case MCFragment::FT_Fill: {
709 ++stats::EmittedFillFragments;
710 const MCFillFragment &FF = cast<MCFillFragment>(F);
711 uint64_t V = FF.getValue();
712 unsigned VSize = FF.getValueSize();
713 const unsigned MaxChunkSize = 16;
714 char Data[MaxChunkSize];
715 assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
716 // Duplicate V into Data as byte vector to reduce number of
717 // writes done. As such, do endian conversion here.
718 for (unsigned I = 0; I != VSize; ++I) {
719 unsigned index = Endian == llvm::endianness::little ? I : (VSize - I - 1);
720 Data[I] = uint8_t(V >> (index * 8));
721 }
722 for (unsigned I = VSize; I < MaxChunkSize; ++I)
723 Data[I] = Data[I - VSize];
724
725 // Set to largest multiple of VSize in Data.
726 const unsigned NumPerChunk = MaxChunkSize / VSize;
727 // Set ChunkSize to largest multiple of VSize in Data
728 const unsigned ChunkSize = VSize * NumPerChunk;
729
730 // Do copies by chunk.
731 StringRef Ref(Data, ChunkSize);
732 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
733 OS << Ref;
734
735 // do remainder if needed.
736 unsigned TrailingCount = FragmentSize % ChunkSize;
737 if (TrailingCount)
738 OS.write(Data, TrailingCount);
739 break;
740 }
741
742 case MCFragment::FT_Nops: {
743 ++stats::EmittedNopsFragments;
744 const MCNopsFragment &NF = cast<MCNopsFragment>(F);
745
746 int64_t NumBytes = NF.getNumBytes();
747 int64_t ControlledNopLength = NF.getControlledNopLength();
748 int64_t MaximumNopLength =
749 Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
750
751 assert(NumBytes > 0 && "Expected positive NOPs fragment size");
752 assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
753
754 if (ControlledNopLength > MaximumNopLength) {
755 Asm.getContext().reportError(NF.getLoc(),
756 "illegal NOP size " +
757 std::to_string(ControlledNopLength) +
758 ". (expected within [0, " +
759 std::to_string(MaximumNopLength) + "])");
760 // Clamp the NOP length as reportError does not stop the execution
761 // immediately.
762 ControlledNopLength = MaximumNopLength;
763 }
764
765 // Use maximum value if the size of each NOP is not specified
766 if (!ControlledNopLength)
767 ControlledNopLength = MaximumNopLength;
768
769 while (NumBytes) {
770 uint64_t NumBytesToEmit =
771 (uint64_t)std::min(NumBytes, ControlledNopLength);
772 assert(NumBytesToEmit && "try to emit empty NOP instruction");
773 if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
774 NF.getSubtargetInfo())) {
775 report_fatal_error("unable to write nop sequence of the remaining " +
776 Twine(NumBytesToEmit) + " bytes");
777 break;
778 }
779 NumBytes -= NumBytesToEmit;
780 }
781 break;
782 }
783
784 case MCFragment::FT_LEB: {
785 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
786 OS << LF.getContents();
787 break;
788 }
789
791 const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
792 if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
793 report_fatal_error("unable to write nop sequence of " +
794 Twine(FragmentSize) + " bytes");
795 break;
796 }
797
799 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
800 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
801 break;
802 }
803
804 case MCFragment::FT_Org: {
805 ++stats::EmittedOrgFragments;
806 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
807
808 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
809 OS << char(OF.getValue());
810
811 break;
812 }
813
815 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
816 OS << OF.getContents();
817 break;
818 }
820 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
821 OS << CF.getContents();
822 break;
823 }
825 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
826 OS << OF.getContents();
827 break;
828 }
830 const auto &DRF = cast<MCCVDefRangeFragment>(F);
831 OS << DRF.getContents();
832 break;
833 }
835 const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
836 OS << PF.getContents();
837 break;
838 }
840 llvm_unreachable("Should not have been added");
841 }
842
843 assert(OS.tell() - Start == FragmentSize &&
844 "The stream should advance by fragment size");
845}
846
848 const MCSection *Sec) const {
849 assert(getBackendPtr() && "Expected assembler backend");
850
851 // Ignore virtual sections.
852 if (Sec->isVirtualSection()) {
853 assert(getSectionFileSize(*Sec) == 0 && "Invalid size for section!");
854
855 // Check that contents are only things legal inside a virtual section.
856 for (const MCFragment &F : *Sec) {
857 switch (F.getKind()) {
858 default: llvm_unreachable("Invalid fragment in virtual section!");
859 case MCFragment::FT_Data: {
860 // Check that we aren't trying to write a non-zero contents (or fixups)
861 // into a virtual section. This is to support clients which use standard
862 // directives to fill the contents of virtual sections.
863 const MCDataFragment &DF = cast<MCDataFragment>(F);
864 if (DF.fixup_begin() != DF.fixup_end())
865 getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
866 " section '" + Sec->getName() +
867 "' cannot have fixups");
868 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
869 if (DF.getContents()[i]) {
871 Sec->getVirtualSectionKind() +
872 " section '" + Sec->getName() +
873 "' cannot have non-zero initializers");
874 break;
875 }
876 break;
877 }
879 // Check that we aren't trying to write a non-zero value into a virtual
880 // section.
881 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
882 cast<MCAlignFragment>(F).getValue() == 0) &&
883 "Invalid align in virtual section!");
884 break;
886 assert((cast<MCFillFragment>(F).getValue() == 0) &&
887 "Invalid fill in virtual section!");
888 break;
890 break;
891 }
892 }
893
894 return;
895 }
896
897 uint64_t Start = OS.tell();
898 (void)Start;
899
900 for (const MCFragment &F : *Sec)
901 writeFragment(OS, *this, F);
902
903 assert(getContext().hadError() ||
904 OS.tell() - Start == getSectionAddressSize(*Sec));
905}
906
907std::tuple<MCValue, uint64_t, bool>
908MCAssembler::handleFixup(MCFragment &F, const MCFixup &Fixup,
909 const MCSubtargetInfo *STI) {
910 // Evaluate the fixup.
912 uint64_t FixedValue;
913 bool WasForced;
914 bool IsResolved =
915 evaluateFixup(Fixup, &F, Target, STI, FixedValue, WasForced);
916 if (!IsResolved) {
917 // The fixup was unresolved, we need a relocation. Inform the object
918 // writer of the relocation, and give it an opportunity to adjust the
919 // fixup value if need be.
920 getWriter().recordRelocation(*this, &F, Fixup, Target, FixedValue);
921 }
922 return std::make_tuple(Target, FixedValue, IsResolved);
923}
924
926 assert(getBackendPtr() && "Expected assembler backend");
927 DEBUG_WITH_TYPE("mc-dump", {
928 errs() << "assembler backend - pre-layout\n--\n";
929 dump(); });
930
931 // Assign section ordinals.
932 unsigned SectionIndex = 0;
933 for (MCSection &Sec : *this) {
934 Sec.setOrdinal(SectionIndex++);
935
936 // Chain together fragments from all subsections.
937 if (Sec.Subsections.size() > 1) {
938 MCDummyFragment Dummy;
939 MCFragment *Tail = &Dummy;
940 for (auto &[_, List] : Sec.Subsections) {
941 assert(List.Head);
942 Tail->Next = List.Head;
943 Tail = List.Tail;
944 }
945 Sec.Subsections.clear();
946 Sec.Subsections.push_back({0u, {Dummy.getNext(), Tail}});
947 Sec.CurFragList = &Sec.Subsections[0].second;
948
949 unsigned FragmentIndex = 0;
950 for (MCFragment &Frag : Sec)
951 Frag.setLayoutOrder(FragmentIndex++);
952 }
953 }
954
955 // Layout until everything fits.
956 this->HasLayout = true;
957 while (layoutOnce()) {
958 if (getContext().hadError())
959 return;
960 // Size of fragments in one section can depend on the size of fragments in
961 // another. If any fragment has changed size, we have to re-layout (and
962 // as a result possibly further relax) all.
963 for (MCSection &Sec : *this)
964 Sec.setHasLayout(false);
965 }
966
967 DEBUG_WITH_TYPE("mc-dump", {
968 errs() << "assembler backend - post-relaxation\n--\n";
969 dump(); });
970
971 // Finalize the layout, including fragment lowering.
972 getBackend().finishLayout(*this);
973
974 DEBUG_WITH_TYPE("mc-dump", {
975 errs() << "assembler backend - final-layout\n--\n";
976 dump(); });
977
978 // Allow the object writer a chance to perform post-layout binding (for
979 // example, to set the index fields in the symbol data).
981
982 // Evaluate and apply the fixups, generating relocation entries as necessary.
983 for (MCSection &Sec : *this) {
984 for (MCFragment &Frag : Sec) {
985 ArrayRef<MCFixup> Fixups;
986 MutableArrayRef<char> Contents;
987 const MCSubtargetInfo *STI = nullptr;
988
989 // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
990 switch (Frag.getKind()) {
991 default:
992 continue;
994 MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
995 // Insert fixup type for code alignment if the target define
996 // shouldInsertFixupForCodeAlign target hook.
997 if (Sec.useCodeAlign() && AF.hasEmitNops())
999 continue;
1000 }
1001 case MCFragment::FT_Data: {
1002 MCDataFragment &DF = cast<MCDataFragment>(Frag);
1003 Fixups = DF.getFixups();
1004 Contents = DF.getContents();
1005 STI = DF.getSubtargetInfo();
1006 assert(!DF.hasInstructions() || STI != nullptr);
1007 break;
1008 }
1010 MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
1011 Fixups = RF.getFixups();
1012 Contents = RF.getContents();
1013 STI = RF.getSubtargetInfo();
1014 assert(!RF.hasInstructions() || STI != nullptr);
1015 break;
1016 }
1018 MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
1019 Fixups = CF.getFixups();
1020 Contents = CF.getContents();
1021 break;
1022 }
1023 case MCFragment::FT_Dwarf: {
1024 MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
1025 Fixups = DF.getFixups();
1026 Contents = DF.getContents();
1027 break;
1028 }
1030 MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
1031 Fixups = DF.getFixups();
1032 Contents = DF.getContents();
1033 break;
1034 }
1035 case MCFragment::FT_LEB: {
1036 auto &LF = cast<MCLEBFragment>(Frag);
1037 Fixups = LF.getFixups();
1038 Contents = LF.getContents();
1039 break;
1040 }
1042 MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
1043 Fixups = PF.getFixups();
1044 Contents = PF.getContents();
1045 break;
1046 }
1047 }
1048 for (const MCFixup &Fixup : Fixups) {
1049 uint64_t FixedValue;
1050 bool IsResolved;
1052 std::tie(Target, FixedValue, IsResolved) =
1053 handleFixup(Frag, Fixup, STI);
1054 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
1055 IsResolved, STI);
1056 }
1057 }
1058 }
1059}
1060
1062 layout();
1063
1064 // Write the object file.
1065 stats::ObjectBytes += getWriter().writeObject(*this);
1066
1067 HasLayout = false;
1068}
1069
1070bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
1071 const MCRelaxableFragment *DF) const {
1072 assert(getBackendPtr() && "Expected assembler backend");
1075 bool WasForced;
1076 bool Resolved = evaluateFixup(Fixup, DF, Target, DF->getSubtargetInfo(),
1077 Value, WasForced);
1078 if (Target.getSymA() &&
1079 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
1080 Fixup.getKind() == FK_Data_1)
1081 return false;
1082 return getBackend().fixupNeedsRelaxationAdvanced(*this, Fixup, Resolved,
1083 Value, DF, WasForced);
1084}
1085
1086bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F) const {
1087 assert(getBackendPtr() && "Expected assembler backend");
1088 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
1089 // are intentionally pushing out inst fragments, or because we relaxed a
1090 // previous instruction to one that doesn't need relaxation.
1091 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
1092 return false;
1093
1094 for (const MCFixup &Fixup : F->getFixups())
1095 if (fixupNeedsRelaxation(Fixup, F))
1096 return true;
1097
1098 return false;
1099}
1100
1101bool MCAssembler::relaxInstruction(MCRelaxableFragment &F) {
1103 "Expected CodeEmitter defined for relaxInstruction");
1104 if (!fragmentNeedsRelaxation(&F))
1105 return false;
1106
1107 ++stats::RelaxedInstructions;
1108
1109 // FIXME-PERF: We could immediately lower out instructions if we can tell
1110 // they are fully resolved, to avoid retesting on later passes.
1111
1112 // Relax the fragment.
1113
1114 MCInst Relaxed = F.getInst();
1115 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
1116
1117 // Encode the new instruction.
1118 F.setInst(Relaxed);
1119 F.getFixups().clear();
1120 F.getContents().clear();
1121 getEmitter().encodeInstruction(Relaxed, F.getContents(), F.getFixups(),
1122 *F.getSubtargetInfo());
1123 return true;
1124}
1125
1126bool MCAssembler::relaxLEB(MCLEBFragment &LF) {
1127 const unsigned OldSize = static_cast<unsigned>(LF.getContents().size());
1128 unsigned PadTo = OldSize;
1129 int64_t Value;
1131 LF.getFixups().clear();
1132 // Use evaluateKnownAbsolute for Mach-O as a hack: .subsections_via_symbols
1133 // requires that .uleb128 A-B is foldable where A and B reside in different
1134 // fragments. This is used by __gcc_except_table.
1135 bool Abs = getSubsectionsViaSymbols()
1136 ? LF.getValue().evaluateKnownAbsolute(Value, *this)
1137 : LF.getValue().evaluateAsAbsolute(Value, *this);
1138 if (!Abs) {
1139 bool Relaxed, UseZeroPad;
1140 std::tie(Relaxed, UseZeroPad) = getBackend().relaxLEB128(*this, LF, Value);
1141 if (!Relaxed) {
1143 Twine(LF.isSigned() ? ".s" : ".u") +
1144 "leb128 expression is not absolute");
1145 LF.setValue(MCConstantExpr::create(0, Context));
1146 }
1147 uint8_t Tmp[10]; // maximum size: ceil(64/7)
1148 PadTo = std::max(PadTo, encodeULEB128(uint64_t(Value), Tmp));
1149 if (UseZeroPad)
1150 Value = 0;
1151 }
1152 Data.clear();
1154 // The compiler can generate EH table assembly that is impossible to assemble
1155 // without either adding padding to an LEB fragment or adding extra padding
1156 // to a later alignment fragment. To accommodate such tables, relaxation can
1157 // only increase an LEB fragment size here, not decrease it. See PR35809.
1158 if (LF.isSigned())
1159 encodeSLEB128(Value, OSE, PadTo);
1160 else
1161 encodeULEB128(Value, OSE, PadTo);
1162 return OldSize != LF.getContents().size();
1163}
1164
1165/// Check if the branch crosses the boundary.
1166///
1167/// \param StartAddr start address of the fused/unfused branch.
1168/// \param Size size of the fused/unfused branch.
1169/// \param BoundaryAlignment alignment requirement of the branch.
1170/// \returns true if the branch cross the boundary.
1172 Align BoundaryAlignment) {
1173 uint64_t EndAddr = StartAddr + Size;
1174 return (StartAddr >> Log2(BoundaryAlignment)) !=
1175 ((EndAddr - 1) >> Log2(BoundaryAlignment));
1176}
1177
1178/// Check if the branch is against the boundary.
1179///
1180/// \param StartAddr start address of the fused/unfused branch.
1181/// \param Size size of the fused/unfused branch.
1182/// \param BoundaryAlignment alignment requirement of the branch.
1183/// \returns true if the branch is against the boundary.
1185 Align BoundaryAlignment) {
1186 uint64_t EndAddr = StartAddr + Size;
1187 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1188}
1189
1190/// Check if the branch needs padding.
1191///
1192/// \param StartAddr start address of the fused/unfused branch.
1193/// \param Size size of the fused/unfused branch.
1194/// \param BoundaryAlignment alignment requirement of the branch.
1195/// \returns true if the branch needs padding.
1196static bool needPadding(uint64_t StartAddr, uint64_t Size,
1197 Align BoundaryAlignment) {
1198 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1199 isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1200}
1201
1202bool MCAssembler::relaxBoundaryAlign(MCBoundaryAlignFragment &BF) {
1203 // BoundaryAlignFragment that doesn't need to align any fragment should not be
1204 // relaxed.
1205 if (!BF.getLastFragment())
1206 return false;
1207
1208 uint64_t AlignedOffset = getFragmentOffset(BF);
1209 uint64_t AlignedSize = 0;
1210 for (const MCFragment *F = BF.getNext();; F = F->getNext()) {
1211 AlignedSize += computeFragmentSize(*F);
1212 if (F == BF.getLastFragment())
1213 break;
1214 }
1215
1216 Align BoundaryAlignment = BF.getAlignment();
1217 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1218 ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1219 : 0U;
1220 if (NewSize == BF.getSize())
1221 return false;
1222 BF.setSize(NewSize);
1223 return true;
1224}
1225
1226bool MCAssembler::relaxDwarfLineAddr(MCDwarfLineAddrFragment &DF) {
1227 bool WasRelaxed;
1228 if (getBackend().relaxDwarfLineAddr(*this, DF, WasRelaxed))
1229 return WasRelaxed;
1230
1231 MCContext &Context = getContext();
1232 uint64_t OldSize = DF.getContents().size();
1233 int64_t AddrDelta;
1234 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, *this);
1235 assert(Abs && "We created a line delta with an invalid expression");
1236 (void)Abs;
1237 int64_t LineDelta;
1238 LineDelta = DF.getLineDelta();
1239 SmallVectorImpl<char> &Data = DF.getContents();
1240 Data.clear();
1241 DF.getFixups().clear();
1242
1244 AddrDelta, Data);
1245 return OldSize != Data.size();
1246}
1247
1248bool MCAssembler::relaxDwarfCallFrameFragment(MCDwarfCallFrameFragment &DF) {
1249 bool WasRelaxed;
1250 if (getBackend().relaxDwarfCFA(*this, DF, WasRelaxed))
1251 return WasRelaxed;
1252
1253 MCContext &Context = getContext();
1254 int64_t Value;
1255 bool Abs = DF.getAddrDelta().evaluateAsAbsolute(Value, *this);
1256 if (!Abs) {
1257 getContext().reportError(DF.getAddrDelta().getLoc(),
1258 "invalid CFI advance_loc expression");
1259 DF.setAddrDelta(MCConstantExpr::create(0, Context));
1260 return false;
1261 }
1262
1263 SmallVectorImpl<char> &Data = DF.getContents();
1264 uint64_t OldSize = Data.size();
1265 Data.clear();
1266 DF.getFixups().clear();
1267
1269 return OldSize != Data.size();
1270}
1271
1272bool MCAssembler::relaxCVInlineLineTable(MCCVInlineLineTableFragment &F) {
1273 unsigned OldSize = F.getContents().size();
1275 return OldSize != F.getContents().size();
1276}
1277
1278bool MCAssembler::relaxCVDefRange(MCCVDefRangeFragment &F) {
1279 unsigned OldSize = F.getContents().size();
1281 return OldSize != F.getContents().size();
1282}
1283
1284bool MCAssembler::relaxPseudoProbeAddr(MCPseudoProbeAddrFragment &PF) {
1285 uint64_t OldSize = PF.getContents().size();
1286 int64_t AddrDelta;
1287 bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, *this);
1288 assert(Abs && "We created a pseudo probe with an invalid expression");
1289 (void)Abs;
1291 Data.clear();
1293 PF.getFixups().clear();
1294
1295 // AddrDelta is a signed integer
1296 encodeSLEB128(AddrDelta, OSE, OldSize);
1297 return OldSize != Data.size();
1298}
1299
1300bool MCAssembler::relaxFragment(MCFragment &F) {
1301 switch(F.getKind()) {
1302 default:
1303 return false;
1305 assert(!getRelaxAll() &&
1306 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1307 return relaxInstruction(cast<MCRelaxableFragment>(F));
1309 return relaxDwarfLineAddr(cast<MCDwarfLineAddrFragment>(F));
1311 return relaxDwarfCallFrameFragment(cast<MCDwarfCallFrameFragment>(F));
1312 case MCFragment::FT_LEB:
1313 return relaxLEB(cast<MCLEBFragment>(F));
1315 return relaxBoundaryAlign(cast<MCBoundaryAlignFragment>(F));
1317 return relaxCVInlineLineTable(cast<MCCVInlineLineTableFragment>(F));
1319 return relaxCVDefRange(cast<MCCVDefRangeFragment>(F));
1321 return relaxPseudoProbeAddr(cast<MCPseudoProbeAddrFragment>(F));
1322 }
1323}
1324
1325bool MCAssembler::layoutOnce() {
1326 ++stats::RelaxationSteps;
1327
1328 bool Changed = false;
1329 for (MCSection &Sec : *this)
1330 for (MCFragment &Frag : Sec)
1331 if (relaxFragment(Frag))
1332 Changed = true;
1333 return Changed;
1334}
1335
1336#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1338 raw_ostream &OS = errs();
1339
1340 OS << "<MCAssembler\n";
1341 OS << " Sections:[\n ";
1342 bool First = true;
1343 for (const MCSection &Sec : *this) {
1344 if (First)
1345 First = false;
1346 else
1347 OS << ",\n ";
1348 Sec.dump();
1349 }
1350 OS << "],\n";
1351 OS << " Symbols:[";
1352
1353 First = true;
1354 for (const MCSymbol &Sym : symbols()) {
1355 if (First)
1356 First = false;
1357 else
1358 OS << ",\n ";
1359 OS << "(";
1360 Sym.dump();
1361 OS << ", Index:" << Sym.getIndex() << ", ";
1362 OS << ")";
1363 }
1364 OS << "]>\n";
1365}
1366#endif
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:537
dxil DXContainer Global Emitter
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define _
static uint64_t computeBundlePadding(unsigned BundleSize, const MCEncodedFragment *F, uint64_t FOffset, uint64_t FSize)
static bool getSymbolOffsetImpl(const MCAssembler &Asm, const MCSymbol &S, bool ReportError, uint64_t &Val)
static bool needPadding(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch needs padding.
static void writeFragment(raw_ostream &OS, const MCAssembler &Asm, const MCFragment &F)
Write the fragment F to the output file.
static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch crosses the boundary.
static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch is against the boundary.
static bool getLabelOffset(const MCAssembler &Asm, const MCSymbol &S, bool ReportError, uint64_t &Val)
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
PowerPC TLS Dynamic Call Fixup
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
endianness Endian
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
void encodeInlineLineTable(const MCAssembler &Asm, MCCVInlineLineTableFragment &F)
Encodes the binary annotations once we have a layout.
Definition: MCCodeView.cpp:484
void encodeDefRange(const MCAssembler &Asm, MCCVDefRangeFragment &F)
Definition: MCCodeView.cpp:621
int64_t getValue() const
Definition: MCFragment.h:315
Align getAlignment() const
Definition: MCFragment.h:313
unsigned getMaxBytesToEmit() const
Definition: MCFragment.h:319
bool hasEmitNops() const
Definition: MCFragment.h:321
unsigned getValueSize() const
Definition: MCFragment.h:317
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:327
virtual void relaxInstruction(MCInst &Inst, const MCSubtargetInfo &STI) const
Relax the instruction in the given fragment to the next wider instruction.
Definition: MCAsmBackend.h:177
virtual bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, MCAlignFragment &AF)
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
Definition: MCAsmBackend.h:111
virtual bool fixupNeedsRelaxationAdvanced(const MCAssembler &Asm, const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const bool WasForced) const
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
virtual void finishLayout(MCAssembler const &Asm) const
Give backend an opportunity to finish layout after relaxation.
Definition: MCAsmBackend.h:221
virtual bool evaluateTargetFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, const MCSubtargetInfo *STI, uint64_t &Value, bool &WasForced)
Definition: MCAsmBackend.h:116
virtual void reset()
lifetime management
Definition: MCAsmBackend.h:65
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
virtual std::pair< bool, bool > relaxLEB128(const MCAssembler &Asm, MCLEBFragment &LF, int64_t &Value) const
Definition: MCAsmBackend.h:195
virtual void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target, MutableArrayRef< char > Data, uint64_t Value, bool IsResolved, const MCSubtargetInfo *STI) const =0
Apply the Value for given Fixup into the provided data fragment, at the offset specified by the fixup...
MCContext & getContext() const
Definition: MCAssembler.h:277
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
void ensureValid(MCSection &Sec) const
uint64_t getSectionAddressSize(const MCSection &Sec) const
void Finish()
Finish - Do final processing and write the object to the output stream.
unsigned getBundleAlignSize() const
Definition: MCAssembler.h:319
bool isBundlingEnabled() const
Definition: MCAssembler.h:317
bool getSubsectionsViaSymbols() const
Definition: MCAssembler.h:303
void writeSectionData(raw_ostream &OS, const MCSection *Section) const
Emit the section contents to OS.
void dump() const
MCObjectWriter * getWriterPtr() const
Definition: MCAssembler.h:283
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:289
MCCodeEmitter * getEmitterPtr() const
Definition: MCAssembler.h:281
uint64_t getFragmentOffset(const MCFragment &F) const
void layoutBundle(MCFragment *Prev, MCFragment *F) const
bool getRelaxAll() const
Definition: MCAssembler.h:314
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:287
MCAssembler(MCContext &Context, std::unique_ptr< MCAsmBackend > Backend, std::unique_ptr< MCCodeEmitter > Emitter, std::unique_ptr< MCObjectWriter > Writer)
Construct a new assembler instance.
Definition: MCAssembler.cpp:82
bool isThumbFunc(const MCSymbol *Func) const
Check whether a given symbol has been flagged with .thumb_func.
MCAsmBackend & getBackend() const
Definition: MCAssembler.h:285
bool registerSection(MCSection &Section)
uint64_t computeFragmentSize(const MCFragment &F) const
Compute the effective fragment size.
const MCSymbol * getBaseSymbol(const MCSymbol &Symbol) const
MCAsmBackend * getBackendPtr() const
Definition: MCAssembler.h:279
iterator_range< pointee_iterator< typename SmallVector< const MCSymbol *, 0 >::const_iterator > > symbols() const
Definition: MCAssembler.h:332
MCLOHContainer & getLOHContainer()
Definition: MCAssembler.h:347
uint64_t getSectionFileSize(const MCSection &Sec) const
void reset()
Reuse an assembler instance.
Definition: MCAssembler.cpp:94
bool registerSymbol(const MCSymbol &Symbol)
MCDwarfLineTableParams getDWARFLinetableParams() const
Definition: MCAssembler.h:291
void writeFragmentPadding(raw_ostream &OS, const MCEncodedFragment &F, uint64_t FSize) const
Write the necessary bundle padding to OS.
Represents required padding such that a particular other set of fragments does not cross a particular...
Definition: MCFragment.h:563
uint64_t getSize() const
Definition: MCFragment.h:580
void setSize(uint64_t Value)
Definition: MCFragment.h:581
const MCFragment * getLastFragment() const
Definition: MCFragment.h:586
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:592
Fragment representing the .cv_def_range directive.
Definition: MCFragment.h:533
Fragment representing the binary annotations produced by the .cv_inline_linetable directive.
Definition: MCFragment.h:501
virtual void encodeInstruction(const MCInst &Inst, SmallVectorImpl< char > &CB, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
Encode the given Inst to bytes and append to CB.
virtual void reset()
Lifetime management.
Definition: MCCodeEmitter.h:31
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:193
Context object for machine code objects.
Definition: MCContext.h:83
CodeViewContext & getCVContext()
Definition: MCContext.cpp:1014
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1069
Fragment for data and encoded instructions.
Definition: MCFragment.h:231
static void encodeAdvanceLoc(MCContext &Context, uint64_t AddrDelta, SmallVectorImpl< char > &OS)
Definition: MCDwarf.cpp:1907
static void encode(MCContext &Context, MCDwarfLineTableParams Params, int64_t LineDelta, uint64_t AddrDelta, SmallVectorImpl< char > &OS)
Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
Definition: MCDwarf.cpp:689
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:188
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:212
Interface implemented by fragments that contain encoded instructions and/or data.
Definition: MCFragment.h:118
const MCSubtargetInfo * getSubtargetInfo() const
Retrieve the MCSubTargetInfo in effect when the instruction was encoded.
Definition: MCFragment.h:165
void setBundlePadding(uint8_t N)
Set the padding size for this fragment.
Definition: MCFragment.h:161
uint8_t getBundlePadding() const
Get the padding size that must be inserted before this fragment.
Definition: MCFragment.h:157
bool alignToBundleEnd() const
Should this fragment be placed at the end of an aligned bundle?
Definition: MCFragment.h:149
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
bool evaluateAsValue(MCValue &Res, const MCAssembler &Asm) const
Try to evaluate the expression to the form (a - b + constant) where neither a nor b are variables.
Definition: MCExpr.cpp:794
bool evaluateKnownAbsolute(int64_t &Res, const MCAssembler &Asm) const
Aggressive variant of evaluateAsRelocatable when relocations are unavailable (e.g.
Definition: MCExpr.cpp:565
bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:789
SMLoc getLoc() const
Definition: MCExpr.h:79
uint8_t getValueSize() const
Definition: MCFragment.h:351
uint64_t getValue() const
Definition: MCFragment.h:350
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
MCSection * getParent() const
Definition: MCFragment.h:93
MCFragment * getNext() const
Definition: MCFragment.h:89
bool hasInstructions() const
Does this fragment have instructions emitted into it? By default this is false, but specific fragment...
Definition: MCFragment.h:103
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
bool isSigned() const
Definition: MCFragment.h:433
const MCExpr & getValue() const
Definition: MCFragment.h:430
void setValue(const MCExpr *Expr)
Definition: MCFragment.h:431
int64_t getControlledNopLength() const
Definition: MCFragment.h:380
int64_t getNumBytes() const
Definition: MCFragment.h:379
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:384
SMLoc getLoc() const
Definition: MCFragment.h:382
virtual void executePostLayoutBinding(MCAssembler &Asm)
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
virtual void reset()
lifetime management
virtual uint64_t writeObject(MCAssembler &Asm)=0
Write the object file and returns the number of bytes written.
virtual void recordRelocation(MCAssembler &Asm, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue)=0
Record a relocation entry.
SMLoc getLoc() const
Definition: MCFragment.h:409
uint8_t getValue() const
Definition: MCFragment.h:407
const MCExpr & getOffset() const
Definition: MCFragment.h:405
const MCExpr & getAddrDelta() const
Definition: MCFragment.h:609
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:261
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
void dump() const
Definition: MCSection.cpp:72
bool hasLayout() const
Definition: MCSection.h:172
void setOrdinal(unsigned Value)
Definition: MCSection.h:156
bool isVirtualSection() const
Check whether this section is "virtual", that is has no actual object file contents.
Definition: MCSection.h:198
virtual bool useCodeAlign() const =0
Return true if a .align directive should use "optimized nops" to fill instead of 0s.
FragList * curFragList() const
Definition: MCSection.h:181
void setHasLayout(bool Value)
Definition: MCSection.h:173
Generic base class for all target subtargets.
Represents a symbol table index fragment.
Definition: MCFragment.h:484
const MCSymbol * getSymbol()
Definition: MCFragment.h:491
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:188
const MCSymbol & getSymbol() const
Definition: MCExpr.h:406
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
const MCExpr * getVariableValue(bool SetUsed=true) const
getVariableValue - Get the value for variable symbols.
Definition: MCSymbol.h:305
bool isCommon() const
Is this a 'common' symbol.
Definition: MCSymbol.h:387
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:300
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:259
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:316
uint64_t getOffset() const
Definition: MCSymbol.h:327
MCFragment * getFragment(bool SetUsed=true) const
Definition: MCSymbol.h:397
This represents an "assembler immediate".
Definition: MCValue.h:36
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
Represents a location in source code.
Definition: SMLoc.h:23
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
LLVM Value Representation.
Definition: Value.h:74
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition: CallingConv.h:76
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
@ FK_Data_1
A one-byte fixup.
Definition: MCFixup.h:23
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: Alignment.h:197
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
endianness
Definition: bit.h:70
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
@ FKF_IsTarget
Should this fixup be evaluated in a target dependent manner?
@ FKF_IsAlignedDownTo32Bits
Should this fixup kind force a 4-byte aligned effective PC value?
@ FKF_Constant
This fixup kind should be resolved if defined.
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
unsigned Flags
Flags describing additional information on this fixup kind.