LLVM 24.0.0git
X86AsmBackend.cpp
Go to the documentation of this file.
1//===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
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
18#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCDwarf.h"
24#include "llvm/MC/MCExpr.h"
25#include "llvm/MC/MCInst.h"
26#include "llvm/MC/MCInstrInfo.h"
31#include "llvm/MC/MCSection.h"
34#include "llvm/MC/MCValue.h"
38
39using namespace llvm;
40
41namespace {
42/// A wrapper for holding a mask of the values from X86::AlignBranchBoundaryKind
43class X86AlignBranchKind {
44private:
45 uint8_t AlignBranchKind = 0;
46
47public:
48 X86AlignBranchKind() = default;
49 explicit X86AlignBranchKind(StringRef Val) {
50 SmallVector<StringRef, 6> BranchTypes;
51 Val.split(BranchTypes, '+', -1, false);
52 for (auto BranchType : BranchTypes) {
53 if (BranchType == "fused")
54 addKind(X86::AlignBranchFused);
55 else if (BranchType == "jcc")
56 addKind(X86::AlignBranchJcc);
57 else if (BranchType == "jmp")
58 addKind(X86::AlignBranchJmp);
59 else if (BranchType == "call")
60 addKind(X86::AlignBranchCall);
61 else if (BranchType == "ret")
62 addKind(X86::AlignBranchRet);
63 else if (BranchType == "indirect")
65 else {
66 errs() << "invalid argument " << BranchType.str()
67 << " to -x86-align-branch=; each element must be one of: fused, "
68 "jcc, jmp, call, ret, indirect.(plus separated)\n";
69 }
70 }
71 }
72
73 operator uint8_t() const { return AlignBranchKind; }
74 void addKind(X86::AlignBranchBoundaryKind Value) { AlignBranchKind |= Value; }
75};
76
77class X86AsmBackend : public MCAsmBackend {
78 const X86MCOptions &CLOpts;
79 const MCSubtargetInfo &STI;
80 std::unique_ptr<const MCInstrInfo> MCII;
81 X86AlignBranchKind AlignBranchType;
82 Align AlignBoundary;
83 unsigned TargetPrefixMax = 0;
84
85 MCInst PrevInst;
86 unsigned PrevInstOpcode = 0;
87 bool PrefixEndsBundleLock = false;
88 MCBoundaryAlignFragment *PendingBA = nullptr;
89 std::pair<MCFragment *, size_t> PrevInstPosition;
90
91 uint8_t determinePaddingPrefix(const MCInst &Inst) const;
92 bool isMacroFused(const MCInst &Cmp, const MCInst &Jcc) const;
93 bool needAlign(const MCInst &Inst) const;
94 bool canPadBranches(MCObjectStreamer &OS) const;
95 bool canPadInst(const MCInst &Inst, MCObjectStreamer &OS) const;
96 void emitInstructionBeginBundle(MCObjectStreamer &OS);
97 void emitInstructionEndBundle(MCObjectStreamer &OS);
98
99public:
100 X86AsmBackend(const X86MCOptions &CLOpts, const Target &T,
101 const MCSubtargetInfo &STI)
102 : MCAsmBackend(llvm::endianness::little), CLOpts(CLOpts), STI(STI),
103 MCII(T.createMCInstrInfo()) {
104 if (CLOpts.branches_within_32B_boundaries) {
105 // At the moment, this defaults to aligning fused branches, unconditional
106 // jumps, and (unfused) conditional jumps with nops. Both the
107 // instructions aligned and the alignment method (nop vs prefix) may
108 // change in the future.
109 AlignBoundary = assumeAligned(32);
110 AlignBranchType.addKind(X86::AlignBranchFused);
111 AlignBranchType.addKind(X86::AlignBranchJcc);
112 AlignBranchType.addKind(X86::AlignBranchJmp);
113 }
114 // Allow overriding defaults set by main flag
115 if (CLOpts.align_branch_boundary)
116 AlignBoundary = assumeAligned(*CLOpts.align_branch_boundary);
117 if (CLOpts.align_branch)
118 AlignBranchType = X86AlignBranchKind(*CLOpts.align_branch);
119 if (CLOpts.pad_max_prefix_size)
120 TargetPrefixMax = *CLOpts.pad_max_prefix_size;
121
122 AllowAutoPadding =
123 AlignBoundary != Align(1) && AlignBranchType != X86::AlignBranchNone;
124 AllowEnhancedRelaxation =
125 AllowAutoPadding && TargetPrefixMax != 0 && CLOpts.pad_for_branch_align;
126 AllowBundling = true;
127 }
128
129 const X86MCOptions &getCLOpts() const { return CLOpts; }
130
131 // The streamer frees the fragments these point into.
132 void reset() override {
133 PrevInst = MCInst();
134 PrevInstOpcode = 0;
135 PrefixEndsBundleLock = false;
136 PendingBA = nullptr;
137 PrevInstPosition = {};
138 }
139
140 void emitInstructionBegin(MCObjectStreamer &OS, const MCInst &Inst,
141 const MCSubtargetInfo &STI);
142 void emitInstructionEnd(MCObjectStreamer &OS, const MCInst &Inst);
143
144
145 std::optional<MCFixupKind> getFixupKind(StringRef Name) const override;
146
147 MCFixupKindInfo getFixupKindInfo(MCFixupKind Kind) const override;
148
149 std::optional<bool> evaluateFixup(const MCFragment &, MCFixup &, MCValue &,
150 uint64_t &) override;
151 void applyFixup(const MCFragment &, const MCFixup &, const MCValue &Target,
152 uint8_t *Data, uint64_t Value, bool IsResolved) override;
153
154 bool mayNeedRelaxation(unsigned Opcode, ArrayRef<MCOperand> Operands,
155 const MCSubtargetInfo &STI) const override;
156
157 bool fixupNeedsRelaxationAdvanced(const MCFragment &, const MCFixup &,
158 const MCValue &, uint64_t,
159 bool) const override;
160
161 void relaxInstruction(MCInst &Inst,
162 const MCSubtargetInfo &STI) const override;
163
164 bool padInstructionViaRelaxation(MCFragment &RF, MCCodeEmitter &Emitter,
165 unsigned &RemainingSize) const;
166
167 bool padInstructionViaPrefix(MCFragment &RF, MCCodeEmitter &Emitter,
168 unsigned &RemainingSize) const;
169
170 bool padInstructionEncoding(MCFragment &RF, MCCodeEmitter &Emitter,
171 unsigned &RemainingSize) const;
172
173 bool finishLayout() const override;
174
175 bool padInstsBackward(SmallVectorImpl<MCFragment *> &Relaxable,
176 unsigned &RemainingSize) const;
177 bool foldBundlePad(const MCAssembler &Asm, MCBoundaryAlignFragment &BF,
178 SmallVectorImpl<MCFragment *> &Relaxable) const;
179 bool optimizeBundleNops(const MCAssembler &Asm) const;
180
181 unsigned getMaximumNopSize(const MCSubtargetInfo &STI) const override;
182
183 bool writeNopData(raw_ostream &OS, uint64_t Count,
184 const MCSubtargetInfo *STI) const override;
185};
186} // end anonymous namespace
187
188static bool isRelaxableBranch(unsigned Opcode) {
189 return Opcode == X86::JCC_1 || Opcode == X86::JMP_1;
190}
191
192static unsigned getRelaxedOpcodeBranch(unsigned Opcode,
193 bool Is16BitMode = false) {
194 switch (Opcode) {
195 default:
196 llvm_unreachable("invalid opcode for branch");
197 case X86::JCC_1:
198 return (Is16BitMode) ? X86::JCC_2 : X86::JCC_4;
199 case X86::JMP_1:
200 return (Is16BitMode) ? X86::JMP_2 : X86::JMP_4;
201 }
202}
203
204static unsigned getRelaxedOpcode(const MCInst &MI, bool Is16BitMode) {
205 unsigned Opcode = MI.getOpcode();
206 return isRelaxableBranch(Opcode) ? getRelaxedOpcodeBranch(Opcode, Is16BitMode)
208}
209
211 const MCInstrInfo &MCII) {
212 unsigned Opcode = MI.getOpcode();
213 switch (Opcode) {
214 default:
215 return X86::COND_INVALID;
216 case X86::JCC_1: {
217 const MCInstrDesc &Desc = MCII.get(Opcode);
218 return static_cast<X86::CondCode>(
219 MI.getOperand(Desc.getNumOperands() - 1).getImm());
220 }
221 }
222}
223
227 return classifySecondCondCodeInMacroFusion(CC);
228}
229
230/// Check if the instruction uses RIP relative addressing.
231static bool isRIPRelative(const MCInst &MI, const MCInstrInfo &MCII) {
232 const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
233 int MemoryOperand = X86II::getMemoryOperandIdx(Desc);
234 if (MemoryOperand < 0)
235 return false;
236 unsigned BaseRegNum = MemoryOperand + X86::AddrBaseReg;
237 MCRegister BaseReg = MI.getOperand(BaseRegNum).getReg();
238 return (BaseReg == X86::RIP);
239}
240
241/// Check if the instruction is a prefix.
242static bool isPrefix(unsigned Opcode, const MCInstrInfo &MCII) {
243 return X86II::isPrefix(MCII.get(Opcode).TSFlags);
244}
245
246/// Check if the instruction is valid as the first instruction in macro fusion.
247static bool isFirstMacroFusibleInst(const MCInst &Inst,
248 const MCInstrInfo &MCII) {
249 // An Intel instruction with RIP relative addressing is not macro fusible.
250 if (isRIPRelative(Inst, MCII))
251 return false;
255}
256
257/// X86 can reduce the bytes of NOP by padding instructions with prefixes to
258/// get a better peformance in some cases. Here, we determine which prefix is
259/// the most suitable.
260///
261/// If the instruction has a segment override prefix, use the existing one.
262/// If the target is 64-bit, use the CS.
263/// If the target is 32-bit,
264/// - If the instruction has a ESP/EBP base register, use SS.
265/// - Otherwise use DS.
266uint8_t X86AsmBackend::determinePaddingPrefix(const MCInst &Inst) const {
267 assert((STI.hasFeature(X86::Is32Bit) || STI.hasFeature(X86::Is64Bit)) &&
268 "Prefixes can be added only in 32-bit or 64-bit mode.");
269 const MCInstrDesc &Desc = MCII->get(Inst.getOpcode());
270 uint64_t TSFlags = Desc.TSFlags;
271
272 // Determine where the memory operand starts, if present.
273 int MemoryOperand = X86II::getMemoryOperandIdx(Desc);
274
275 MCRegister SegmentReg;
276 if (MemoryOperand >= 0) {
277 // Check for explicit segment override on memory operand.
278 SegmentReg = Inst.getOperand(MemoryOperand + X86::AddrSegmentReg).getReg();
279 }
280
281 switch (TSFlags & X86II::FormMask) {
282 default:
283 break;
284 case X86II::RawFrmDstSrc: {
285 // Check segment override opcode prefix as needed (not for %ds).
286 if (Inst.getOperand(2).getReg() != X86::DS)
287 SegmentReg = Inst.getOperand(2).getReg();
288 break;
289 }
290 case X86II::RawFrmSrc: {
291 // Check segment override opcode prefix as needed (not for %ds).
292 if (Inst.getOperand(1).getReg() != X86::DS)
293 SegmentReg = Inst.getOperand(1).getReg();
294 break;
295 }
297 // Check segment override opcode prefix as needed.
298 SegmentReg = Inst.getOperand(1).getReg();
299 break;
300 }
301 }
302
303 if (SegmentReg)
304 return X86::getSegmentOverridePrefixForReg(SegmentReg);
305
306 if (STI.hasFeature(X86::Is64Bit))
307 return X86::CS_Encoding;
308
309 if (MemoryOperand >= 0) {
310 unsigned BaseRegNum = MemoryOperand + X86::AddrBaseReg;
311 MCRegister BaseReg = Inst.getOperand(BaseRegNum).getReg();
312 if (BaseReg == X86::ESP || BaseReg == X86::EBP)
313 return X86::SS_Encoding;
314 }
315 return X86::DS_Encoding;
316}
317
318/// Check if the two instructions will be macro-fused on the target cpu.
319bool X86AsmBackend::isMacroFused(const MCInst &Cmp, const MCInst &Jcc) const {
320 const MCInstrDesc &InstDesc = MCII->get(Jcc.getOpcode());
321 if (!InstDesc.isConditionalBranch())
322 return false;
323 if (!isFirstMacroFusibleInst(Cmp, *MCII))
324 return false;
325 const X86::FirstMacroFusionInstKind CmpKind =
327 const X86::SecondMacroFusionInstKind BranchKind =
329 return X86::isMacroFused(CmpKind, BranchKind);
330}
331
332/// Check if the instruction has a variant symbol operand.
333static bool hasVariantSymbol(const MCInst &MI) {
334 for (auto &Operand : MI) {
335 if (!Operand.isExpr())
336 continue;
337 const MCExpr &Expr = *Operand.getExpr();
338 if (Expr.getKind() == MCExpr::SymbolRef &&
339 cast<MCSymbolRefExpr>(&Expr)->getSpecifier())
340 return true;
341 }
342 return false;
343}
344
345/// X86 has certain instructions which enable interrupts exactly one
346/// instruction *after* the instruction which stores to SS. Return true if the
347/// given instruction may have such an interrupt delay slot.
348static bool mayHaveInterruptDelaySlot(unsigned InstOpcode) {
349 switch (InstOpcode) {
350 case X86::POPSS16:
351 case X86::POPSS32:
352 case X86::STI:
353 return true;
354
355 case X86::MOV16sr:
356 case X86::MOV32sr:
357 case X86::MOV64sr:
358 case X86::MOV16sm:
359 // In fact, this is only the case if the first operand is SS. However, as
360 // segment moves occur extremely rarely, this is just a minor pessimization.
361 return true;
362 }
363 return false;
364}
365
366/// Return true if we can insert NOP or prefixes automatically before the
367/// the instruction to be emitted.
368bool X86AsmBackend::canPadInst(const MCInst &Inst, MCObjectStreamer &OS) const {
369 if (hasVariantSymbol(Inst))
370 // Linker may rewrite the instruction with variant symbol operand(e.g.
371 // TLSCALL).
372 return false;
373
374 if (mayHaveInterruptDelaySlot(PrevInstOpcode))
375 // If this instruction follows an interrupt enabling instruction with a one
376 // instruction delay, inserting a nop would change behavior.
377 return false;
378
379 if (isPrefix(PrevInstOpcode, *MCII))
380 // If this instruction follows a prefix, inserting a nop/prefix would change
381 // semantic.
382 return false;
383
384 if (isPrefix(Inst.getOpcode(), *MCII))
385 // If this instruction is a prefix, inserting a prefix would change
386 // semantic.
387 return false;
388
389 // If this instruction follows any data, there is no clear instruction
390 // boundary, inserting a nop/prefix would change semantic.
391 auto Offset = OS.getCurFragSize();
392 if (Offset && (OS.getCurrentFragment() != PrevInstPosition.first ||
393 Offset != PrevInstPosition.second))
394 return false;
395
396 return true;
397}
398
399bool X86AsmBackend::canPadBranches(MCObjectStreamer &OS) const {
400 if (!OS.getAllowAutoPadding())
401 return false;
402 assert(allowAutoPadding() && "incorrect initialization!");
403
404 // We only pad in text section.
405 if (!OS.getCurrentSectionOnly()->isText())
406 return false;
407
408 // Branches only need to be aligned in 32-bit or 64-bit mode.
409 if (!(STI.hasFeature(X86::Is64Bit) || STI.hasFeature(X86::Is32Bit)))
410 return false;
411
412 return true;
413}
414
415/// Check if the instruction operand needs to be aligned.
416bool X86AsmBackend::needAlign(const MCInst &Inst) const {
417 const MCInstrDesc &Desc = MCII->get(Inst.getOpcode());
418 return (Desc.isConditionalBranch() &&
419 (AlignBranchType & X86::AlignBranchJcc)) ||
420 (Desc.isUnconditionalBranch() &&
421 (AlignBranchType & X86::AlignBranchJmp)) ||
422 (Desc.isCall() && (AlignBranchType & X86::AlignBranchCall)) ||
423 (Desc.isReturn() && (AlignBranchType & X86::AlignBranchRet)) ||
424 (Desc.isIndirectBranch() &&
425 (AlignBranchType & X86::AlignBranchIndirect));
426}
427
429 const MCSubtargetInfo &STI) {
430 auto &Backend = static_cast<X86AsmBackend &>(S.getAssembler().getBackend());
431 bool AutoPadding = S.getAllowAutoPadding();
432 if (LLVM_LIKELY(!AutoPadding && !Backend.getCLOpts().pad_for_align)) {
433 S.MCObjectStreamer::emitInstruction(Inst, STI);
434 return;
435 }
436
437 // Run the LFI rewriter outside of emitInstructionBegin/End so that nested
438 // instructions or bundle_lock/unlock directives do not corrupt the Begin/End
439 // bookkeeping for the original instruction.
440 if (S.getLFIRewriter() && S.getLFIRewriter()->rewriteInst(Inst, S, STI))
441 return;
442
443 Backend.emitInstructionBegin(S, Inst, STI);
444 S.MCObjectStreamer::emitInstruction(Inst, STI);
445 Backend.emitInstructionEnd(S, Inst);
446}
447
448/// Open a MCBoundaryAlignFragment for the upcoming instruction so that layout
449/// can pad it into the next bundle. Within .bundle_lock the group's fragment
450/// already covers it.
451void X86AsmBackend::emitInstructionBeginBundle(MCObjectStreamer &OS) {
452 assert(Asm->isBundlingEnabled());
453
454 // The prefix stays in the group while this instruction gets its own
455 // fragment, so padding may land between the two.
456 if (PrefixEndsBundleLock && OS.getCurrentFragment() != PrevInstPosition.first)
457 getContext().reportError(OS.getStartTokLoc(),
458 "instruction prefix cannot be the last "
459 "instruction of a .bundle_lock group");
460
461 if (OS.isBundleLocked())
462 return;
463 // A pending fragment means the previous MCInst was a prefix, which must stay
464 // with this one: extend its range. Adjacency rejects a fragment left stale by
465 // an intervening .bundle_lock group.
466 if (PendingBA &&
467 PendingBA->getLastFragment()->getNext() == OS.getCurrentFragment()) {
468 PendingBA->setLastFragment(OS.getCurrentFragment());
469 return;
470 }
472 Asm->getBundleAlign(), STI);
473 // We can set LastFragment now, before the instruction is emitted, as bundling
474 // emits one fragment per instruction. Deferring setLastFragment to
475 // post-emitInstruction would risk capturing a fragment that a subsequent
476 // emitCodeAlignment repurposes in-place to FT_Align, corrupting the BA's
477 // boundary range.
478 PendingBA->setLastFragment(OS.getCurrentFragment());
479}
480
481/// Close the fragment opened by emitInstructionBeginBundle, unless the
482/// instruction was a prefix, in which case the next one extends it.
483void X86AsmBackend::emitInstructionEndBundle(MCObjectStreamer &OS) {
484 assert(Asm->isBundlingEnabled());
485
486 if (OS.isBundleLocked()) {
487 PrefixEndsBundleLock = isPrefix(PrevInstOpcode, *MCII);
488 return;
489 }
490 PrefixEndsBundleLock = false;
491 assert(PendingBA && "MCBoundaryAlignFragment is expected for every "
492 "instruction if it is not bundle-locked");
493
494 OS.getCurrentSectionOnly()->ensureMinAlignment(Asm->getBundleAlign());
495
496 if (!isPrefix(PrevInstOpcode, *MCII))
497 PendingBA = nullptr;
498}
499
500/// Insert BoundaryAlignFragment before instructions to align branches.
501void X86AsmBackend::emitInstructionBegin(MCObjectStreamer &OS,
502 const MCInst &Inst,
503 const MCSubtargetInfo &STI) {
504 bool CanPadInst = canPadInst(Inst, OS);
505 if (Asm->isBundlingEnabled()) {
506 emitInstructionBeginBundle(OS);
507 OS.getCurrentFragment()->setAllowAutoPadding(CanPadInst);
508 return;
509 }
510 if (CanPadInst)
512
513 if (!canPadBranches(OS))
514 return;
515
516 // NB: PrevInst only valid if canPadBranches is true.
517 if (!isMacroFused(PrevInst, Inst))
518 // Macro fusion doesn't happen indeed, clear the pending.
519 PendingBA = nullptr;
520
521 // When branch padding is enabled (basically the skx102 erratum => unlikely),
522 // we call canPadInst (not cheap) twice. However, in the common case, we can
523 // avoid unnecessary calls to that, as this is otherwise only used for
524 // relaxable fragments.
525 if (!CanPadInst)
526 return;
527
528 if (PendingBA) {
529 auto *NextFragment = PendingBA->getNext();
530 assert(NextFragment && "NextFragment should not be null");
531 if (NextFragment == OS.getCurrentFragment())
532 return;
533 // We eagerly create an empty fragment when inserting a fragment
534 // with a variable-size tail.
535 if (NextFragment->getNext() == OS.getCurrentFragment())
536 return;
537
538 // Macro fusion actually happens and there is no other fragment inserted
539 // after the previous instruction.
540 //
541 // Do nothing here since we already inserted a BoudaryAlign fragment when
542 // we met the first instruction in the fused pair and we'll tie them
543 // together in emitInstructionEnd.
544 //
545 // Note: When there is at least one fragment, such as MCAlignFragment,
546 // inserted after the previous instruction, e.g.
547 //
548 // \code
549 // cmp %rax %rcx
550 // .align 16
551 // je .Label0
552 // \ endcode
553 //
554 // We will treat the JCC as a unfused branch although it may be fused
555 // with the CMP.
556 return;
557 }
558
559 if (needAlign(Inst) || ((AlignBranchType & X86::AlignBranchFused) &&
560 isFirstMacroFusibleInst(Inst, *MCII))) {
561 // If we meet a unfused branch or the first instruction in a fusiable pair,
562 // insert a BoundaryAlign fragment.
563 PendingBA =
564 OS.newSpecialFragment<MCBoundaryAlignFragment>(AlignBoundary, STI);
565 }
566}
567
568/// Set the last fragment to be aligned for the BoundaryAlignFragment.
569void X86AsmBackend::emitInstructionEnd(MCObjectStreamer &OS,
570 const MCInst &Inst) {
571 // Update PrevInstOpcode here, canPadInst() reads that.
572 MCFragment *CF = OS.getCurrentFragment();
573 PrevInstOpcode = Inst.getOpcode();
574 PrevInstPosition = std::make_pair(CF, OS.getCurFragSize());
575 if (Asm->isBundlingEnabled())
576 return emitInstructionEndBundle(OS);
577
578 if (!canPadBranches(OS))
579 return;
580
581 // PrevInst is only needed if canPadBranches. Copying an MCInst isn't cheap.
582 PrevInst = Inst;
583
584 if (!needAlign(Inst) || !PendingBA)
585 return;
586
587 // Tie the aligned instructions into a pending BoundaryAlign.
588 PendingBA->setLastFragment(CF);
589 PendingBA = nullptr;
590
591 // We need to ensure that further data isn't added to the current
592 // DataFragment, so that we can get the size of instructions later in
593 // MCAssembler::relaxBoundaryAlign. The easiest way is to insert a new empty
594 // DataFragment.
595 OS.newFragment();
596
597 // Update the maximum alignment on the current section if necessary.
598 CF->getParent()->ensureMinAlignment(AlignBoundary);
599}
600
601std::optional<MCFixupKind> X86AsmBackend::getFixupKind(StringRef Name) const {
602 if (STI.getTargetTriple().isOSBinFormatELF()) {
603 unsigned Type;
604 if (STI.getTargetTriple().isX86_64()) {
605 Type = llvm::StringSwitch<unsigned>(Name)
606#define ELF_RELOC(X, Y) .Case(#X, Y)
607#include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
608#undef ELF_RELOC
609 .Case("BFD_RELOC_NONE", ELF::R_X86_64_NONE)
610 .Case("BFD_RELOC_8", ELF::R_X86_64_8)
611 .Case("BFD_RELOC_16", ELF::R_X86_64_16)
612 .Case("BFD_RELOC_32", ELF::R_X86_64_32)
613 .Case("BFD_RELOC_64", ELF::R_X86_64_64)
614 .Default(-1u);
615 } else {
616 Type = llvm::StringSwitch<unsigned>(Name)
617#define ELF_RELOC(X, Y) .Case(#X, Y)
618#include "llvm/BinaryFormat/ELFRelocs/i386.def"
619#undef ELF_RELOC
620 .Case("BFD_RELOC_NONE", ELF::R_386_NONE)
621 .Case("BFD_RELOC_8", ELF::R_386_8)
622 .Case("BFD_RELOC_16", ELF::R_386_16)
623 .Case("BFD_RELOC_32", ELF::R_386_32)
624 .Default(-1u);
625 }
626 if (Type == -1u)
627 return std::nullopt;
628 return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
629 }
630 return MCAsmBackend::getFixupKind(Name);
631}
632
633MCFixupKindInfo X86AsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
634 const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
635 // clang-format off
636 {"reloc_riprel_4byte", 0, 32, 0},
637 {"reloc_riprel_4byte_movq_load", 0, 32, 0},
638 {"reloc_riprel_4byte_movq_load_rex2", 0, 32, 0},
639 {"reloc_riprel_4byte_relax", 0, 32, 0},
640 {"reloc_riprel_4byte_relax_rex", 0, 32, 0},
641 {"reloc_riprel_4byte_relax_rex2", 0, 32, 0},
642 {"reloc_riprel_4byte_relax_evex", 0, 32, 0},
643 {"reloc_signed_4byte", 0, 32, 0},
644 {"reloc_signed_4byte_relax", 0, 32, 0},
645 {"reloc_global_offset_table", 0, 32, 0},
646 {"reloc_branch_4byte_pcrel", 0, 32, 0},
647 // clang-format on
648 };
649
650 // Fixup kinds from .reloc directive are like R_386_NONE/R_X86_64_NONE. They
651 // do not require any extra processing.
652 if (mc::isRelocation(Kind))
653 return {};
654
655 if (Kind < FirstTargetFixupKind)
657
659 "Invalid kind!");
660 assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
661 return Infos[Kind - FirstTargetFixupKind];
662}
663
664static unsigned getFixupKindSize(unsigned Kind) {
665 switch (Kind) {
666 default:
667 llvm_unreachable("invalid fixup kind!");
668 case FK_NONE:
669 return 0;
670 case FK_SecRel_1:
671 case FK_Data_1:
672 return 1;
673 case FK_SecRel_2:
674 case FK_Data_2:
675 return 2;
687 case FK_SecRel_4:
688 case FK_Data_4:
689 return 4;
690 case FK_SecRel_8:
691 case FK_Data_8:
692 return 8;
693 }
694}
695
696constexpr char GotSymName[] = "_GLOBAL_OFFSET_TABLE_";
697
698// Adjust PC-relative fixup offsets, which are calculated from the start of the
699// next instruction.
700std::optional<bool> X86AsmBackend::evaluateFixup(const MCFragment &,
701 MCFixup &Fixup,
702 MCValue &Target, uint64_t &) {
703 if (Fixup.isPCRel()) {
704 switch (Fixup.getKind()) {
705 case FK_Data_1:
706 Target.setConstant(Target.getConstant() - 1);
707 break;
708 case FK_Data_2:
709 Target.setConstant(Target.getConstant() - 2);
710 break;
711 default: {
712 Target.setConstant(Target.getConstant() - 4);
713 auto *Add = Target.getAddSym();
714 // If this is a pc-relative load off _GLOBAL_OFFSET_TABLE_:
715 // leaq _GLOBAL_OFFSET_TABLE_(%rip), %r15
716 // this needs to be a GOTPC32 relocation.
717 if (Add && Add->getName() == GotSymName)
718 Fixup = MCFixup::create(Fixup.getOffset(), Fixup.getValue(),
720 } break;
721 }
722 }
723 // Use default handling for `Value` and `IsResolved`.
724 return {};
725}
726
727void X86AsmBackend::applyFixup(const MCFragment &F, const MCFixup &Fixup,
728 const MCValue &Target, uint8_t *Data,
729 uint64_t Value, bool IsResolved) {
730 // Force relocation when there is a specifier. This might be too conservative
731 // - GAS doesn't emit a relocation for call local@plt; local:.
732 if (Target.getSpecifier())
733 IsResolved = false;
734 maybeAddReloc(F, Fixup, Target, Value, IsResolved);
735
736 auto Kind = Fixup.getKind();
737 if (mc::isRelocation(Kind))
738 return;
739 unsigned Size = getFixupKindSize(Kind);
740
741 assert(Fixup.getOffset() + Size <= F.getSize() && "Invalid fixup offset!");
742
743 // Check fixup value overflow similar to GAS (fixups emitted as RELA
744 // relocations have a value of 0).
745 // - Unknown signedness: the range (-2^N, 2^N) is allowed,
746 // accommodating intN_t, uintN_t, and a non-positive value type.
747 // - Signed (intN_t): the range [-2^(N-1), 2^(N-1)) is allowed.
748 //
749 // Currently only resolved PC-relative fixups are treated as signed. GAS
750 // treats more as signed (e.g. unresolved R_X86_64_32S).
751 // Unresolved fixups have unknown signedness to allow `jmp foo+0xffffffff`.
752 if (Size && Size < 8) {
753 bool Signed = IsResolved && Fixup.isPCRel();
754 uint64_t Mask = ~uint64_t(0) << (Size * 8 - (Signed ? 1 : 0));
755 if ((Value & Mask) && (Signed ? (Value & Mask) != Mask : (-Value & Mask)))
756 getContext().reportError(Fixup.getLoc(),
757 "value of " + Twine(int64_t(Value)) +
758 " is too large for field of " + Twine(Size) +
759 (Size == 1 ? " byte" : " bytes"));
760 }
761
762 for (unsigned i = 0; i != Size; ++i)
763 Data[i] = uint8_t(Value >> (i * 8));
764}
765
766bool X86AsmBackend::mayNeedRelaxation(unsigned Opcode,
768 const MCSubtargetInfo &STI) const {
769 unsigned SkipOperands = X86::isCCMPCC(Opcode) ? 2 : 0;
770 return isRelaxableBranch(Opcode) ||
771 (X86::getOpcodeForLongImmediateForm(Opcode) != Opcode &&
772 Operands[Operands.size() - 1 - SkipOperands].isExpr());
773}
774
775bool X86AsmBackend::fixupNeedsRelaxationAdvanced(const MCFragment &F,
776 const MCFixup &Fixup,
777 const MCValue &Target,
779 bool Resolved) const {
780 // If resolved, relax if the value is too big for a (signed) i8.
781 //
782 // Currently, `jmp local@plt` relaxes JMP even if the offset is small,
783 // different from gas.
784 if (Resolved) {
785 // finishLayout folds padding into encodings after relaxation, shifting a
786 // branch and its target within their bundles. Keep a bundle of headroom.
787 // Immediates do not shift.
788 int64_t Slack = Asm->isBundlingEnabled() && TargetPrefixMax != 0 &&
789 isRelaxableBranch(F.getOpcode())
790 ? Asm->getBundleAlign().value()
791 : 0;
792 return !isInt<8>(int64_t(Value) + Slack) ||
793 !isInt<8>(int64_t(Value) - Slack) || Target.getSpecifier();
794 }
795
796 // Otherwise, relax unless there is a @ABS8 specifier.
797 if (Fixup.getKind() == FK_Data_1 && Target.getAddSym() &&
798 Target.getSpecifier() == X86::S_ABS8)
799 return false;
800 return true;
801}
802
803// FIXME: Can tblgen help at all here to verify there aren't other instructions
804// we can relax?
805void X86AsmBackend::relaxInstruction(MCInst &Inst,
806 const MCSubtargetInfo &STI) const {
807 // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
808 bool Is16BitMode = STI.hasFeature(X86::Is16Bit);
809 unsigned RelaxedOp = getRelaxedOpcode(Inst, Is16BitMode);
810 assert(RelaxedOp != Inst.getOpcode());
811 Inst.setOpcode(RelaxedOp);
812}
813
814bool X86AsmBackend::padInstructionViaPrefix(MCFragment &RF,
815 MCCodeEmitter &Emitter,
816 unsigned &RemainingSize) const {
817 if (!RF.getAllowAutoPadding())
818 return false;
819 // If the instruction isn't fully relaxed, shifting it around might require a
820 // larger value for one of the fixups then can be encoded. The outer loop
821 // will also catch this before moving to the next instruction, but we need to
822 // prevent padding this single instruction as well.
823 if (mayNeedRelaxation(RF.getOpcode(), RF.getOperands(),
824 *RF.getSubtargetInfo()))
825 return false;
826
827 const unsigned OldSize = RF.getVarSize();
828 if (OldSize == 15)
829 return false;
830
831 const unsigned MaxPossiblePad = std::min(15 - OldSize, RemainingSize);
832 const unsigned RemainingPrefixSize = [&]() -> unsigned {
833 SmallString<15> Code;
834 X86_MC::emitPrefix(Emitter, RF.getInst(), Code, STI);
835 assert(Code.size() < 15 && "The number of prefixes must be less than 15.");
836
837 // TODO: It turns out we need a decent amount of plumbing for the target
838 // specific bits to determine number of prefixes its safe to add. Various
839 // targets (older chips mostly, but also Atom family) encounter decoder
840 // stalls with too many prefixes. For testing purposes, we set the value
841 // externally for the moment.
842 unsigned ExistingPrefixSize = Code.size();
843 if (TargetPrefixMax <= ExistingPrefixSize)
844 return 0;
845 return TargetPrefixMax - ExistingPrefixSize;
846 }();
847 const unsigned PrefixBytesToAdd =
848 std::min(MaxPossiblePad, RemainingPrefixSize);
849 if (PrefixBytesToAdd == 0)
850 return false;
851
852 const uint8_t Prefix = determinePaddingPrefix(RF.getInst());
853
854 SmallString<256> Code;
855 Code.append(PrefixBytesToAdd, Prefix);
856 Code.append(RF.getVarContents().begin(), RF.getVarContents().end());
857 RF.setVarContents(Code);
858
859 // Adjust the fixups for the change in offsets
860 for (auto &F : RF.getVarFixups())
861 F.setOffset(PrefixBytesToAdd + F.getOffset());
862
863 RemainingSize -= PrefixBytesToAdd;
864 return true;
865}
866
867bool X86AsmBackend::padInstructionViaRelaxation(MCFragment &RF,
868 MCCodeEmitter &Emitter,
869 unsigned &RemainingSize) const {
870 if (!mayNeedRelaxation(RF.getOpcode(), RF.getOperands(),
871 *RF.getSubtargetInfo()))
872 // TODO: There are lots of other tricks we could apply for increasing
873 // encoding size without impacting performance.
874 return false;
875
876 MCInst Relaxed = RF.getInst();
877 relaxInstruction(Relaxed, *RF.getSubtargetInfo());
878
880 SmallString<15> Code;
881 Emitter.encodeInstruction(Relaxed, Code, Fixups, *RF.getSubtargetInfo());
882 const unsigned OldSize = RF.getVarContents().size();
883 const unsigned NewSize = Code.size();
884 assert(NewSize >= OldSize && "size decrease during relaxation?");
885 unsigned Delta = NewSize - OldSize;
886 if (Delta > RemainingSize)
887 return false;
888 RF.setInst(Relaxed);
889 RF.setVarContents(Code);
890 RF.setVarFixups(Fixups);
891 RemainingSize -= Delta;
892 return true;
893}
894
895bool X86AsmBackend::padInstructionEncoding(MCFragment &RF,
896 MCCodeEmitter &Emitter,
897 unsigned &RemainingSize) const {
898 bool Changed = false;
899 if (RemainingSize != 0)
900 Changed |= padInstructionViaRelaxation(RF, Emitter, RemainingSize);
901 if (RemainingSize != 0)
902 Changed |= padInstructionViaPrefix(RF, Emitter, RemainingSize);
903 return Changed;
904}
905
906bool X86AsmBackend::padInstsBackward(SmallVectorImpl<MCFragment *> &Relaxable,
907 unsigned &RemainingSize) const {
908 bool Changed = false;
909 while (!Relaxable.empty() && RemainingSize != 0) {
910 auto &RF = *Relaxable.pop_back_val();
911 // Give the backend a chance to play any tricks it wishes to increase
912 // the encoding size of the given instruction. Target independent code
913 // will try further relaxation, but target's may play further tricks.
914 Changed |= padInstructionEncoding(RF, Asm->getEmitter(), RemainingSize);
915
916 // If we have an instruction which hasn't been fully relaxed, we can't
917 // skip past it and insert bytes before it. Changing its starting
918 // offset might require a larger negative offset than it can encode.
919 // We don't need to worry about larger positive offsets as none of the
920 // possible offsets between this and our align are visible, and the
921 // ones afterwards aren't changing.
922 if (mayNeedRelaxation(RF.getOpcode(), RF.getOperands(),
923 *RF.getSubtargetInfo()))
924 break;
925 }
926 Relaxable.clear();
927 return Changed;
928}
929
930/// Trade the padding held by \p BF for ignored prefixes on the instructions
931/// around it. Padding never leaves its own bundle, so no instruction or
932/// bundle-locked group moves across a boundary. \p Relaxable holds the
933/// preceding instructions in that bundle and is consumed.
934bool X86AsmBackend::foldBundlePad(
935 const MCAssembler &Asm, MCBoundaryAlignFragment &BF,
936 SmallVectorImpl<MCFragment *> &Relaxable) const {
937 const uint64_t BundleSize = Asm.getBundleAlign().value();
938 const uint64_t PadStart = Asm.getFragmentOffset(BF);
939 unsigned Remaining = BF.getSize();
940
941 // Only padding in PadStart's own bundle may move backward; an align_to_end
942 // group can push the rest into the next bundle.
943 unsigned Budget =
944 std::min<uint64_t>(Remaining, BundleSize - PadStart % BundleSize);
945 unsigned Left = Budget;
946 bool Changed = padInstsBackward(Relaxable, Left);
947 Remaining -= Budget - Left;
948
949 // Absorbing padding moves the group's start earlier while its end is pinned,
950 // so it may only grow into the slack in its bundle: BundleSize - GroupSize
951 // for align_to_end, zero for a group that already starts on a boundary.
952 if (BF.isAlignToEnd() && Remaining) {
953 uint64_t GroupSize = 0;
954 for (const MCFragment *F = BF.getNext();; F = F->getNext()) {
955 GroupSize += Asm.computeFragmentSize(*F);
956 if (F == BF.getLastFragment())
957 break;
958 }
959 if (GroupSize < BundleSize) {
960 Left = Budget = std::min<uint64_t>(Remaining, BundleSize - GroupSize);
961 for (MCFragment *F = BF.getNext(); F; F = F->getNext()) {
962 if (F->getKind() == MCFragment::FT_Relaxable)
963 Changed |= padInstructionEncoding(*F, Asm.getEmitter(), Left);
964 if (F == BF.getLastFragment() || Left == 0)
965 break;
966 }
967 Remaining -= Budget - Left;
968 }
969 }
970
971 BF.setSize(Remaining);
972 return Changed;
973}
974
975bool X86AsmBackend::optimizeBundleNops(const MCAssembler &Asm) const {
976 const uint64_t BundleSize = Asm.getBundleAlign().value();
977 bool Changed = false;
978 for (MCSection &Sec : Asm) {
979 if (!Sec.isText())
980 continue;
981
982 // Instructions preceding the next padding and sharing its bundle.
984 // Folding leaves stale offsets until the next layout, so skip the
985 // rewritten range.
986 const MCFragment *ResumeAfter = nullptr;
987 for (MCFragment &F : Sec) {
988 if (ResumeAfter) {
989 if (&F == ResumeAfter)
990 ResumeAfter = nullptr;
991 continue;
992 }
993 uint64_t Offset = Asm.getFragmentOffset(F);
994 if (!Relaxable.empty() &&
995 Asm.getFragmentOffset(*Relaxable.front()) / BundleSize !=
996 Offset / BundleSize)
997 Relaxable.clear();
998
999 switch (F.getKind()) {
1001 auto &BF = static_cast<MCBoundaryAlignFragment &>(F);
1002 if (!BF.getSize())
1003 break; // Nothing to fold, and not a barrier.
1004 Changed |= foldBundlePad(Asm, BF, Relaxable);
1005 ResumeAfter = BF.getLastFragment();
1006 break;
1007 }
1009 Relaxable.push_back(&F);
1010 break;
1012 break; // Fixed bytes, safe to shift.
1013 default:
1014 // Other kinds may change size when shifted (.p2align, .org, LEBs).
1015 Relaxable.clear();
1016 break;
1017 }
1018 }
1019 }
1020
1021 return Changed;
1022}
1023
1024bool X86AsmBackend::finishLayout() const {
1025 // With bundling, padding is fully determined during layout and the only
1026 // post-layout optimization is prefix padding.
1027 if (Asm->isBundlingEnabled())
1028 return TargetPrefixMax != 0 && optimizeBundleNops(*Asm);
1029 // See if we can further relax some instructions to cut down on the number of
1030 // nop bytes required for code alignment. The actual win is in reducing
1031 // instruction count, not number of bytes. Modern X86-64 can easily end up
1032 // decode limited. It is often better to reduce the number of instructions
1033 // (i.e. eliminate nops) even at the cost of increasing the size and
1034 // complexity of others.
1035 if (!CLOpts.pad_for_align &&
1036 !(AllowAutoPadding && CLOpts.pad_for_branch_align))
1037 return false;
1038
1039 // The processed regions are delimitered by LabeledFragments. -g may have more
1040 // MCSymbols and therefore different relaxation results. -x86-pad-for-align is
1041 // disabled by default to eliminate the -g vs non -g difference.
1042 DenseSet<MCFragment *> LabeledFragments;
1043 for (const MCSymbol &S : Asm->symbols())
1044 LabeledFragments.insert(S.getFragment());
1045
1046 bool Changed = false;
1047 for (MCSection &Sec : *Asm) {
1048 if (!Sec.isText())
1049 continue;
1050
1052 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1053 MCFragment &F = *I;
1054
1055 if (LabeledFragments.count(&F))
1056 Relaxable.clear();
1057
1058 if (F.getKind() == MCFragment::FT_Data) // Skip and ignore
1059 continue;
1060
1061 if (F.getKind() == MCFragment::FT_Relaxable) {
1062 auto &RF = cast<MCFragment>(*I);
1063 Relaxable.push_back(&RF);
1064 continue;
1065 }
1066
1067 auto canHandle = [&](MCFragment &F) -> bool {
1068 switch (F.getKind()) {
1069 default:
1070 return false;
1072 return CLOpts.pad_for_align;
1074 return CLOpts.pad_for_branch_align;
1075 }
1076 };
1077 // For any unhandled kind, assume we can't change layout.
1078 if (!canHandle(F)) {
1079 Relaxable.clear();
1080 continue;
1081 }
1082
1083 // To keep the effects local, prefer to relax instructions closest to
1084 // the align directive. This is purely about human understandability
1085 // of the resulting code. If we later find a reason to expand
1086 // particular instructions over others, we can adjust.
1087 unsigned RemainingSize = Asm->computeFragmentSize(F) - F.getFixedSize();
1088 Changed |= padInstsBackward(Relaxable, RemainingSize);
1089
1090 // If we're looking at a boundary align, make sure we don't try to pad
1091 // its target instructions for some following directive. Doing so would
1092 // break the alignment of the current boundary align.
1093 if (auto *BF = dyn_cast<MCBoundaryAlignFragment>(&F)) {
1094 cast<MCBoundaryAlignFragment>(F).setSize(RemainingSize);
1095 Changed = true;
1096 const MCFragment *LastFragment = BF->getLastFragment();
1097 if (!LastFragment)
1098 continue;
1099 while (&*I != LastFragment)
1100 ++I;
1101 }
1102 }
1103 }
1104
1105 return Changed;
1106}
1107
1108unsigned X86AsmBackend::getMaximumNopSize(const MCSubtargetInfo &STI) const {
1109 if (STI.hasFeature(X86::Is16Bit))
1110 return 4;
1111 if (!STI.hasFeature(X86::FeatureNOPL) && !STI.hasFeature(X86::Is64Bit))
1112 return 1;
1113 if (STI.hasFeature(X86::TuningFast7ByteNOP))
1114 return 7;
1115 if (STI.hasFeature(X86::TuningFast15ByteNOP))
1116 return 15;
1117 if (STI.hasFeature(X86::TuningFast11ByteNOP))
1118 return 11;
1119 // FIXME: handle 32-bit mode
1120 // 15-bytes is the longest single NOP instruction, but 10-bytes is
1121 // commonly the longest that can be efficiently decoded.
1122 return 10;
1123}
1124
1125/// Write a sequence of optimal nops to the output, covering \p Count
1126/// bytes.
1127/// \return - true on success, false on failure
1128bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count,
1129 const MCSubtargetInfo *STI) const {
1130 static const char Nops32Bit[10][11] = {
1131 // nop
1132 "\x90",
1133 // xchg %ax,%ax
1134 "\x66\x90",
1135 // nopl (%[re]ax)
1136 "\x0f\x1f\x00",
1137 // nopl 0(%[re]ax)
1138 "\x0f\x1f\x40\x00",
1139 // nopl 0(%[re]ax,%[re]ax,1)
1140 "\x0f\x1f\x44\x00\x00",
1141 // nopw 0(%[re]ax,%[re]ax,1)
1142 "\x66\x0f\x1f\x44\x00\x00",
1143 // nopl 0L(%[re]ax)
1144 "\x0f\x1f\x80\x00\x00\x00\x00",
1145 // nopl 0L(%[re]ax,%[re]ax,1)
1146 "\x0f\x1f\x84\x00\x00\x00\x00\x00",
1147 // nopw 0L(%[re]ax,%[re]ax,1)
1148 "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
1149 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1150 "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
1151 };
1152
1153 // 16-bit mode uses different nop patterns than 32-bit.
1154 static const char Nops16Bit[4][11] = {
1155 // nop
1156 "\x90",
1157 // xchg %eax,%eax
1158 "\x66\x90",
1159 // lea 0(%si),%si
1160 "\x8d\x74\x00",
1161 // lea 0w(%si),%si
1162 "\x8d\xb4\x00\x00",
1163 };
1164
1165 const char(*Nops)[11] =
1166 STI->hasFeature(X86::Is16Bit) ? Nops16Bit : Nops32Bit;
1167
1168 uint64_t MaxNopLength = (uint64_t)getMaximumNopSize(*STI);
1169
1170 // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
1171 // length.
1172 do {
1173 const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
1174 const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
1175 for (uint8_t i = 0; i < Prefixes; i++)
1176 OS << '\x66';
1177 const uint8_t Rest = ThisNopLength - Prefixes;
1178 if (Rest != 0)
1179 OS.write(Nops[Rest - 1], Rest);
1180 Count -= ThisNopLength;
1181 } while (Count != 0);
1182
1183 return true;
1184}
1185
1186/* *** */
1187
1188namespace {
1189
1190class ELFX86AsmBackend : public X86AsmBackend {
1191public:
1192 uint8_t OSABI;
1193 ELFX86AsmBackend(const X86MCOptions &CLOpts, const Target &T, uint8_t OSABI,
1194 const MCSubtargetInfo &STI)
1195 : X86AsmBackend(CLOpts, T, STI), OSABI(OSABI) {}
1196};
1197
1198class ELFX86_32AsmBackend : public ELFX86AsmBackend {
1199public:
1200 using ELFX86AsmBackend::ELFX86AsmBackend;
1201
1202 std::unique_ptr<MCObjectTargetWriter>
1203 createObjectTargetWriter() const override {
1204 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
1205 }
1206};
1207
1208class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
1209public:
1210 using ELFX86AsmBackend::ELFX86AsmBackend;
1211
1212 std::unique_ptr<MCObjectTargetWriter>
1213 createObjectTargetWriter() const override {
1214 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
1215 ELF::EM_X86_64);
1216 }
1217};
1218
1219class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
1220public:
1221 using ELFX86AsmBackend::ELFX86AsmBackend;
1222
1223 std::unique_ptr<MCObjectTargetWriter>
1224 createObjectTargetWriter() const override {
1225 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
1226 ELF::EM_IAMCU);
1227 }
1228};
1229
1230class ELFX86_64AsmBackend : public ELFX86AsmBackend {
1231public:
1232 using ELFX86AsmBackend::ELFX86AsmBackend;
1233
1234 std::unique_ptr<MCObjectTargetWriter>
1235 createObjectTargetWriter() const override {
1236 return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
1237 }
1238};
1239
1240class WindowsX86AsmBackend : public X86AsmBackend {
1241 bool Is64Bit;
1242
1243public:
1244 WindowsX86AsmBackend(const X86MCOptions &CLOpts, const Target &T,
1245 bool is64Bit, const MCSubtargetInfo &STI)
1246 : X86AsmBackend(CLOpts, T, STI), Is64Bit(is64Bit) {}
1247
1248 std::optional<MCFixupKind> getFixupKind(StringRef Name) const override {
1249 return StringSwitch<std::optional<MCFixupKind>>(Name)
1250 .Case("dir32", FK_Data_4)
1251 .Case("secrel32", FK_SecRel_4)
1252 .Case("secidx", FK_SecRel_2)
1253 .Default(MCAsmBackend::getFixupKind(Name));
1254 }
1255
1256 std::unique_ptr<MCObjectTargetWriter>
1257 createObjectTargetWriter() const override {
1258 return createX86WinCOFFObjectWriter(Is64Bit);
1259 }
1260};
1261
1262namespace CU {
1263
1264 /// Compact unwind encoding values.
1265 enum CompactUnwindEncodings {
1266 /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
1267 /// the return address, then [RE]SP is moved to [RE]BP.
1268 UNWIND_MODE_BP_FRAME = 0x01000000,
1269
1270 /// A frameless function with a small constant stack size.
1271 UNWIND_MODE_STACK_IMMD = 0x02000000,
1272
1273 /// A frameless function with a large constant stack size.
1274 UNWIND_MODE_STACK_IND = 0x03000000,
1275
1276 /// No compact unwind encoding is available.
1277 UNWIND_MODE_DWARF = 0x04000000,
1278
1279 /// Mask for encoding the frame registers.
1280 UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
1281
1282 /// Mask for encoding the frameless registers.
1283 UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
1284 };
1285
1286} // namespace CU
1287
1288class DarwinX86AsmBackend : public X86AsmBackend {
1289 const MCRegisterInfo &MRI;
1290
1291 /// Number of registers that can be saved in a compact unwind encoding.
1292 enum { CU_NUM_SAVED_REGS = 6 };
1293
1294 mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
1295 Triple TT;
1296 bool Is64Bit;
1297
1298 unsigned OffsetSize; ///< Offset of a "push" instruction.
1299 unsigned MoveInstrSize; ///< Size of a "move" instruction.
1300 unsigned StackDivide; ///< Amount to adjust stack size by.
1301protected:
1302 /// Size of a "push" instruction for the given register.
1303 unsigned PushInstrSize(MCRegister Reg) const {
1304 switch (Reg.id()) {
1305 case X86::EBX:
1306 case X86::ECX:
1307 case X86::EDX:
1308 case X86::EDI:
1309 case X86::ESI:
1310 case X86::EBP:
1311 case X86::RBX:
1312 case X86::RBP:
1313 return 1;
1314 case X86::R12:
1315 case X86::R13:
1316 case X86::R14:
1317 case X86::R15:
1318 return 2;
1319 }
1320 return 1;
1321 }
1322
1323private:
1324 /// Get the compact unwind number for a given register. The number
1325 /// corresponds to the enum lists in compact_unwind_encoding.h.
1326 int getCompactUnwindRegNum(unsigned Reg) const {
1327 static const MCPhysReg CU32BitRegs[7] = {
1328 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
1329 };
1330 static const MCPhysReg CU64BitRegs[] = {
1331 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
1332 };
1333 const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
1334 for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
1335 if (*CURegs == Reg)
1336 return Idx;
1337
1338 return -1;
1339 }
1340
1341 /// Return the registers encoded for a compact encoding with a frame
1342 /// pointer.
1343 uint32_t encodeCompactUnwindRegistersWithFrame() const {
1344 // Encode the registers in the order they were saved --- 3-bits per
1345 // register. The list of saved registers is assumed to be in reverse
1346 // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
1347 uint32_t RegEnc = 0;
1348 for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
1349 unsigned Reg = SavedRegs[i];
1350 if (Reg == 0) break;
1351
1352 int CURegNum = getCompactUnwindRegNum(Reg);
1353 if (CURegNum == -1) return ~0U;
1354
1355 // Encode the 3-bit register number in order, skipping over 3-bits for
1356 // each register.
1357 RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
1358 }
1359
1360 assert((RegEnc & 0x3FFFF) == RegEnc &&
1361 "Invalid compact register encoding!");
1362 return RegEnc;
1363 }
1364
1365 /// Create the permutation encoding used with frameless stacks. It is
1366 /// passed the number of registers to be saved and an array of the registers
1367 /// saved.
1368 uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
1369 // The saved registers are numbered from 1 to 6. In order to encode the
1370 // order in which they were saved, we re-number them according to their
1371 // place in the register order. The re-numbering is relative to the last
1372 // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
1373 // that order:
1374 //
1375 // Orig Re-Num
1376 // ---- ------
1377 // 6 6
1378 // 2 2
1379 // 4 3
1380 // 5 3
1381 //
1382 for (unsigned i = 0; i < RegCount; ++i) {
1383 int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
1384 if (CUReg == -1) return ~0U;
1385 SavedRegs[i] = CUReg;
1386 }
1387
1388 // Reverse the list.
1389 std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
1390
1391 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
1392 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
1393 unsigned Countless = 0;
1394 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
1395 if (SavedRegs[j] < SavedRegs[i])
1396 ++Countless;
1397
1398 RenumRegs[i] = SavedRegs[i] - Countless - 1;
1399 }
1400
1401 // Take the renumbered values and encode them into a 10-bit number.
1402 uint32_t permutationEncoding = 0;
1403 switch (RegCount) {
1404 case 6:
1405 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
1406 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
1407 + RenumRegs[4];
1408 break;
1409 case 5:
1410 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
1411 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
1412 + RenumRegs[5];
1413 break;
1414 case 4:
1415 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
1416 + 3 * RenumRegs[4] + RenumRegs[5];
1417 break;
1418 case 3:
1419 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
1420 + RenumRegs[5];
1421 break;
1422 case 2:
1423 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
1424 break;
1425 case 1:
1426 permutationEncoding |= RenumRegs[5];
1427 break;
1428 }
1429
1430 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
1431 "Invalid compact register encoding!");
1432 return permutationEncoding;
1433 }
1434
1435public:
1436 DarwinX86AsmBackend(const X86MCOptions &CLOpts, const Target &T,
1437 const MCRegisterInfo &MRI, const MCSubtargetInfo &STI)
1438 : X86AsmBackend(CLOpts, T, STI), MRI(MRI), TT(STI.getTargetTriple()),
1439 Is64Bit(TT.isX86_64()) {
1440 memset(SavedRegs, 0, sizeof(SavedRegs));
1441 OffsetSize = Is64Bit ? 8 : 4;
1442 MoveInstrSize = Is64Bit ? 3 : 2;
1443 StackDivide = Is64Bit ? 8 : 4;
1444 }
1445
1446 std::unique_ptr<MCObjectTargetWriter>
1447 createObjectTargetWriter() const override {
1448 uint32_t CPUType = cantFail(MachO::getCPUType(TT));
1449 uint32_t CPUSubType = cantFail(MachO::getCPUSubType(TT));
1450 return createX86MachObjectWriter(Is64Bit, CPUType, CPUSubType);
1451 }
1452
1453 /// Implementation of algorithm to generate the compact unwind encoding
1454 /// for the CFI instructions.
1455 uint64_t generateCompactUnwindEncoding(const MCDwarfFrameInfo *FI,
1456 const MCContext *Ctxt) const override {
1457 if (Ctxt->emitDwarfUnwindInfo() == EmitDwarfUnwindType::DwarfOnly)
1458 return CU::UNWIND_MODE_DWARF;
1459
1460 // Signal frames cannot be encoded in compact unwind.
1461 if (FI->IsSignalFrame)
1462 return CU::UNWIND_MODE_DWARF;
1463
1465 if (Instrs.empty()) return 0;
1466 if (!isDarwinCanonicalPersonality(FI->Personality) &&
1468 return CU::UNWIND_MODE_DWARF;
1469
1470 // Reset the saved registers.
1471 unsigned SavedRegIdx = 0;
1472 memset(SavedRegs, 0, sizeof(SavedRegs));
1473
1474 bool HasFP = false;
1475
1476 // Encode that we are using EBP/RBP as the frame pointer.
1477 uint64_t CompactUnwindEncoding = 0;
1478
1479 unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
1480 unsigned InstrOffset = 0;
1481 unsigned StackAdjust = 0;
1482 uint64_t StackSize = 0;
1483 int64_t MinAbsOffset = std::numeric_limits<int64_t>::max();
1484
1485 for (const MCCFIInstruction &Inst : Instrs) {
1486 switch (Inst.getOperation()) {
1487 default:
1488 // Any other CFI directives indicate a frame that we aren't prepared
1489 // to represent via compact unwind, so just bail out.
1490 return CU::UNWIND_MODE_DWARF;
1492 // Defines a frame pointer. E.g.
1493 //
1494 // movq %rsp, %rbp
1495 // L0:
1496 // .cfi_def_cfa_register %rbp
1497 //
1498 HasFP = true;
1499
1500 // If the frame pointer is other than esp/rsp, we do not have a way to
1501 // generate a compact unwinding representation, so bail out.
1502 if (*MRI.getLLVMRegNum(Inst.getRegister(), true) !=
1503 (Is64Bit ? X86::RBP : X86::EBP))
1504 return CU::UNWIND_MODE_DWARF;
1505
1506 // Reset the counts.
1507 memset(SavedRegs, 0, sizeof(SavedRegs));
1508 StackAdjust = 0;
1509 SavedRegIdx = 0;
1510 MinAbsOffset = std::numeric_limits<int64_t>::max();
1511 InstrOffset += MoveInstrSize;
1512 break;
1513 }
1515 // Defines a new offset for the CFA. E.g.
1516 //
1517 // With frame:
1518 //
1519 // pushq %rbp
1520 // L0:
1521 // .cfi_def_cfa_offset 16
1522 //
1523 // Without frame:
1524 //
1525 // subq $72, %rsp
1526 // L0:
1527 // .cfi_def_cfa_offset 80
1528 //
1529 StackSize = Inst.getOffset() / StackDivide;
1530 break;
1531 }
1533 // Defines a "push" of a callee-saved register. E.g.
1534 //
1535 // pushq %r15
1536 // pushq %r14
1537 // pushq %rbx
1538 // L0:
1539 // subq $120, %rsp
1540 // L1:
1541 // .cfi_offset %rbx, -40
1542 // .cfi_offset %r14, -32
1543 // .cfi_offset %r15, -24
1544 //
1545 if (SavedRegIdx == CU_NUM_SAVED_REGS)
1546 // If there are too many saved registers, we cannot use a compact
1547 // unwind encoding.
1548 return CU::UNWIND_MODE_DWARF;
1549
1550 MCRegister Reg = *MRI.getLLVMRegNum(Inst.getRegister(), true);
1551 SavedRegs[SavedRegIdx++] = Reg.id();
1552 StackAdjust += OffsetSize;
1553 MinAbsOffset = std::min(MinAbsOffset, std::abs(Inst.getOffset()));
1554 InstrOffset += PushInstrSize(Reg);
1555 break;
1556 }
1557 }
1558 }
1559
1560 StackAdjust /= StackDivide;
1561
1562 if (HasFP) {
1563 if ((StackAdjust & 0xFF) != StackAdjust)
1564 // Offset was too big for a compact unwind encoding.
1565 return CU::UNWIND_MODE_DWARF;
1566
1567 // We don't attempt to track a real StackAdjust, so if the saved registers
1568 // aren't adjacent to rbp we can't cope.
1569 if (SavedRegIdx != 0 && MinAbsOffset != 3 * (int)OffsetSize)
1570 return CU::UNWIND_MODE_DWARF;
1571
1572 // Get the encoding of the saved registers when we have a frame pointer.
1573 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
1574 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
1575
1576 CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
1577 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
1578 CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
1579 } else {
1580 SubtractInstrIdx += InstrOffset;
1581 ++StackAdjust;
1582
1583 if ((StackSize & 0xFF) == StackSize) {
1584 // Frameless stack with a small stack size.
1585 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
1586
1587 // Encode the stack size.
1588 CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
1589 } else {
1590 if ((StackAdjust & 0x7) != StackAdjust)
1591 // The extra stack adjustments are too big for us to handle.
1592 return CU::UNWIND_MODE_DWARF;
1593
1594 // Frameless stack with an offset too large for us to encode compactly.
1595 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
1596
1597 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
1598 // instruction.
1599 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
1600
1601 // Encode any extra stack adjustments (done via push instructions).
1602 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
1603 }
1604
1605 // Encode the number of registers saved. (Reverse the list first.)
1606 std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
1607 CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
1608
1609 // Get the encoding of the saved registers when we don't have a frame
1610 // pointer.
1611 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
1612 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
1613
1614 // Encode the register encoding.
1615 CompactUnwindEncoding |=
1616 RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
1617 }
1618
1619 return CompactUnwindEncoding;
1620 }
1621};
1622
1623} // end anonymous namespace
1624
1626 const MCSubtargetInfo &STI,
1627 const MCRegisterInfo &MRI,
1628 const MCTargetOptions &Options) {
1629 const Triple &TheTriple = STI.getTargetTriple();
1630 const X86MCOptions &CLOpts = X86_MC::getCLOpts(Options);
1631 if (TheTriple.isOSBinFormatMachO())
1632 return new DarwinX86AsmBackend(CLOpts, T, MRI, STI);
1633
1634 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
1635 return new WindowsX86AsmBackend(CLOpts, T, false, STI);
1636
1637 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1638
1639 if (TheTriple.isOSIAMCU())
1640 return new ELFX86_IAMCUAsmBackend(CLOpts, T, OSABI, STI);
1641
1642 return new ELFX86_32AsmBackend(CLOpts, T, OSABI, STI);
1643}
1644
1646 const MCSubtargetInfo &STI,
1647 const MCRegisterInfo &MRI,
1648 const MCTargetOptions &Options) {
1649 const Triple &TheTriple = STI.getTargetTriple();
1650 const X86MCOptions &CLOpts = X86_MC::getCLOpts(Options);
1651 if (TheTriple.isOSBinFormatMachO())
1652 return new DarwinX86AsmBackend(CLOpts, T, MRI, STI);
1653
1654 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
1655 return new WindowsX86AsmBackend(CLOpts, T, true, STI);
1656
1657 if (TheTriple.isUEFI()) {
1658 assert(TheTriple.isOSBinFormatCOFF() &&
1659 "Only COFF format is supported in UEFI environment.");
1660 return new WindowsX86AsmBackend(CLOpts, T, true, STI);
1661 }
1662
1663 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1664
1665 if (TheTriple.isX32())
1666 return new ELFX86_X32AsmBackend(CLOpts, T, OSABI, STI);
1667 return new ELFX86_64AsmBackend(CLOpts, T, OSABI, STI);
1668}
1669
1670namespace {
1671class X86ELFStreamer : public MCELFStreamer {
1672public:
1673 X86ELFStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> TAB,
1674 std::unique_ptr<MCObjectWriter> OW,
1675 std::unique_ptr<MCCodeEmitter> Emitter)
1676 : MCELFStreamer(Context, std::move(TAB), std::move(OW),
1677 std::move(Emitter)) {}
1678
1679 void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
1680};
1681} // end anonymous namespace
1682
1683void X86ELFStreamer::emitInstruction(const MCInst &Inst,
1684 const MCSubtargetInfo &STI) {
1685 X86_MC::emitInstruction(*this, Inst, STI);
1686}
1687
1689 std::unique_ptr<MCAsmBackend> &&MAB,
1690 std::unique_ptr<MCObjectWriter> &&MOW,
1691 std::unique_ptr<MCCodeEmitter> &&MCE) {
1692 return new X86ELFStreamer(Context, std::move(MAB), std::move(MOW),
1693 std::move(MCE));
1694}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:347
dxil container DXContainer Global Emitter
IRTranslator LLVM IR MI
static LVOptions Options
Definition LVOptions.cpp:25
static unsigned getRelaxedOpcode(unsigned Opcode)
This file declares the MCLFIRewriter class, an abstract class that encapsulates the rewriting logic f...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define T
if(PassOpts->AAPipeline)
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
static MCInstrInfo * createMCInstrInfo()
static unsigned getRelaxedOpcodeBranch(unsigned Opcode, bool Is16BitMode=false)
static X86::SecondMacroFusionInstKind classifySecondInstInMacroFusion(const MCInst &MI, const MCInstrInfo &MCII)
static bool isRIPRelative(const MCInst &MI, const MCInstrInfo &MCII)
Check if the instruction uses RIP relative addressing.
static bool mayHaveInterruptDelaySlot(unsigned InstOpcode)
X86 has certain instructions which enable interrupts exactly one instruction after the instruction wh...
static bool isFirstMacroFusibleInst(const MCInst &Inst, const MCInstrInfo &MCII)
Check if the instruction is valid as the first instruction in macro fusion.
constexpr char GotSymName[]
static X86::CondCode getCondFromBranch(const MCInst &MI, const MCInstrInfo &MCII)
static unsigned getRelaxedOpcode(const MCInst &MI, bool Is16BitMode)
static unsigned getFixupKindSize(unsigned Kind)
static bool isRelaxableBranch(unsigned Opcode)
static bool isPrefix(unsigned Opcode, const MCInstrInfo &MCII)
Check if the instruction is a prefix.
static bool hasVariantSymbol(const MCInst &MI)
Check if the instruction has a variant symbol operand.
static bool is64Bit(const char *name)
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Generic interface to target specific assembler backends.
virtual MCFixupKindInfo getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
virtual std::optional< MCFixupKind > getFixupKind(StringRef Name) const
Map a relocation name used in .reloc to a fixup kind.
Represents required padding such that a particular other set of fragments does not cross a particular...
Definition MCSection.h:539
void setSize(uint64_t Value)
Definition MCSection.h:559
const MCFragment * getLastFragment() const
Definition MCSection.h:567
void setLastFragment(const MCFragment *F)
Definition MCSection.h:568
Context object for machine code objects.
Definition MCContext.h:84
LLVM_ABI bool emitCompactUnwindNonCanonical() const
LLVM_ABI EmitDwarfUnwindType emitDwarfUnwindInfo() const
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
@ SymbolRef
References to labels and assigned expressions.
Definition MCExpr.h:43
ExprKind getKind() const
Definition MCExpr.h:85
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition MCFixup.h:65
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, bool PCRel=false)
Consider bit fields if we need more flags.
Definition MCFixup.h:90
bool getAllowAutoPadding() const
Definition MCSection.h:209
void setAllowAutoPadding(bool V)
Definition MCSection.h:210
MCInst getInst() const
Definition MCSection.h:748
unsigned getOpcode() const
Definition MCSection.h:249
MCSection * getParent() const
Definition MCSection.h:181
LLVM_ABI void setVarFixups(ArrayRef< MCFixup > Fixups)
MCFragment * getNext() const
Definition MCSection.h:177
ArrayRef< MCOperand > getOperands() const
Definition MCSection.h:743
size_t getVarSize() const
Definition MCSection.h:224
LLVM_ABI void setVarContents(ArrayRef< char > Contents)
Definition MCSection.cpp:61
MutableArrayRef< char > getVarContents()
Definition MCSection.h:714
const MCSubtargetInfo * getSubtargetInfo() const
Retrieve the MCSubTargetInfo in effect when the instruction was encoded.
Definition MCSection.h:197
MutableArrayRef< MCFixup > getVarFixups()
Definition MCSection.h:734
void setInst(const MCInst &Inst)
Definition MCSection.h:757
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getOpcode() const
Definition MCInst.h:202
void setOpcode(unsigned Op)
Definition MCInst.h:201
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:210
Describe properties that are true of each instruction in the target description file.
bool isConditionalBranch() const
Return true if this is a branch which may fall through to the next instruction or may transfer contro...
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
virtual bool rewriteInst(const MCInst &Inst, MCStreamer &Out, const MCSubtargetInfo &STI)=0
Streaming object file generation interface.
FT * newSpecialFragment(Args &&...args)
MCAssembler & getAssembler()
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:73
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
void ensureMinAlignment(Align MinAlignment)
Makes sure that Alignment is at least MinAlignment.
Definition MCSection.h:668
bool isText() const
Definition MCSection.h:651
Streaming machine code generation interface.
Definition MCStreamer.h:222
MCFragment * getCurrentFragment() const
Definition MCStreamer.h:449
SMLoc getStartTokLoc() const
Definition MCStreamer.h:314
MCLFIRewriter * getLFIRewriter()
Definition MCStreamer.h:320
size_t getCurFragSize() const
Definition MCStreamer.h:458
bool getAllowAutoPadding() const
Definition MCStreamer.h:341
MCSection * getCurrentSectionOnly() const
Definition MCStreamer.h:438
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
iterator end() const
Definition ArrayRef.h:339
iterator begin() const
Definition ArrayRef.h:338
constexpr unsigned id() const
Definition Register.h:100
void push_back(const T &Elt)
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isX86_64() const
Tests whether the target is x86 (64-bit).
Definition Triple.h:1211
bool isX32() const
Tests whether the target is X32.
Definition Triple.h:1242
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition Triple.h:878
OSType getOS() const
Get the parsed operating system type of this triple.
Definition Triple.h:526
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition Triple.h:872
bool isUEFI() const
Tests whether the OS is UEFI.
Definition Triple.h:777
bool isOSWindows() const
Tests whether the OS is Windows.
Definition Triple.h:780
bool isOSIAMCU() const
Definition Triple.h:759
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:869
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
raw_ostream & write(unsigned char C)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Expected< uint32_t > getCPUSubType(const Triple &T)
Definition MachO.cpp:109
LLVM_ABI Expected< uint32_t > getCPUType(const Triple &T)
Definition MachO.cpp:89
VE::Fixups getFixupKind(uint8_t S)
bool isPrefix(uint64_t TSFlags)
int getMemoryOperandIdx(const MCInstrDesc &Desc)
@ RawFrmDstSrc
RawFrmDstSrc - This form is for instructions that use the source index register SI/ESI/RSI with a pos...
@ RawFrmSrc
RawFrmSrc - This form is for instructions that use the source index register SI/ESI/RSI with a possib...
@ RawFrmMemOffs
RawFrmMemOffs - This form is for instructions that store an absolute memory offset as an immediate wi...
const X86MCOptions & getCLOpts(const MCTargetOptions &Options)
void emitPrefix(MCCodeEmitter &MCE, const MCInst &MI, SmallVectorImpl< char > &CB, const MCSubtargetInfo &STI)
void emitInstruction(MCObjectStreamer &, const MCInst &Inst, const MCSubtargetInfo &STI)
FirstMacroFusionInstKind classifyFirstOpcodeInMacroFusion(unsigned Opcode)
AlignBranchBoundaryKind
Defines the possible values of the branch boundary alignment mask.
@ AlignBranchIndirect
SecondMacroFusionInstKind
EncodingOfSegmentOverridePrefix getSegmentOverridePrefixForReg(MCRegister Reg)
Given a segment register, return the encoding of the segment override prefix for it.
FirstMacroFusionInstKind
unsigned getOpcodeForLongImmediateForm(unsigned Opcode)
bool isMacroFused(FirstMacroFusionInstKind FirstKind, SecondMacroFusionInstKind SecondKind)
@ reloc_riprel_4byte_movq_load_rex2
@ reloc_signed_4byte_relax
@ reloc_branch_4byte_pcrel
@ NumTargetFixupKinds
@ reloc_riprel_4byte_relax
@ reloc_riprel_4byte_relax_evex
@ reloc_riprel_4byte_relax_rex
@ reloc_global_offset_table
@ reloc_riprel_4byte_movq_load
@ reloc_riprel_4byte_relax_rex2
bool isRelocation(MCFixupKind FixupKind)
Definition MCFixup.h:134
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MCAsmBackend * createX86_64AsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
std::unique_ptr< MCObjectTargetWriter > createX86WinCOFFObjectWriter(bool Is64Bit)
Construct an X86 Win COFF object writer.
constexpr MCFixupKind FirstTargetFixupKind
Definition MCFixup.h:49
Op::Description Desc
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint16_t MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition MCFixup.h:22
MCStreamer * createX86ELFStreamer(const Triple &T, MCContext &Context, std::unique_ptr< MCAsmBackend > &&MAB, std::unique_ptr< MCObjectWriter > &&MOW, std::unique_ptr< MCCodeEmitter > &&MCE)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ FK_SecRel_2
A two-byte section relative fixup.
Definition MCFixup.h:44
@ FK_Data_8
A eight-byte fixup.
Definition MCFixup.h:41
@ FK_Data_1
A one-byte fixup.
Definition MCFixup.h:38
@ FK_Data_4
A four-byte fixup.
Definition MCFixup.h:40
@ FK_SecRel_8
A eight-byte section relative fixup.
Definition MCFixup.h:46
@ FK_NONE
A no-op fixup.
Definition MCFixup.h:37
@ FK_SecRel_4
A four-byte section relative fixup.
Definition MCFixup.h:45
@ FK_SecRel_1
A one-byte section relative fixup.
Definition MCFixup.h:43
@ FK_Data_2
A two-byte fixup.
Definition MCFixup.h:39
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
std::unique_ptr< MCObjectTargetWriter > createX86MachObjectWriter(bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype)
Construct an X86 Mach-O object writer.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ArrayRef(const T &OneElt) -> ArrayRef< T >
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:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::unique_ptr< MCObjectTargetWriter > createX86ELFObjectWriter(bool IsELF64, uint8_t OSABI, uint16_t EMachine)
Construct an X86 ELF object writer.
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
Definition Alignment.h:105
endianness
Definition bit.h:71
MCAsmBackend * createX86_32AsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
constexpr MCFixupKind FirstLiteralRelocationKind
Definition MCFixup.h:32
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
const MCSymbol * Personality
Definition MCDwarf.h:907
std::vector< MCCFIInstruction > Instructions
Definition MCDwarf.h:909