42class X86AlignBranchKind {
44 uint8_t AlignBranchKind = 0;
47 void operator=(
const std::string &Val) {
51 StringRef(Val).split(BranchTypes,
'+', -1,
false);
52 for (
auto BranchType : BranchTypes) {
53 if (BranchType ==
"fused")
55 else if (BranchType ==
"jcc")
57 else if (BranchType ==
"jmp")
59 else if (BranchType ==
"call")
61 else if (BranchType ==
"ret")
63 else if (BranchType ==
"indirect")
67 <<
" to -x86-align-branch=; each element must be one of: fused, "
68 "jcc, jmp, call, ret, indirect.(plus separated)\n";
73 operator uint8_t()
const {
return AlignBranchKind; }
77X86AlignBranchKind X86AlignBranchKindLoc;
80 "x86-align-branch-boundary",
cl::init(0),
82 "Control how the assembler should align branches with NOP. If the "
83 "boundary's size is not 0, it should be a power of 2 and no less "
84 "than 32. Branches will be aligned to prevent from being across or "
85 "against the boundary of specified size. The default value 0 does not "
91 "Specify types of branches to align (plus separated list of types):"
92 "\njcc indicates conditional jumps"
93 "\nfused indicates fused conditional jumps"
94 "\njmp indicates direct unconditional jumps"
95 "\ncall indicates direct and indirect calls"
96 "\nret indicates rets"
97 "\nindirect indicates indirect unconditional jumps"),
101 "x86-branches-within-32B-boundaries",
cl::init(
false),
103 "Align selected instructions to mitigate negative performance impact "
104 "of Intel's micro code update for errata skx102. May break "
105 "assumptions about labels corresponding to particular instructions, "
106 "and should be used with caution."));
109 "x86-pad-max-prefix-size",
cl::init(0),
110 cl::desc(
"Maximum number of prefixes to use for padding"));
114 cl::desc(
"Pad previous instructions to implement align directives"));
118 cl::desc(
"Pad previous instructions to implement branch alignment"));
121 const MCSubtargetInfo &STI;
122 std::unique_ptr<const MCInstrInfo> MCII;
123 X86AlignBranchKind AlignBranchType;
125 unsigned TargetPrefixMax = 0;
128 unsigned PrevInstOpcode = 0;
129 bool PrefixEndsBundleLock =
false;
130 MCBoundaryAlignFragment *PendingBA =
nullptr;
131 std::pair<MCFragment *, size_t> PrevInstPosition;
133 uint8_t determinePaddingPrefix(
const MCInst &Inst)
const;
134 bool isMacroFused(
const MCInst &Cmp,
const MCInst &Jcc)
const;
135 bool needAlign(
const MCInst &Inst)
const;
136 bool canPadBranches(MCObjectStreamer &OS)
const;
137 bool canPadInst(
const MCInst &Inst, MCObjectStreamer &OS)
const;
138 void emitInstructionBeginBundle(MCObjectStreamer &OS);
139 void emitInstructionEndBundle(MCObjectStreamer &OS);
142 X86AsmBackend(
const Target &
T,
const MCSubtargetInfo &STI)
145 if (X86AlignBranchWithin32BBoundaries) {
156 if (X86AlignBranchBoundary.getNumOccurrences())
158 if (X86AlignBranch.getNumOccurrences())
159 AlignBranchType = X86AlignBranchKindLoc;
160 if (X86PadMaxPrefixSize.getNumOccurrences())
161 TargetPrefixMax = X86PadMaxPrefixSize;
165 AllowEnhancedRelaxation =
166 AllowAutoPadding && TargetPrefixMax != 0 && X86PadForBranchAlign;
167 AllowBundling =
true;
171 void reset()
override {
174 PrefixEndsBundleLock =
false;
176 PrevInstPosition = {};
179 void emitInstructionBegin(MCObjectStreamer &OS,
const MCInst &Inst,
180 const MCSubtargetInfo &STI);
181 void emitInstructionEnd(MCObjectStreamer &OS,
const MCInst &Inst);
184 std::optional<MCFixupKind>
getFixupKind(StringRef Name)
const override;
186 MCFixupKindInfo getFixupKindInfo(
MCFixupKind Kind)
const override;
188 std::optional<bool> evaluateFixup(
const MCFragment &, MCFixup &, MCValue &,
189 uint64_t &)
override;
190 void applyFixup(
const MCFragment &,
const MCFixup &,
const MCValue &Target,
191 uint8_t *
Data, uint64_t
Value,
bool IsResolved)
override;
194 const MCSubtargetInfo &STI)
const override;
196 bool fixupNeedsRelaxationAdvanced(
const MCFragment &,
const MCFixup &,
197 const MCValue &, uint64_t,
198 bool)
const override;
200 void relaxInstruction(MCInst &Inst,
201 const MCSubtargetInfo &STI)
const override;
203 bool padInstructionViaRelaxation(MCFragment &RF, MCCodeEmitter &
Emitter,
204 unsigned &RemainingSize)
const;
206 bool padInstructionViaPrefix(MCFragment &RF, MCCodeEmitter &
Emitter,
207 unsigned &RemainingSize)
const;
209 bool padInstructionEncoding(MCFragment &RF, MCCodeEmitter &
Emitter,
210 unsigned &RemainingSize)
const;
212 bool finishLayout()
const override;
214 bool padInstsBackward(SmallVectorImpl<MCFragment *> &Relaxable,
215 unsigned &RemainingSize)
const;
216 bool foldBundlePad(
const MCAssembler &Asm, MCBoundaryAlignFragment &BF,
217 SmallVectorImpl<MCFragment *> &Relaxable)
const;
218 bool optimizeBundleNops(
const MCAssembler &Asm)
const;
220 unsigned getMaximumNopSize(
const MCSubtargetInfo &STI)
const override;
222 bool writeNopData(raw_ostream &OS, uint64_t
Count,
223 const MCSubtargetInfo *STI)
const override;
228 return Opcode == X86::JCC_1 || Opcode == X86::JMP_1;
232 bool Is16BitMode =
false) {
237 return (Is16BitMode) ? X86::JCC_2 : X86::JCC_4;
239 return (Is16BitMode) ? X86::JMP_2 : X86::JMP_4;
244 unsigned Opcode =
MI.getOpcode();
251 unsigned Opcode =
MI.getOpcode();
258 MI.getOperand(
Desc.getNumOperands() - 1).getImm());
266 return classifySecondCondCodeInMacroFusion(CC);
273 if (MemoryOperand < 0)
276 MCRegister BaseReg =
MI.getOperand(BaseRegNum).getReg();
277 return (BaseReg == X86::RIP);
305uint8_t X86AsmBackend::determinePaddingPrefix(
const MCInst &Inst)
const {
307 "Prefixes can be added only in 32-bit or 64-bit mode.");
309 uint64_t TSFlags =
Desc.TSFlags;
314 MCRegister SegmentReg;
315 if (MemoryOperand >= 0) {
348 if (MemoryOperand >= 0) {
351 if (BaseReg == X86::ESP || BaseReg == X86::EBP)
358bool X86AsmBackend::isMacroFused(
const MCInst &Cmp,
const MCInst &Jcc)
const {
359 const MCInstrDesc &InstDesc = MCII->get(Jcc.
getOpcode());
373 for (
auto &Operand :
MI) {
374 if (!Operand.isExpr())
376 const MCExpr &Expr = *Operand.getExpr();
388 switch (InstOpcode) {
407bool X86AsmBackend::canPadInst(
const MCInst &Inst, MCObjectStreamer &OS)
const {
418 if (
isPrefix(PrevInstOpcode, *MCII))
432 Offset != PrevInstPosition.second))
438bool X86AsmBackend::canPadBranches(MCObjectStreamer &OS)
const {
441 assert(allowAutoPadding() &&
"incorrect initialization!");
455bool X86AsmBackend::needAlign(
const MCInst &Inst)
const {
457 return (
Desc.isConditionalBranch() &&
459 (
Desc.isUnconditionalBranch() &&
463 (
Desc.isIndirectBranch() &&
470 if (
LLVM_LIKELY(!AutoPadding && !X86PadForAlign)) {
471 S.MCObjectStreamer::emitInstruction(Inst, STI);
475 auto &Backend =
static_cast<X86AsmBackend &
>(S.
getAssembler().getBackend());
476 Backend.emitInstructionBegin(S, Inst, STI);
477 S.MCObjectStreamer::emitInstruction(Inst, STI);
478 Backend.emitInstructionEnd(S, Inst);
485 assert(Asm->isBundlingEnabled());
491 "instruction prefix cannot be the last "
492 "instruction of a .bundle_lock group");
505 Asm->getBundleAlign(), STI);
516void X86AsmBackend::emitInstructionEndBundle(MCObjectStreamer &OS) {
520 PrefixEndsBundleLock =
isPrefix(PrevInstOpcode, *MCII);
523 PrefixEndsBundleLock =
false;
524 assert(PendingBA &&
"MCBoundaryAlignFragment is expected for every "
525 "instruction if it is not bundle-locked");
529 if (!
isPrefix(PrevInstOpcode, *MCII))
534void X86AsmBackend::emitInstructionBegin(MCObjectStreamer &OS,
536 const MCSubtargetInfo &STI) {
537 bool CanPadInst = canPadInst(Inst, OS);
538 if (
Asm->isBundlingEnabled()) {
539 emitInstructionBeginBundle(OS);
546 if (!canPadBranches(OS))
562 auto *NextFragment = PendingBA->
getNext();
563 assert(NextFragment &&
"NextFragment should not be null");
602void X86AsmBackend::emitInstructionEnd(MCObjectStreamer &OS,
603 const MCInst &Inst) {
608 if (
Asm->isBundlingEnabled())
609 return emitInstructionEndBundle(OS);
611 if (!canPadBranches(OS))
617 if (!needAlign(Inst) || !PendingBA)
634std::optional<MCFixupKind> X86AsmBackend::getFixupKind(StringRef Name)
const {
638 Type = llvm::StringSwitch<unsigned>(Name)
639#define ELF_RELOC(X, Y) .Case(#X, Y)
640#include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
642 .Case(
"BFD_RELOC_NONE", ELF::R_X86_64_NONE)
643 .Case(
"BFD_RELOC_8", ELF::R_X86_64_8)
644 .Case(
"BFD_RELOC_16", ELF::R_X86_64_16)
645 .Case(
"BFD_RELOC_32", ELF::R_X86_64_32)
646 .Case(
"BFD_RELOC_64", ELF::R_X86_64_64)
649 Type = llvm::StringSwitch<unsigned>(Name)
650#define ELF_RELOC(X, Y) .Case(#X, Y)
651#include "llvm/BinaryFormat/ELFRelocs/i386.def"
653 .Case(
"BFD_RELOC_NONE", ELF::R_386_NONE)
654 .Case(
"BFD_RELOC_8", ELF::R_386_8)
655 .Case(
"BFD_RELOC_16", ELF::R_386_16)
656 .Case(
"BFD_RELOC_32", ELF::R_386_32)
666MCFixupKindInfo X86AsmBackend::getFixupKindInfo(
MCFixupKind Kind)
const {
669 {
"reloc_riprel_4byte", 0, 32, 0},
670 {
"reloc_riprel_4byte_movq_load", 0, 32, 0},
671 {
"reloc_riprel_4byte_movq_load_rex2", 0, 32, 0},
672 {
"reloc_riprel_4byte_relax", 0, 32, 0},
673 {
"reloc_riprel_4byte_relax_rex", 0, 32, 0},
674 {
"reloc_riprel_4byte_relax_rex2", 0, 32, 0},
675 {
"reloc_riprel_4byte_relax_evex", 0, 32, 0},
676 {
"reloc_signed_4byte", 0, 32, 0},
677 {
"reloc_signed_4byte_relax", 0, 32, 0},
678 {
"reloc_global_offset_table", 0, 32, 0},
679 {
"reloc_branch_4byte_pcrel", 0, 32, 0},
733std::optional<bool> X86AsmBackend::evaluateFixup(
const MCFragment &,
736 if (
Fixup.isPCRel()) {
737 switch (
Fixup.getKind()) {
760void X86AsmBackend::applyFixup(
const MCFragment &
F,
const MCFixup &
Fixup,
761 const MCValue &Target, uint8_t *
Data,
762 uint64_t
Value,
bool IsResolved) {
765 if (
Target.getSpecifier())
767 maybeAddReloc(
F,
Fixup, Target,
Value, IsResolved);
790 "value of " + Twine(int64_t(
Value)) +
791 " is too large for field of " + Twine(
Size) +
792 (
Size == 1 ?
" byte" :
" bytes"));
795 for (
unsigned i = 0; i !=
Size; ++i)
799bool X86AsmBackend::mayNeedRelaxation(
unsigned Opcode,
801 const MCSubtargetInfo &STI)
const {
802 unsigned SkipOperands = X86::isCCMPCC(Opcode) ? 2 : 0;
808bool X86AsmBackend::fixupNeedsRelaxationAdvanced(
const MCFragment &
F,
809 const MCFixup &
Fixup,
810 const MCValue &Target,
812 bool Resolved)
const {
821 int64_t Slack =
Asm->isBundlingEnabled() && TargetPrefixMax != 0 &&
823 ?
Asm->getBundleAlign().value()
838void X86AsmBackend::relaxInstruction(MCInst &Inst,
839 const MCSubtargetInfo &STI)
const {
841 bool Is16BitMode = STI.
hasFeature(X86::Is16Bit);
847bool X86AsmBackend::padInstructionViaPrefix(MCFragment &RF,
849 unsigned &RemainingSize)
const {
864 const unsigned MaxPossiblePad = std::min(15 - OldSize, RemainingSize);
865 const unsigned RemainingPrefixSize = [&]() ->
unsigned {
866 SmallString<15>
Code;
868 assert(
Code.size() < 15 &&
"The number of prefixes must be less than 15.");
875 unsigned ExistingPrefixSize =
Code.size();
876 if (TargetPrefixMax <= ExistingPrefixSize)
878 return TargetPrefixMax - ExistingPrefixSize;
880 const unsigned PrefixBytesToAdd =
881 std::min(MaxPossiblePad, RemainingPrefixSize);
882 if (PrefixBytesToAdd == 0)
887 SmallString<256>
Code;
888 Code.append(PrefixBytesToAdd, Prefix);
894 F.setOffset(PrefixBytesToAdd +
F.getOffset());
896 RemainingSize -= PrefixBytesToAdd;
900bool X86AsmBackend::padInstructionViaRelaxation(MCFragment &RF,
902 unsigned &RemainingSize)
const {
913 SmallString<15>
Code;
916 const unsigned NewSize =
Code.size();
917 assert(NewSize >= OldSize &&
"size decrease during relaxation?");
918 unsigned Delta = NewSize - OldSize;
919 if (Delta > RemainingSize)
924 RemainingSize -= Delta;
928bool X86AsmBackend::padInstructionEncoding(MCFragment &RF,
930 unsigned &RemainingSize)
const {
932 if (RemainingSize != 0)
933 Changed |= padInstructionViaRelaxation(RF,
Emitter, RemainingSize);
934 if (RemainingSize != 0)
939bool X86AsmBackend::padInstsBackward(SmallVectorImpl<MCFragment *> &Relaxable,
940 unsigned &RemainingSize)
const {
942 while (!Relaxable.
empty() && RemainingSize != 0) {
947 Changed |= padInstructionEncoding(RF,
Asm->getEmitter(), RemainingSize);
967bool X86AsmBackend::foldBundlePad(
968 const MCAssembler &Asm, MCBoundaryAlignFragment &BF,
969 SmallVectorImpl<MCFragment *> &Relaxable)
const {
970 const uint64_t BundleSize =
Asm.getBundleAlign().value();
971 const uint64_t PadStart =
Asm.getFragmentOffset(BF);
972 unsigned Remaining = BF.
getSize();
977 std::min<uint64_t>(Remaining, BundleSize - PadStart % BundleSize);
978 unsigned Left = Budget;
980 Remaining -= Budget -
Left;
986 uint64_t GroupSize = 0;
988 GroupSize +=
Asm.computeFragmentSize(*
F);
992 if (GroupSize < BundleSize) {
993 Left = Budget = std::min<uint64_t>(Remaining, BundleSize - GroupSize);
1000 Remaining -= Budget -
Left;
1008bool X86AsmBackend::optimizeBundleNops(
const MCAssembler &Asm)
const {
1009 const uint64_t BundleSize =
Asm.getBundleAlign().value();
1011 for (MCSection &Sec : Asm) {
1019 const MCFragment *ResumeAfter =
nullptr;
1020 for (MCFragment &
F : Sec) {
1022 if (&
F == ResumeAfter)
1023 ResumeAfter =
nullptr;
1027 if (!Relaxable.
empty() &&
1028 Asm.getFragmentOffset(*Relaxable.
front()) / BundleSize !=
1032 switch (
F.getKind()) {
1034 auto &BF =
static_cast<MCBoundaryAlignFragment &
>(
F);
1037 Changed |= foldBundlePad(Asm, BF, Relaxable);
1057bool X86AsmBackend::finishLayout()
const {
1060 if (
Asm->isBundlingEnabled())
1061 return TargetPrefixMax != 0 && optimizeBundleNops(*Asm);
1068 if (!X86PadForAlign && !X86PadForBranchAlign)
1074 DenseSet<MCFragment *> LabeledFragments;
1075 for (
const MCSymbol &S :
Asm->symbols())
1076 LabeledFragments.
insert(S.getFragment());
1079 for (MCSection &Sec : *Asm) {
1084 for (MCSection::iterator
I = Sec.begin(), IE = Sec.end();
I != IE; ++
I) {
1087 if (LabeledFragments.
count(&
F))
1099 auto canHandle = [](MCFragment &
F) ->
bool {
1100 switch (
F.getKind()) {
1104 return X86PadForAlign;
1106 return X86PadForBranchAlign;
1110 if (!canHandle(
F)) {
1119 unsigned RemainingSize =
Asm->computeFragmentSize(
F) -
F.getFixedSize();
1120 Changed |= padInstsBackward(Relaxable, RemainingSize);
1131 while (&*
I != LastFragment)
1140unsigned X86AsmBackend::getMaximumNopSize(
const MCSubtargetInfo &STI)
const {
1147 if (STI.
hasFeature(X86::TuningFast15ByteNOP))
1149 if (STI.
hasFeature(X86::TuningFast11ByteNOP))
1160bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t
Count,
1161 const MCSubtargetInfo *STI)
const {
1162 static const char Nops32Bit[10][11] = {
1172 "\x0f\x1f\x44\x00\x00",
1174 "\x66\x0f\x1f\x44\x00\x00",
1176 "\x0f\x1f\x80\x00\x00\x00\x00",
1178 "\x0f\x1f\x84\x00\x00\x00\x00\x00",
1180 "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
1182 "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
1186 static const char Nops16Bit[4][11] = {
1197 const char(*Nops)[11] =
1198 STI->
hasFeature(X86::Is16Bit) ? Nops16Bit : Nops32Bit;
1200 uint64_t MaxNopLength = (uint64_t)getMaximumNopSize(*STI);
1205 const uint8_t ThisNopLength = (uint8_t) std::min(
Count, MaxNopLength);
1206 const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
1207 for (uint8_t i = 0; i < Prefixes; i++)
1209 const uint8_t Rest = ThisNopLength - Prefixes;
1211 OS.
write(Nops[Rest - 1], Rest);
1212 Count -= ThisNopLength;
1213 }
while (
Count != 0);
1222class ELFX86AsmBackend :
public X86AsmBackend {
1225 ELFX86AsmBackend(
const Target &
T, uint8_t OSABI,
const MCSubtargetInfo &STI)
1226 : X86AsmBackend(
T, STI), OSABI(OSABI) {}
1229class ELFX86_32AsmBackend :
public ELFX86AsmBackend {
1231 ELFX86_32AsmBackend(
const Target &
T, uint8_t OSABI,
1232 const MCSubtargetInfo &STI)
1233 : ELFX86AsmBackend(
T, OSABI, STI) {}
1235 std::unique_ptr<MCObjectTargetWriter>
1236 createObjectTargetWriter()
const override {
1241class ELFX86_X32AsmBackend :
public ELFX86AsmBackend {
1243 ELFX86_X32AsmBackend(
const Target &
T, uint8_t OSABI,
1244 const MCSubtargetInfo &STI)
1245 : ELFX86AsmBackend(
T, OSABI, STI) {}
1247 std::unique_ptr<MCObjectTargetWriter>
1248 createObjectTargetWriter()
const override {
1254class ELFX86_IAMCUAsmBackend :
public ELFX86AsmBackend {
1256 ELFX86_IAMCUAsmBackend(
const Target &
T, uint8_t OSABI,
1257 const MCSubtargetInfo &STI)
1258 : ELFX86AsmBackend(
T, OSABI, STI) {}
1260 std::unique_ptr<MCObjectTargetWriter>
1261 createObjectTargetWriter()
const override {
1267class ELFX86_64AsmBackend :
public ELFX86AsmBackend {
1269 ELFX86_64AsmBackend(
const Target &
T, uint8_t OSABI,
1270 const MCSubtargetInfo &STI)
1271 : ELFX86AsmBackend(
T, OSABI, STI) {}
1273 std::unique_ptr<MCObjectTargetWriter>
1274 createObjectTargetWriter()
const override {
1279class WindowsX86AsmBackend :
public X86AsmBackend {
1283 WindowsX86AsmBackend(
const Target &
T,
bool is64Bit,
1284 const MCSubtargetInfo &STI)
1285 : X86AsmBackend(
T, STI)
1289 std::optional<MCFixupKind>
getFixupKind(StringRef Name)
const override {
1290 return StringSwitch<std::optional<MCFixupKind>>(
Name)
1297 std::unique_ptr<MCObjectTargetWriter>
1298 createObjectTargetWriter()
const override {
1306 enum CompactUnwindEncodings {
1309 UNWIND_MODE_BP_FRAME = 0x01000000,
1312 UNWIND_MODE_STACK_IMMD = 0x02000000,
1315 UNWIND_MODE_STACK_IND = 0x03000000,
1318 UNWIND_MODE_DWARF = 0x04000000,
1321 UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
1324 UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
1329class DarwinX86AsmBackend :
public X86AsmBackend {
1330 const MCRegisterInfo &MRI;
1333 enum { CU_NUM_SAVED_REGS = 6 };
1335 mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
1339 unsigned OffsetSize;
1340 unsigned MoveInstrSize;
1341 unsigned StackDivide;
1344 unsigned PushInstrSize(MCRegister
Reg)
const {
1367 int getCompactUnwindRegNum(
unsigned Reg)
const {
1368 static const MCPhysReg CU32BitRegs[7] = {
1369 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
1371 static const MCPhysReg CU64BitRegs[] = {
1372 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
1374 const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
1375 for (
int Idx = 1; *CURegs; ++CURegs, ++Idx)
1384 uint32_t encodeCompactUnwindRegistersWithFrame()
const {
1388 uint32_t RegEnc = 0;
1389 for (
int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
1390 unsigned Reg = SavedRegs[i];
1391 if (
Reg == 0)
break;
1393 int CURegNum = getCompactUnwindRegNum(
Reg);
1394 if (CURegNum == -1)
return ~0
U;
1398 RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
1401 assert((RegEnc & 0x3FFFF) == RegEnc &&
1402 "Invalid compact register encoding!");
1409 uint32_t encodeCompactUnwindRegistersWithoutFrame(
unsigned RegCount)
const {
1423 for (
unsigned i = 0; i < RegCount; ++i) {
1424 int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
1425 if (CUReg == -1)
return ~0
U;
1426 SavedRegs[i] = CUReg;
1430 std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
1432 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
1433 for (
unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
1434 unsigned Countless = 0;
1435 for (
unsigned j = CU_NUM_SAVED_REGS - RegCount;
j < i; ++
j)
1436 if (SavedRegs[j] < SavedRegs[i])
1439 RenumRegs[i] = SavedRegs[i] - Countless - 1;
1443 uint32_t permutationEncoding = 0;
1446 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
1447 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
1451 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
1452 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
1456 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
1457 + 3 * RenumRegs[4] + RenumRegs[5];
1460 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
1464 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
1467 permutationEncoding |= RenumRegs[5];
1471 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
1472 "Invalid compact register encoding!");
1473 return permutationEncoding;
1477 DarwinX86AsmBackend(
const Target &
T,
const MCRegisterInfo &MRI,
1478 const MCSubtargetInfo &STI)
1479 : X86AsmBackend(
T, STI), MRI(MRI),
TT(STI.getTargetTriple()),
1480 Is64Bit(
TT.isX86_64()) {
1481 memset(SavedRegs, 0,
sizeof(SavedRegs));
1482 OffsetSize = Is64Bit ? 8 : 4;
1483 MoveInstrSize = Is64Bit ? 3 : 2;
1484 StackDivide = Is64Bit ? 8 : 4;
1487 std::unique_ptr<MCObjectTargetWriter>
1488 createObjectTargetWriter()
const override {
1496 uint64_t generateCompactUnwindEncoding(
const MCDwarfFrameInfo *FI,
1497 const MCContext *Ctxt)
const override {
1499 return CU::UNWIND_MODE_DWARF;
1503 return CU::UNWIND_MODE_DWARF;
1506 if (Instrs.
empty())
return 0;
1507 if (!isDarwinCanonicalPersonality(FI->
Personality) &&
1509 return CU::UNWIND_MODE_DWARF;
1512 unsigned SavedRegIdx = 0;
1513 memset(SavedRegs, 0,
sizeof(SavedRegs));
1518 uint64_t CompactUnwindEncoding = 0;
1520 unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
1521 unsigned InstrOffset = 0;
1522 unsigned StackAdjust = 0;
1523 uint64_t StackSize = 0;
1524 int64_t MinAbsOffset = std::numeric_limits<int64_t>::max();
1526 for (
const MCCFIInstruction &Inst : Instrs) {
1527 switch (Inst.getOperation()) {
1531 return CU::UNWIND_MODE_DWARF;
1544 (Is64Bit ? X86::RBP : X86::EBP))
1545 return CU::UNWIND_MODE_DWARF;
1548 memset(SavedRegs, 0,
sizeof(SavedRegs));
1551 MinAbsOffset = std::numeric_limits<int64_t>::max();
1552 InstrOffset += MoveInstrSize;
1570 StackSize = Inst.getOffset() / StackDivide;
1586 if (SavedRegIdx == CU_NUM_SAVED_REGS)
1589 return CU::UNWIND_MODE_DWARF;
1592 SavedRegs[SavedRegIdx++] =
Reg.
id();
1593 StackAdjust += OffsetSize;
1594 MinAbsOffset = std::min(MinAbsOffset, std::abs(Inst.getOffset()));
1595 InstrOffset += PushInstrSize(
Reg);
1601 StackAdjust /= StackDivide;
1604 if ((StackAdjust & 0xFF) != StackAdjust)
1606 return CU::UNWIND_MODE_DWARF;
1610 if (SavedRegIdx != 0 && MinAbsOffset != 3 * (
int)OffsetSize)
1611 return CU::UNWIND_MODE_DWARF;
1614 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
1615 if (RegEnc == ~0U)
return CU::UNWIND_MODE_DWARF;
1617 CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
1618 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
1619 CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
1621 SubtractInstrIdx += InstrOffset;
1624 if ((StackSize & 0xFF) == StackSize) {
1626 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
1629 CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
1631 if ((StackAdjust & 0x7) != StackAdjust)
1633 return CU::UNWIND_MODE_DWARF;
1636 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
1640 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
1643 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
1647 std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
1648 CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
1652 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
1653 if (RegEnc == ~0U)
return CU::UNWIND_MODE_DWARF;
1656 CompactUnwindEncoding |=
1657 RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
1660 return CompactUnwindEncoding;
1672 return new DarwinX86AsmBackend(
T, MRI, STI);
1675 return new WindowsX86AsmBackend(
T,
false, STI);
1680 return new ELFX86_IAMCUAsmBackend(
T, OSABI, STI);
1682 return new ELFX86_32AsmBackend(
T, OSABI, STI);
1691 return new DarwinX86AsmBackend(
T, MRI, STI);
1694 return new WindowsX86AsmBackend(
T,
true, STI);
1696 if (TheTriple.
isUEFI()) {
1698 "Only COFF format is supported in UEFI environment.");
1699 return new WindowsX86AsmBackend(
T,
true, STI);
1704 if (TheTriple.
isX32())
1705 return new ELFX86_X32AsmBackend(
T, OSABI, STI);
1706 return new ELFX86_64AsmBackend(
T, OSABI, STI);
1712 X86ELFStreamer(
MCContext &Context, std::unique_ptr<MCAsmBackend> TAB,
1713 std::unique_ptr<MCObjectWriter> OW,
1714 std::unique_ptr<MCCodeEmitter>
Emitter)
1718 void emitInstruction(
const MCInst &Inst,
const MCSubtargetInfo &STI)
override;
1722void X86ELFStreamer::emitInstruction(
const MCInst &Inst,
1723 const MCSubtargetInfo &STI) {
1728 std::unique_ptr<MCAsmBackend> &&MAB,
1729 std::unique_ptr<MCObjectWriter> &&MOW,
1730 std::unique_ptr<MCCodeEmitter> &&MCE) {
1731 return new X86ELFStreamer(Context, std::move(MAB), std::move(MOW),
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_LIKELY(EXPR)
dxil DXContainer Global Emitter
static unsigned getRelaxedOpcode(unsigned Opcode)
PowerPC TLS Dynamic Call Fixup
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.
bool empty() const
Check if the array is empty.
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...
void setSize(uint64_t Value)
const MCFragment * getLastFragment() const
bool isAlignToEnd() const
void setLastFragment(const MCFragment *F)
Context object for machine code objects.
LLVM_ABI bool emitCompactUnwindNonCanonical() const
LLVM_ABI EmitDwarfUnwindType emitDwarfUnwindInfo() const
Base class for the full range of assembler expressions which are needed for parsing.
@ SymbolRef
References to labels and assigned expressions.
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, bool PCRel=false)
Consider bit fields if we need more flags.
bool getAllowAutoPadding() const
void setAllowAutoPadding(bool V)
unsigned getOpcode() const
MCSection * getParent() const
LLVM_ABI void setVarFixups(ArrayRef< MCFixup > Fixups)
MCFragment * getNext() const
ArrayRef< MCOperand > getOperands() const
size_t getVarSize() const
LLVM_ABI void setVarContents(ArrayRef< char > Contents)
MutableArrayRef< char > getVarContents()
const MCSubtargetInfo * getSubtargetInfo() const
Retrieve the MCSubTargetInfo in effect when the instruction was encoded.
MutableArrayRef< MCFixup > getVarFixups()
void setInst(const MCInst &Inst)
Instances of this class represent a single low-level machine instruction.
unsigned getOpcode() const
void setOpcode(unsigned Op)
const MCOperand & getOperand(unsigned i) const
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.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Streaming object file generation interface.
FT * newSpecialFragment(Args &&...args)
MCAssembler & getAssembler()
bool isBundleLocked() const
MCRegister getReg() const
Returns the register number.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
std::optional< MCRegister > getLLVMRegNum(uint64_t RegNum, bool isEH) const
Map a dwarf register back to a target register.
Wrapper class representing physical registers. Should be passed by value.
void ensureMinAlignment(Align MinAlignment)
Makes sure that Alignment is at least MinAlignment.
Streaming machine code generation interface.
MCFragment * getCurrentFragment() const
SMLoc getStartTokLoc() const
size_t getCurFragSize() const
bool getAllowAutoPadding() const
MCSection * getCurrentSectionOnly() const
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
constexpr unsigned id() const
void push_back(const T &Elt)
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
bool isX86_64() const
Tests whether the target is x86 (64-bit).
bool isX32() const
Tests whether the target is X32.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
OSType getOS() const
Get the parsed operating system type of this triple.
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
bool isUEFI() const
Tests whether the OS is UEFI.
bool isOSWindows() const
Tests whether the OS is Windows.
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
raw_ostream & write(unsigned char C)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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)
LLVM_ABI Expected< uint32_t > getCPUType(const Triple &T)
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...
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.
SecondMacroFusionInstKind
EncodingOfSegmentOverridePrefix getSegmentOverridePrefixForReg(MCRegister Reg)
Given a segment register, return the encoding of the segment override prefix for it.
unsigned getOpcodeForLongImmediateForm(unsigned Opcode)
bool isMacroFused(FirstMacroFusionInstKind FirstKind, SecondMacroFusionInstKind SecondKind)
@ reloc_riprel_4byte_movq_load_rex2
@ reloc_signed_4byte_relax
@ reloc_branch_4byte_pcrel
@ 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
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
Error applyFixup(LinkGraph &G, Block &B, const Edge &E, const ArmConfig &ArmCfg)
Apply fixup expression for edge to block content.
bool isRelocation(MCFixupKind FixupKind)
NodeAddr< CodeNode * > Code
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
This is an optimization pass for GlobalISel generic memory operations.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
uint16_t MCFixupKind
Extensible enumeration to represent the type of a fixup.
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.
@ FirstLiteralRelocationKind
@ FK_Data_8
A eight-byte fixup.
@ FK_Data_1
A one-byte fixup.
@ FK_Data_4
A four-byte fixup.
@ FK_SecRel_8
A eight-byte section relative fixup.
@ FK_SecRel_4
A four-byte section relative fixup.
@ FK_SecRel_1
A one-byte section relative fixup.
@ FK_Data_2
A two-byte fixup.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
std::unique_ptr< MCObjectTargetWriter > createX86MachObjectWriter(bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype)
Construct an X86 Mach-O object writer.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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.
MCAsmBackend * createX86_32AsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
Implement std::hash so that hash_code can be used in STL containers.
const MCSymbol * Personality
std::vector< MCCFIInstruction > Instructions