LLVM 18.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"
18#include "llvm/MC/MCAsmLayout.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"
26#include "llvm/MC/MCFragment.h"
27#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCSection.h"
30#include "llvm/MC/MCSymbol.h"
31#include "llvm/MC/MCValue.h"
34#include "llvm/Support/Debug.h"
37#include "llvm/Support/LEB128.h"
39#include <cassert>
40#include <cstdint>
41#include <tuple>
42#include <utility>
43
44using namespace llvm;
45
46namespace llvm {
47class MCSubtargetInfo;
48}
49
50#define DEBUG_TYPE "assembler"
51
52namespace {
53namespace stats {
54
55STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
56STATISTIC(EmittedRelaxableFragments,
57 "Number of emitted assembler fragments - relaxable");
58STATISTIC(EmittedDataFragments,
59 "Number of emitted assembler fragments - data");
60STATISTIC(EmittedCompactEncodedInstFragments,
61 "Number of emitted assembler fragments - compact encoded inst");
62STATISTIC(EmittedAlignFragments,
63 "Number of emitted assembler fragments - align");
64STATISTIC(EmittedFillFragments,
65 "Number of emitted assembler fragments - fill");
66STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
67STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
68STATISTIC(evaluateFixup, "Number of evaluated fixups");
69STATISTIC(FragmentLayouts, "Number of fragment layouts");
70STATISTIC(ObjectBytes, "Number of emitted object file bytes");
71STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
72STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
73
74} // end namespace stats
75} // end anonymous namespace
76
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.
81
82/* *** */
83
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;
94}
95
97
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();
116
117 // reset objects owned by us
118 if (getBackendPtr())
119 getBackendPtr()->reset();
120 if (getEmitterPtr())
121 getEmitterPtr()->reset();
122 if (getWriterPtr())
123 getWriterPtr()->reset();
125}
126
128 if (Section.isRegistered())
129 return false;
130 Sections.push_back(&Section);
131 Section.setIsRegistered(true);
132 return true;
133}
134
135bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
136 if (ThumbFuncs.count(Symbol))
137 return true;
138
139 if (!Symbol->isVariable())
140 return false;
141
142 const MCExpr *Expr = Symbol->getVariableValue();
143
144 MCValue V;
145 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
146 return false;
147
148 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
149 return false;
150
151 const MCSymbolRefExpr *Ref = V.getSymA();
152 if (!Ref)
153 return false;
154
155 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
156 return false;
157
158 const MCSymbol &Sym = Ref->getSymbol();
159 if (!isThumbFunc(&Sym))
160 return false;
161
162 ThumbFuncs.insert(Symbol); // Cache it.
163 return true;
164}
165
167 // Non-temporary labels should always be visible to the linker.
168 if (!Symbol.isTemporary())
169 return true;
170
171 if (Symbol.isUsedInReloc())
172 return true;
173
174 return false;
175}
176
177const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
178 // Linker visible symbols define atoms.
180 return &S;
181
182 // Absolute and undefined symbols have no defining atom.
183 if (!S.isInSection())
184 return nullptr;
185
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;
191
192 // Otherwise, return the atom for the containing fragment.
193 return S.getFragment()->getAtom();
194}
195
196bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
197 const MCFixup &Fixup, const MCFragment *DF,
199 bool &WasForced) const {
200 ++stats::evaluateFixup;
201
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.
205
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;
215 }
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;
221 }
222 }
223
224 assert(getBackendPtr() && "Expected assembler backend");
225 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
227
228 if (IsTarget)
229 return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
230 Value, WasForced);
231
232 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
233 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
235
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);
251 }
252 }
253 } else {
254 IsResolved = Target.isAbsolute();
255 }
256
257 Value = Target.getConstant();
258
259 if (const MCSymbolRefExpr *A = Target.getSymA()) {
260 const MCSymbol &Sym = A->getSymbol();
261 if (Sym.isDefined())
262 Value += Layout.getSymbolOffset(Sym);
263 }
264 if (const MCSymbolRefExpr *B = Target.getSymB()) {
265 const MCSymbol &Sym = B->getSymbol();
266 if (Sym.isDefined())
267 Value -= Layout.getSymbolOffset(Sym);
268 }
269
270 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
272 assert((ShouldAlignPC ? IsPCRel : true) &&
273 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
274
275 if (IsPCRel) {
276 uint64_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
277
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;
282 }
283
284 // Let the backend force a relocation if needed.
285 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
286 IsResolved = false;
287 WasForced = true;
288 }
289
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;
296
297 return IsResolved;
298}
299
301 const MCFragment &F) const {
302 assert(getBackendPtr() && "Requires assembler backend");
303 switch (F.getKind()) {
305 return cast<MCDataFragment>(F).getContents().size();
307 return cast<MCRelaxableFragment>(F).getContents().size();
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;
317 }
318 int64_t Size = NumValues * FF.getValueSize();
319 if (Size < 0) {
320 getContext().reportError(FF.getLoc(), "invalid number of bytes");
321 return 0;
322 }
323 return Size;
324 }
325
327 return cast<MCNopsFragment>(F).getNumBytes();
328
330 return cast<MCLEBFragment>(F).getContents().size();
331
333 return cast<MCBoundaryAlignFragment>(F).getSize();
334
336 return 4;
337
339 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
340 unsigned Offset = Layout.getFragmentOffset(&AF);
341 unsigned Size = offsetToAlignment(Offset, AF.getAlignment());
342
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;
348
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();
354 }
355 if (Size > AF.getMaxBytesToEmit())
356 return 0;
357 return Size;
358 }
359
360 case MCFragment::FT_Org: {
361 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
363 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
365 "expected assembly-time absolute expression");
366 return 0;
367 }
368
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;
376 }
377 TargetLocation += Val;
378 }
379 int64_t Size = TargetLocation - FragmentOffset;
380 if (Size < 0 || Size >= 0x40000000) {
382 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
383 "' (at offset '" + Twine(FragmentOffset) + "')");
384 return 0;
385 }
386 return Size;
387 }
388
390 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
392 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
394 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
396 return cast<MCCVDefRangeFragment>(F).getContents().size();
398 return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
400 llvm_unreachable("Should not have been added");
401 }
402
403 llvm_unreachable("invalid fragment kind");
404}
405
407 MCFragment *Prev = F->getPrevNode();
408
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!");
415
416 assert(!F->IsBeingLaidOut && "Already being laid out!");
417 F->IsBeingLaidOut = true;
418
419 ++stats::FragmentLayouts;
420
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;
428
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:
431 //
432 //
433 // BundlePadding
434 // |||
435 // -------------------------------------
436 // Prev |##########| F |
437 // -------------------------------------
438 // ^
439 // |
440 // F->Offset
441 //
442 // The fragment's offset will point to after the padding, and its computed
443 // size won't include the padding.
444 //
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.
450 //
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.
455 //
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);
461
462 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
463 report_fatal_error("Fragment can't be larger than a bundle size");
464
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;
471 }
472}
473
475 bool Changed = !Symbol.isRegistered();
476 if (Changed) {
477 Symbol.setIsRegistered(true);
478 Symbols.push_back(&Symbol);
479 }
480 return Changed;
481}
482
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) {
491 "Writing bundle padding with disabled bundling");
492 assert(EF.hasInstructions() &&
493 "Writing bundle padding for a fragment without instructions");
494
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;
511 }
512 if (!getBackend().writeNopData(OS, BundlePadding, STI))
513 report_fatal_error("unable to write NOP sequence of " +
514 Twine(BundlePadding) + " bytes");
515 }
516}
517
518/// Write the fragment \p F to the output file.
519static 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);
523
524 llvm::endianness Endian = Asm.getBackend().Endian;
525
526 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
527 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
528
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;
533
534 ++stats::EmittedFragments;
535
536 switch (F.getKind()) {
538 ++stats::EmittedAlignFragments;
539 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
540 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
541
542 uint64_t Count = FragmentSize / AF.getValueSize();
543
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) + "'");
552
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;
562 }
563
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;
578 }
579 }
580 break;
581 }
582
584 ++stats::EmittedDataFragments;
585 OS << cast<MCDataFragment>(F).getContents();
586 break;
587
589 ++stats::EmittedRelaxableFragments;
590 OS << cast<MCRelaxableFragment>(F).getContents();
591 break;
592
594 ++stats::EmittedCompactEncodedInstFragments;
595 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
596 break;
597
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));
611 }
612 for (unsigned I = VSize; I < MaxChunkSize; ++I)
613 Data[I] = Data[I - VSize];
614
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;
619
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;
624
625 // do remainder if needed.
626 unsigned TrailingCount = FragmentSize % ChunkSize;
627 if (TrailingCount)
628 OS.write(Data, TrailingCount);
629 break;
630 }
631
632 case MCFragment::FT_Nops: {
633 ++stats::EmittedNopsFragments;
634 const MCNopsFragment &NF = cast<MCNopsFragment>(F);
635
636 int64_t NumBytes = NF.getNumBytes();
637 int64_t ControlledNopLength = NF.getControlledNopLength();
638 int64_t MaximumNopLength =
639 Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
640
641 assert(NumBytes > 0 && "Expected positive NOPs fragment size");
642 assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
643
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;
653 }
654
655 // Use maximum value if the size of each NOP is not specified
656 if (!ControlledNopLength)
657 ControlledNopLength = MaximumNopLength;
658
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;
668 }
669 NumBytes -= NumBytesToEmit;
670 }
671 break;
672 }
673
674 case MCFragment::FT_LEB: {
675 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
676 OS << LF.getContents();
677 break;
678 }
679
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;
686 }
687
689 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
690 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
691 break;
692 }
693
694 case MCFragment::FT_Org: {
695 ++stats::EmittedOrgFragments;
696 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
697
698 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
699 OS << char(OF.getValue());
700
701 break;
702 }
703
705 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
706 OS << OF.getContents();
707 break;
708 }
710 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
711 OS << CF.getContents();
712 break;
713 }
715 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
716 OS << OF.getContents();
717 break;
718 }
720 const auto &DRF = cast<MCCVDefRangeFragment>(F);
721 OS << DRF.getContents();
722 break;
723 }
725 const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
726 OS << PF.getContents();
727 break;
728 }
730 llvm_unreachable("Should not have been added");
731 }
732
733 assert(OS.tell() - Start == FragmentSize &&
734 "The stream should advance by fragment size");
735}
736
738 const MCAsmLayout &Layout) const {
739 assert(getBackendPtr() && "Expected assembler backend");
740
741 // Ignore virtual sections.
742 if (Sec->isVirtualSection()) {
743 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
744
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]) {
761 Sec->getVirtualSectionKind() +
762 " section '" + Sec->getName() +
763 "' cannot have non-zero initializers");
764 break;
765 }
766 break;
767 }
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;
776 assert((cast<MCFillFragment>(F).getValue() == 0) &&
777 "Invalid fill in virtual section!");
778 break;
780 break;
781 }
782 }
783
784 return;
785 }
786
787 uint64_t Start = OS.tell();
788 (void)Start;
789
790 for (const MCFragment &F : *Sec)
791 writeFragment(OS, *this, Layout, F);
792
793 assert(getContext().hadError() ||
794 OS.tell() - Start == Layout.getSectionAddressSize(Sec));
795}
796
797std::tuple<MCValue, uint64_t, bool>
798MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
799 const MCFixup &Fixup) {
800 // Evaluate the fixup.
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);
811 }
812 return std::make_tuple(Target, FixedValue, IsResolved);
813}
814
816 assert(getBackendPtr() && "Expected assembler backend");
817 DEBUG_WITH_TYPE("mc-dump", {
818 errs() << "assembler backend - pre-layout\n--\n";
819 dump(); });
820
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);
828
829 Sec.setOrdinal(SectionIndex++);
830 }
831
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);
836
837 unsigned FragmentIndex = 0;
838 for (MCFragment &Frag : *Sec)
839 Frag.setLayoutOrder(FragmentIndex++);
840 }
841
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());
851 }
852
853 DEBUG_WITH_TYPE("mc-dump", {
854 errs() << "assembler backend - post-relaxation\n--\n";
855 dump(); });
856
857 // Finalize the layout, including fragment lowering.
858 finishLayout(Layout);
859
860 DEBUG_WITH_TYPE("mc-dump", {
861 errs() << "assembler backend - final-layout\n--\n";
862 dump(); });
863
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);
867
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;
874
875 // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
876 switch (Frag.getKind()) {
877 default:
878 continue;
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;
886 }
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;
894 }
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;
902 }
904 MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
905 Fixups = CF.getFixups();
906 Contents = CF.getContents();
907 break;
908 }
910 MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
911 Fixups = DF.getFixups();
912 Contents = DF.getContents();
913 break;
914 }
916 MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
917 Fixups = DF.getFixups();
918 Contents = DF.getContents();
919 break;
920 }
921 case MCFragment::FT_LEB: {
922 auto &LF = cast<MCLEBFragment>(Frag);
923 Fixups = LF.getFixups();
924 Contents = LF.getContents();
925 break;
926 }
928 MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
929 Fixups = PF.getFixups();
930 Contents = PF.getContents();
931 break;
932 }
933 }
934 for (const MCFixup &Fixup : Fixups) {
935 uint64_t FixedValue;
936 bool IsResolved;
938 std::tie(Target, FixedValue, IsResolved) =
939 handleFixup(Layout, Frag, Fixup);
940 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
941 IsResolved, STI);
942 }
943 }
944 }
945}
946
948 // Create the layout object.
949 MCAsmLayout Layout(*this);
950 layout(Layout);
951
952 // Write the object file.
953 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
954}
955
956bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
957 const MCRelaxableFragment *DF,
958 const MCAsmLayout &Layout) const {
959 assert(getBackendPtr() && "Expected assembler backend");
962 bool WasForced;
963 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
964 if (Target.getSymA() &&
965 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
966 Fixup.getKind() == FK_Data_1)
967 return false;
969 Layout, WasForced);
970}
971
972bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
973 const MCAsmLayout &Layout) const {
974 assert(getBackendPtr() && "Expected assembler backend");
975 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
976 // are intentionally pushing out inst fragments, or because we relaxed a
977 // previous instruction to one that doesn't need relaxation.
978 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
979 return false;
980
981 for (const MCFixup &Fixup : F->getFixups())
982 if (fixupNeedsRelaxation(Fixup, F, Layout))
983 return true;
984
985 return false;
986}
987
988bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
991 "Expected CodeEmitter defined for relaxInstruction");
992 if (!fragmentNeedsRelaxation(&F, Layout))
993 return false;
994
995 ++stats::RelaxedInstructions;
996
997 // FIXME-PERF: We could immediately lower out instructions if we can tell
998 // they are fully resolved, to avoid retesting on later passes.
999
1000 // Relax the fragment.
1001
1002 MCInst Relaxed = F.getInst();
1003 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
1004
1005 // Encode the new instruction.
1006 F.setInst(Relaxed);
1007 F.getFixups().clear();
1008 F.getContents().clear();
1009 getEmitter().encodeInstruction(Relaxed, F.getContents(), F.getFixups(),
1010 *F.getSubtargetInfo());
1011 return true;
1012}
1013
1014bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1015 const unsigned OldSize = static_cast<unsigned>(LF.getContents().size());
1016 unsigned PadTo = OldSize;
1017 int64_t Value;
1019 LF.getFixups().clear();
1020 // Use evaluateKnownAbsolute for Mach-O as a hack: .subsections_via_symbols
1021 // requires that .uleb128 A-B is foldable where A and B reside in different
1022 // fragments. This is used by __gcc_except_table.
1023 bool Abs = getSubsectionsViaSymbols()
1024 ? LF.getValue().evaluateKnownAbsolute(Value, Layout)
1025 : LF.getValue().evaluateAsAbsolute(Value, Layout);
1026 if (!Abs) {
1027 if (!getBackend().relaxLEB128(LF, Layout, Value)) {
1029 Twine(LF.isSigned() ? ".s" : ".u") +
1030 "leb128 expression is not absolute");
1031 LF.setValue(MCConstantExpr::create(0, Context));
1032 }
1033 uint8_t Tmp[10]; // maximum size: ceil(64/7)
1034 PadTo = std::max(PadTo, encodeULEB128(uint64_t(Value), Tmp));
1035 }
1036 Data.clear();
1038 // The compiler can generate EH table assembly that is impossible to assemble
1039 // without either adding padding to an LEB fragment or adding extra padding
1040 // to a later alignment fragment. To accommodate such tables, relaxation can
1041 // only increase an LEB fragment size here, not decrease it. See PR35809.
1042 if (LF.isSigned())
1043 encodeSLEB128(Value, OSE, PadTo);
1044 else
1045 encodeULEB128(Value, OSE, PadTo);
1046 return OldSize != LF.getContents().size();
1047}
1048
1049/// Check if the branch crosses the boundary.
1050///
1051/// \param StartAddr start address of the fused/unfused branch.
1052/// \param Size size of the fused/unfused branch.
1053/// \param BoundaryAlignment alignment requirement of the branch.
1054/// \returns true if the branch cross the boundary.
1056 Align BoundaryAlignment) {
1057 uint64_t EndAddr = StartAddr + Size;
1058 return (StartAddr >> Log2(BoundaryAlignment)) !=
1059 ((EndAddr - 1) >> Log2(BoundaryAlignment));
1060}
1061
1062/// Check if the branch is against the boundary.
1063///
1064/// \param StartAddr start address of the fused/unfused branch.
1065/// \param Size size of the fused/unfused branch.
1066/// \param BoundaryAlignment alignment requirement of the branch.
1067/// \returns true if the branch is against the boundary.
1069 Align BoundaryAlignment) {
1070 uint64_t EndAddr = StartAddr + Size;
1071 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1072}
1073
1074/// Check if the branch needs padding.
1075///
1076/// \param StartAddr start address of the fused/unfused branch.
1077/// \param Size size of the fused/unfused branch.
1078/// \param BoundaryAlignment alignment requirement of the branch.
1079/// \returns true if the branch needs padding.
1080static bool needPadding(uint64_t StartAddr, uint64_t Size,
1081 Align BoundaryAlignment) {
1082 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1083 isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1084}
1085
1086bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1088 // BoundaryAlignFragment that doesn't need to align any fragment should not be
1089 // relaxed.
1090 if (!BF.getLastFragment())
1091 return false;
1092
1093 uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1094 uint64_t AlignedSize = 0;
1095 for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1096 F = F->getPrevNode())
1097 AlignedSize += computeFragmentSize(Layout, *F);
1098
1099 Align BoundaryAlignment = BF.getAlignment();
1100 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1101 ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1102 : 0U;
1103 if (NewSize == BF.getSize())
1104 return false;
1105 BF.setSize(NewSize);
1106 Layout.invalidateFragmentsFrom(&BF);
1107 return true;
1108}
1109
1110bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1112
1113 bool WasRelaxed;
1114 if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
1115 return WasRelaxed;
1116
1117 MCContext &Context = Layout.getAssembler().getContext();
1118 uint64_t OldSize = DF.getContents().size();
1119 int64_t AddrDelta;
1120 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1121 assert(Abs && "We created a line delta with an invalid expression");
1122 (void)Abs;
1123 int64_t LineDelta;
1124 LineDelta = DF.getLineDelta();
1125 SmallVectorImpl<char> &Data = DF.getContents();
1126 Data.clear();
1127 DF.getFixups().clear();
1128
1130 AddrDelta, Data);
1131 return OldSize != Data.size();
1132}
1133
1134bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1136 bool WasRelaxed;
1137 if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
1138 return WasRelaxed;
1139
1141 int64_t Value;
1142 bool Abs = DF.getAddrDelta().evaluateAsAbsolute(Value, Layout);
1143 if (!Abs) {
1144 getContext().reportError(DF.getAddrDelta().getLoc(),
1145 "invalid CFI advance_loc expression");
1146 DF.setAddrDelta(MCConstantExpr::create(0, Context));
1147 return false;
1148 }
1149
1150 SmallVectorImpl<char> &Data = DF.getContents();
1151 uint64_t OldSize = Data.size();
1152 Data.clear();
1153 DF.getFixups().clear();
1154
1156 return OldSize != Data.size();
1157}
1158
1159bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1161 unsigned OldSize = F.getContents().size();
1163 return OldSize != F.getContents().size();
1164}
1165
1166bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1168 unsigned OldSize = F.getContents().size();
1170 return OldSize != F.getContents().size();
1171}
1172
1173bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
1175 uint64_t OldSize = PF.getContents().size();
1176 int64_t AddrDelta;
1177 bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1178 assert(Abs && "We created a pseudo probe with an invalid expression");
1179 (void)Abs;
1181 Data.clear();
1183 PF.getFixups().clear();
1184
1185 // AddrDelta is a signed integer
1186 encodeSLEB128(AddrDelta, OSE, OldSize);
1187 return OldSize != Data.size();
1188}
1189
1190bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1191 switch(F.getKind()) {
1192 default:
1193 return false;
1195 assert(!getRelaxAll() &&
1196 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1197 return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1199 return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1201 return relaxDwarfCallFrameFragment(Layout,
1202 cast<MCDwarfCallFrameFragment>(F));
1203 case MCFragment::FT_LEB:
1204 return relaxLEB(Layout, cast<MCLEBFragment>(F));
1206 return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1208 return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1210 return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1212 return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
1213 }
1214}
1215
1216bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1217 // Holds the first fragment which needed relaxing during this layout. It will
1218 // remain NULL if none were relaxed.
1219 // When a fragment is relaxed, all the fragments following it should get
1220 // invalidated because their offset is going to change.
1221 MCFragment *FirstRelaxedFragment = nullptr;
1222
1223 // Attempt to relax all the fragments in the section.
1224 for (MCFragment &Frag : Sec) {
1225 // Check if this is a fragment that needs relaxation.
1226 bool RelaxedFrag = relaxFragment(Layout, Frag);
1227 if (RelaxedFrag && !FirstRelaxedFragment)
1228 FirstRelaxedFragment = &Frag;
1229 }
1230 if (FirstRelaxedFragment) {
1231 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1232 return true;
1233 }
1234 return false;
1235}
1236
1237bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1238 ++stats::RelaxationSteps;
1239
1240 bool WasRelaxed = false;
1241 for (MCSection &Sec : *this) {
1242 while (layoutSectionOnce(Layout, Sec))
1243 WasRelaxed = true;
1244 }
1245
1246 return WasRelaxed;
1247}
1248
1249void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1250 assert(getBackendPtr() && "Expected assembler backend");
1251 // The layout is done. Mark every fragment as valid.
1252 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1253 MCSection &Section = *Layout.getSectionOrder()[i];
1254 Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1255 computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1256 }
1257 getBackend().finishLayout(*this, Layout);
1258}
1259
1260#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1262 raw_ostream &OS = errs();
1263
1264 OS << "<MCAssembler\n";
1265 OS << " Sections:[\n ";
1266 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1267 if (it != begin()) OS << ",\n ";
1268 it->dump();
1269 }
1270 OS << "],\n";
1271 OS << " Symbols:[";
1272
1273 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1274 if (it != symbol_begin()) OS << ",\n ";
1275 OS << "(";
1276 it->dump();
1277 OS << ", Index:" << it->getIndex() << ", ";
1278 OS << ")";
1279 }
1280 OS << "]>\n";
1281}
1282#endif
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:510
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:477
static void writeFragment(raw_ostream &OS, const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment &F)
Write the fragment F to the output file.
static bool needPadding(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch needs padding.
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.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
LLVMContext & Context
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(MCAsmLayout &Layout, MCCVInlineLineTableFragment &F)
Encodes the binary annotations once we have a layout.
Definition: MCCodeView.cpp:485
void encodeDefRange(MCAsmLayout &Layout, MCCVDefRangeFragment &F)
Definition: MCCodeView.cpp:622
int64_t getValue() const
Definition: MCFragment.h:328
Align getAlignment() const
Definition: MCFragment.h:326
unsigned getMaxBytesToEmit() const
Definition: MCFragment.h:332
bool hasEmitNops() const
Definition: MCFragment.h:334
unsigned getValueSize() const
Definition: MCFragment.h:330
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:340
virtual bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout, const bool WasForced) const
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
virtual bool evaluateTargetFixup(const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, uint64_t &Value, bool &WasForced)
Definition: MCAsmBackend.h:124
virtual bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, const MCAsmLayout &Layout, MCAlignFragment &AF)
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
Definition: MCAsmBackend.h:118
virtual void relaxInstruction(MCInst &Inst, const MCSubtargetInfo &STI) const
Relax the instruction in the given fragment to the next wider instruction.
Definition: MCAsmBackend.h:184
virtual void finishLayout(MCAssembler const &Asm, MCAsmLayout &Layout) const
Give backend an opportunity to finish layout after relaxation.
Definition: MCAsmBackend.h:226
virtual void reset()
lifetime management
Definition: MCAsmBackend.h:73
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
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...
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:28
void invalidateFragmentsFrom(MCFragment *F)
Invalidate the fragments starting with F because it has been resized.
Definition: MCFragment.cpp:70
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
Definition: MCFragment.cpp:198
llvm::SmallVectorImpl< MCSection * > & getSectionOrder()
Definition: MCAsmLayout.h:69
uint64_t getSectionFileSize(const MCSection *Sec) const
Get the data size of the given section, as emitted to the object file.
Definition: MCFragment.cpp:204
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
Definition: MCFragment.cpp:152
void layoutFragment(MCFragment *Fragment)
Perform layout for a single fragment, assuming that the previous fragment has already been laid out c...
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
Definition: MCFragment.cpp:96
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:50
MCContext & getContext() const
Definition: MCAssembler.h:321
void Finish()
Finish - Do final processing and write the object to the output stream.
void writeSectionData(raw_ostream &OS, const MCSection *Section, const MCAsmLayout &Layout) const
Emit the section contents to OS.
unsigned getBundleAlignSize() const
Definition: MCAssembler.h:362
bool isBundlingEnabled() const
Definition: MCAssembler.h:360
symbol_iterator symbol_begin()
Definition: MCAssembler.h:384
bool getSubsectionsViaSymbols() const
Definition: MCAssembler.h:347
void dump() const
void layout(MCAsmLayout &Layout)
MCObjectWriter * getWriterPtr() const
Definition: MCAssembler.h:327
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:333
uint64_t computeFragmentSize(const MCAsmLayout &Layout, const MCFragment &F) const
Compute the effective fragment size assuming it is laid out at the given SectionAddress and FragmentO...
MCCodeEmitter * getEmitterPtr() const
Definition: MCAssembler.h:325
bool getRelaxAll() const
Definition: MCAssembler.h:357
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:331
iterator end()
Definition: MCAssembler.h:376
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:84
iterator begin()
Definition: MCAssembler.h:373
bool isThumbFunc(const MCSymbol *Func) const
Check whether a given symbol has been flagged with .thumb_func.
MCAsmBackend & getBackend() const
Definition: MCAssembler.h:329
bool registerSection(MCSection &Section)
const MCSymbol * getAtom(const MCSymbol &S) const
Find the symbol which defines the atom containing the given symbol, or null if there is no such symbo...
MCAsmBackend * getBackendPtr() const
Definition: MCAssembler.h:323
bool isSymbolLinkerVisible(const MCSymbol &SD) const
Check whether a particular symbol is visible to the linker and is required in the symbol table,...
MCLOHContainer & getLOHContainer()
Definition: MCAssembler.h:460
symbol_iterator symbol_end()
Definition: MCAssembler.h:387
void reset()
Reuse an assembler instance.
Definition: MCAssembler.cpp:98
bool registerSymbol(const MCSymbol &Symbol)
MCDwarfLineTableParams getDWARFLinetableParams() const
Definition: MCAssembler.h:335
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:580
uint64_t getSize() const
Definition: MCFragment.h:598
void setSize(uint64_t Value)
Definition: MCFragment.h:599
const MCFragment * getLastFragment() const
Definition: MCFragment.h:604
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:610
Fragment representing the .cv_def_range directive.
Definition: MCFragment.h:550
Fragment representing the binary annotations produced by the .cv_inline_linetable directive.
Definition: MCFragment.h:517
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:194
Context object for machine code objects.
Definition: MCContext.h:76
bool hadError()
Definition: MCContext.h:851
CodeViewContext & getCVContext()
Definition: MCContext.cpp:1003
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1058
Fragment for data and encoded instructions.
Definition: MCFragment.h:242
static void encodeAdvanceLoc(MCContext &Context, uint64_t AddrDelta, SmallVectorImpl< char > &OS)
Definition: MCDwarf.cpp:1930
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:683
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:197
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:223
Interface implemented by fragments that contain encoded instructions and/or data.
Definition: MCFragment.h:125
const MCSubtargetInfo * getSubtargetInfo() const
Retrieve the MCSubTargetInfo in effect when the instruction was encoded.
Definition: MCFragment.h:173
void setBundlePadding(uint8_t N)
Set the padding size for this fragment.
Definition: MCFragment.h:169
uint8_t getBundlePadding() const
Get the padding size that must be inserted before this fragment.
Definition: MCFragment.h:165
bool alignToBundleEnd() const
Should this fragment be placed at the end of an aligned bundle?
Definition: MCFragment.h:157
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const
Definition: MCExpr.cpp:567
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:802
bool evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const
Try to evaluate the expression to the form (a - b + constant) where neither a nor b are variables.
Definition: MCExpr.cpp:810
SMLoc getLoc() const
Definition: MCExpr.h:82
uint8_t getValueSize() const
Definition: MCFragment.h:364
uint64_t getValue() const
Definition: MCFragment.h:363
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
const MCSymbol * getAtom() const
Definition: MCFragment.h:99
MCSection * getParent() const
Definition: MCFragment.h:96
bool hasInstructions() const
Does this fragment have instructions emitted into it? By default this is false, but specific fragment...
Definition: MCFragment.h:107
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
bool isSigned() const
Definition: MCFragment.h:448
const MCExpr & getValue() const
Definition: MCFragment.h:445
void setValue(const MCExpr *Expr)
Definition: MCFragment.h:446
int64_t getControlledNopLength() const
Definition: MCFragment.h:393
int64_t getNumBytes() const
Definition: MCFragment.h:392
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:397
SMLoc getLoc() const
Definition: MCFragment.h:395
virtual uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout)=0
Write the object file and returns the number of bytes written.
virtual void executePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout)=0
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
virtual void reset()
lifetime management
virtual void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue)=0
Record a relocation entry.
SMLoc getLoc() const
Definition: MCFragment.h:424
uint8_t getValue() const
Definition: MCFragment.h:422
const MCExpr & getOffset() const
Definition: MCFragment.h:420
const MCExpr & getAddrDelta() const
Definition: MCFragment.h:627
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:274
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
void setLayoutOrder(unsigned Value)
Definition: MCSection.h:153
MCSection::FragmentListType & getFragmentList()
Definition: MCSection.h:172
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
void setOrdinal(unsigned Value)
Definition: MCSection.h:150
virtual bool useCodeAlign() const =0
Return true if a .align directive should use "optimized nops" to fill instead of 0s.
iterator begin()
Definition: MCSection.h:185
Generic base class for all target subtargets.
Represents a symbol table index fragment.
Definition: MCFragment.h:500
const MCSymbol * getSymbol()
Definition: MCFragment.h:507
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:254
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
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:577
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:134
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
@ FK_Data_1
A one-byte fixup.
Definition: MCFixup.h:23
uint64_t computeBundlePadding(const MCAssembler &Assembler, const MCEncodedFragment *F, uint64_t FOffset, uint64_t FSize)
Compute the amount of padding required before the fragment F to obey bundling restrictions,...
Definition: MCFragment.cpp:213
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.
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:1853
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.
An iterator type that allows iterating over the pointees via some other iterator.
Definition: iterator.h:324