1 //===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "MCTargetDesc/X86FixupKinds.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/BinaryFormat/ELF.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCFixupKindInfo.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCMachObjectWriter.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static unsigned getFixupKindLog2Size(unsigned Kind) {
32 llvm_unreachable("invalid fixup kind!");
42 case X86::reloc_riprel_4byte:
43 case X86::reloc_riprel_4byte_relax:
44 case X86::reloc_riprel_4byte_relax_rex:
45 case X86::reloc_riprel_4byte_movq_load:
46 case X86::reloc_signed_4byte:
47 case X86::reloc_signed_4byte_relax:
48 case X86::reloc_global_offset_table:
49 case X86::reloc_branch_4byte_pcrel:
56 case X86::reloc_global_offset_table8:
63 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
65 X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
66 bool HasRelocationAddend, bool foobar)
67 : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
70 class X86AsmBackend : public MCAsmBackend {
71 const MCSubtargetInfo &STI;
73 X86AsmBackend(const Target &T, const MCSubtargetInfo &STI)
74 : MCAsmBackend(support::little), STI(STI) {}
76 unsigned getNumFixupKinds() const override {
77 return X86::NumTargetFixupKinds;
80 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
81 const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
82 {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
83 {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
84 {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
85 {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
86 {"reloc_signed_4byte", 0, 32, 0},
87 {"reloc_signed_4byte_relax", 0, 32, 0},
88 {"reloc_global_offset_table", 0, 32, 0},
89 {"reloc_global_offset_table8", 0, 64, 0},
90 {"reloc_branch_4byte_pcrel", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
93 if (Kind < FirstTargetFixupKind)
94 return MCAsmBackend::getFixupKindInfo(Kind);
96 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
98 assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
99 return Infos[Kind - FirstTargetFixupKind];
102 void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
103 const MCValue &Target, MutableArrayRef<char> Data,
104 uint64_t Value, bool IsResolved,
105 const MCSubtargetInfo *STI) const override {
106 unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
108 assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
110 // Check that uppper bits are either all zeros or all ones.
111 // Specifically ignore overflow/underflow as long as the leakage is
112 // limited to the lower bits. This is to remain compatible with
114 assert(isIntN(Size * 8 + 1, Value) &&
115 "Value does not fit in the Fixup field");
117 for (unsigned i = 0; i != Size; ++i)
118 Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
121 bool mayNeedRelaxation(const MCInst &Inst,
122 const MCSubtargetInfo &STI) const override;
124 bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
125 const MCRelaxableFragment *DF,
126 const MCAsmLayout &Layout) const override;
128 void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
129 MCInst &Res) const override;
131 bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
133 } // end anonymous namespace
135 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
136 unsigned Op = Inst.getOpcode();
141 return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
143 return (is16BitMode) ? X86::JA_2 : X86::JA_4;
145 return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
147 return (is16BitMode) ? X86::JB_2 : X86::JB_4;
149 return (is16BitMode) ? X86::JE_2 : X86::JE_4;
151 return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
153 return (is16BitMode) ? X86::JG_2 : X86::JG_4;
155 return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
157 return (is16BitMode) ? X86::JL_2 : X86::JL_4;
159 return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
161 return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
163 return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
165 return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
167 return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
169 return (is16BitMode) ? X86::JO_2 : X86::JO_4;
171 return (is16BitMode) ? X86::JP_2 : X86::JP_4;
173 return (is16BitMode) ? X86::JS_2 : X86::JS_4;
177 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
178 unsigned Op = Inst.getOpcode();
184 case X86::IMUL16rri8: return X86::IMUL16rri;
185 case X86::IMUL16rmi8: return X86::IMUL16rmi;
186 case X86::IMUL32rri8: return X86::IMUL32rri;
187 case X86::IMUL32rmi8: return X86::IMUL32rmi;
188 case X86::IMUL64rri8: return X86::IMUL64rri32;
189 case X86::IMUL64rmi8: return X86::IMUL64rmi32;
192 case X86::AND16ri8: return X86::AND16ri;
193 case X86::AND16mi8: return X86::AND16mi;
194 case X86::AND32ri8: return X86::AND32ri;
195 case X86::AND32mi8: return X86::AND32mi;
196 case X86::AND64ri8: return X86::AND64ri32;
197 case X86::AND64mi8: return X86::AND64mi32;
200 case X86::OR16ri8: return X86::OR16ri;
201 case X86::OR16mi8: return X86::OR16mi;
202 case X86::OR32ri8: return X86::OR32ri;
203 case X86::OR32mi8: return X86::OR32mi;
204 case X86::OR64ri8: return X86::OR64ri32;
205 case X86::OR64mi8: return X86::OR64mi32;
208 case X86::XOR16ri8: return X86::XOR16ri;
209 case X86::XOR16mi8: return X86::XOR16mi;
210 case X86::XOR32ri8: return X86::XOR32ri;
211 case X86::XOR32mi8: return X86::XOR32mi;
212 case X86::XOR64ri8: return X86::XOR64ri32;
213 case X86::XOR64mi8: return X86::XOR64mi32;
216 case X86::ADD16ri8: return X86::ADD16ri;
217 case X86::ADD16mi8: return X86::ADD16mi;
218 case X86::ADD32ri8: return X86::ADD32ri;
219 case X86::ADD32mi8: return X86::ADD32mi;
220 case X86::ADD64ri8: return X86::ADD64ri32;
221 case X86::ADD64mi8: return X86::ADD64mi32;
224 case X86::ADC16ri8: return X86::ADC16ri;
225 case X86::ADC16mi8: return X86::ADC16mi;
226 case X86::ADC32ri8: return X86::ADC32ri;
227 case X86::ADC32mi8: return X86::ADC32mi;
228 case X86::ADC64ri8: return X86::ADC64ri32;
229 case X86::ADC64mi8: return X86::ADC64mi32;
232 case X86::SUB16ri8: return X86::SUB16ri;
233 case X86::SUB16mi8: return X86::SUB16mi;
234 case X86::SUB32ri8: return X86::SUB32ri;
235 case X86::SUB32mi8: return X86::SUB32mi;
236 case X86::SUB64ri8: return X86::SUB64ri32;
237 case X86::SUB64mi8: return X86::SUB64mi32;
240 case X86::SBB16ri8: return X86::SBB16ri;
241 case X86::SBB16mi8: return X86::SBB16mi;
242 case X86::SBB32ri8: return X86::SBB32ri;
243 case X86::SBB32mi8: return X86::SBB32mi;
244 case X86::SBB64ri8: return X86::SBB64ri32;
245 case X86::SBB64mi8: return X86::SBB64mi32;
248 case X86::CMP16ri8: return X86::CMP16ri;
249 case X86::CMP16mi8: return X86::CMP16mi;
250 case X86::CMP32ri8: return X86::CMP32ri;
251 case X86::CMP32mi8: return X86::CMP32mi;
252 case X86::CMP64ri8: return X86::CMP64ri32;
253 case X86::CMP64mi8: return X86::CMP64mi32;
256 case X86::PUSH32i8: return X86::PUSHi32;
257 case X86::PUSH16i8: return X86::PUSHi16;
258 case X86::PUSH64i8: return X86::PUSH64i32;
262 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
263 unsigned R = getRelaxedOpcodeArith(Inst);
264 if (R != Inst.getOpcode())
266 return getRelaxedOpcodeBranch(Inst, is16BitMode);
269 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst,
270 const MCSubtargetInfo &STI) const {
271 // Branches can always be relaxed in either mode.
272 if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
275 // Check if this instruction is ever relaxable.
276 if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
280 // Check if the relaxable operand has an expression. For the current set of
281 // relaxable instructions, the relaxable operand is always the last operand.
282 unsigned RelaxableOp = Inst.getNumOperands() - 1;
283 if (Inst.getOperand(RelaxableOp).isExpr())
289 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
291 const MCRelaxableFragment *DF,
292 const MCAsmLayout &Layout) const {
293 // Relax if the value is too big for a (signed) i8.
294 return int64_t(Value) != int64_t(int8_t(Value));
297 // FIXME: Can tblgen help at all here to verify there aren't other instructions
299 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
300 const MCSubtargetInfo &STI,
302 // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
303 bool is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
304 unsigned RelaxedOp = getRelaxedOpcode(Inst, is16BitMode);
306 if (RelaxedOp == Inst.getOpcode()) {
307 SmallString<256> Tmp;
308 raw_svector_ostream OS(Tmp);
309 Inst.dump_pretty(OS);
311 report_fatal_error("unexpected instruction to relax: " + OS.str());
315 Res.setOpcode(RelaxedOp);
318 /// Write a sequence of optimal nops to the output, covering \p Count
320 /// \return - true on success, false on failure
321 bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
322 static const char Nops[10][11] = {
331 // nopl 0(%[re]ax,%[re]ax,1)
332 "\x0f\x1f\x44\x00\x00",
333 // nopw 0(%[re]ax,%[re]ax,1)
334 "\x66\x0f\x1f\x44\x00\x00",
336 "\x0f\x1f\x80\x00\x00\x00\x00",
337 // nopl 0L(%[re]ax,%[re]ax,1)
338 "\x0f\x1f\x84\x00\x00\x00\x00\x00",
339 // nopw 0L(%[re]ax,%[re]ax,1)
340 "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
341 // nopw %cs:0L(%[re]ax,%[re]ax,1)
342 "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
345 // This CPU doesn't support long nops. If needed add more.
346 // FIXME: We could generated something better than plain 0x90.
347 if (!STI.getFeatureBits()[X86::FeatureNOPL]) {
348 for (uint64_t i = 0; i < Count; ++i)
353 // 15-bytes is the longest single NOP instruction, but 10-bytes is
354 // commonly the longest that can be efficiently decoded.
355 uint64_t MaxNopLength = 10;
356 if (STI.getFeatureBits()[X86::ProcIntelSLM])
358 else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
360 else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
363 // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
366 const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
367 const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
368 for (uint8_t i = 0; i < Prefixes; i++)
370 const uint8_t Rest = ThisNopLength - Prefixes;
372 OS.write(Nops[Rest - 1], Rest);
373 Count -= ThisNopLength;
374 } while (Count != 0);
383 class ELFX86AsmBackend : public X86AsmBackend {
386 ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
387 : X86AsmBackend(T, STI), OSABI(OSABI) {}
390 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
392 ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
393 const MCSubtargetInfo &STI)
394 : ELFX86AsmBackend(T, OSABI, STI) {}
396 std::unique_ptr<MCObjectTargetWriter>
397 createObjectTargetWriter() const override {
398 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
402 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
404 ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
405 const MCSubtargetInfo &STI)
406 : ELFX86AsmBackend(T, OSABI, STI) {}
408 std::unique_ptr<MCObjectTargetWriter>
409 createObjectTargetWriter() const override {
410 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
415 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
417 ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
418 const MCSubtargetInfo &STI)
419 : ELFX86AsmBackend(T, OSABI, STI) {}
421 std::unique_ptr<MCObjectTargetWriter>
422 createObjectTargetWriter() const override {
423 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
428 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
430 ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
431 const MCSubtargetInfo &STI)
432 : ELFX86AsmBackend(T, OSABI, STI) {}
434 std::unique_ptr<MCObjectTargetWriter>
435 createObjectTargetWriter() const override {
436 return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
440 class WindowsX86AsmBackend : public X86AsmBackend {
444 WindowsX86AsmBackend(const Target &T, bool is64Bit,
445 const MCSubtargetInfo &STI)
446 : X86AsmBackend(T, STI)
450 Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
451 return StringSwitch<Optional<MCFixupKind>>(Name)
452 .Case("dir32", FK_Data_4)
453 .Case("secrel32", FK_SecRel_4)
454 .Case("secidx", FK_SecRel_2)
455 .Default(MCAsmBackend::getFixupKind(Name));
458 std::unique_ptr<MCObjectTargetWriter>
459 createObjectTargetWriter() const override {
460 return createX86WinCOFFObjectWriter(Is64Bit);
466 /// Compact unwind encoding values.
467 enum CompactUnwindEncodings {
468 /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
469 /// the return address, then [RE]SP is moved to [RE]BP.
470 UNWIND_MODE_BP_FRAME = 0x01000000,
472 /// A frameless function with a small constant stack size.
473 UNWIND_MODE_STACK_IMMD = 0x02000000,
475 /// A frameless function with a large constant stack size.
476 UNWIND_MODE_STACK_IND = 0x03000000,
478 /// No compact unwind encoding is available.
479 UNWIND_MODE_DWARF = 0x04000000,
481 /// Mask for encoding the frame registers.
482 UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
484 /// Mask for encoding the frameless registers.
485 UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
488 } // end CU namespace
490 class DarwinX86AsmBackend : public X86AsmBackend {
491 const MCRegisterInfo &MRI;
493 /// Number of registers that can be saved in a compact unwind encoding.
494 enum { CU_NUM_SAVED_REGS = 6 };
496 mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
499 unsigned OffsetSize; ///< Offset of a "push" instruction.
500 unsigned MoveInstrSize; ///< Size of a "move" instruction.
501 unsigned StackDivide; ///< Amount to adjust stack size by.
503 /// Size of a "push" instruction for the given register.
504 unsigned PushInstrSize(unsigned Reg) const {
524 /// Implementation of algorithm to generate the compact unwind encoding
525 /// for the CFI instructions.
527 generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
528 if (Instrs.empty()) return 0;
530 // Reset the saved registers.
531 unsigned SavedRegIdx = 0;
532 memset(SavedRegs, 0, sizeof(SavedRegs));
536 // Encode that we are using EBP/RBP as the frame pointer.
537 uint32_t CompactUnwindEncoding = 0;
539 unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
540 unsigned InstrOffset = 0;
541 unsigned StackAdjust = 0;
542 unsigned StackSize = 0;
543 unsigned PrevStackSize = 0;
544 unsigned NumDefCFAOffsets = 0;
546 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
547 const MCCFIInstruction &Inst = Instrs[i];
549 switch (Inst.getOperation()) {
551 // Any other CFI directives indicate a frame that we aren't prepared
552 // to represent via compact unwind, so just bail out.
554 case MCCFIInstruction::OpDefCfaRegister: {
555 // Defines a frame pointer. E.g.
559 // .cfi_def_cfa_register %rbp
563 // If the frame pointer is other than esp/rsp, we do not have a way to
564 // generate a compact unwinding representation, so bail out.
565 if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
566 (Is64Bit ? X86::RBP : X86::EBP))
570 memset(SavedRegs, 0, sizeof(SavedRegs));
573 InstrOffset += MoveInstrSize;
576 case MCCFIInstruction::OpDefCfaOffset: {
577 // Defines a new offset for the CFA. E.g.
583 // .cfi_def_cfa_offset 16
589 // .cfi_def_cfa_offset 80
591 PrevStackSize = StackSize;
592 StackSize = std::abs(Inst.getOffset()) / StackDivide;
596 case MCCFIInstruction::OpOffset: {
597 // Defines a "push" of a callee-saved register. E.g.
605 // .cfi_offset %rbx, -40
606 // .cfi_offset %r14, -32
607 // .cfi_offset %r15, -24
609 if (SavedRegIdx == CU_NUM_SAVED_REGS)
610 // If there are too many saved registers, we cannot use a compact
612 return CU::UNWIND_MODE_DWARF;
614 unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
615 SavedRegs[SavedRegIdx++] = Reg;
616 StackAdjust += OffsetSize;
617 InstrOffset += PushInstrSize(Reg);
623 StackAdjust /= StackDivide;
626 if ((StackAdjust & 0xFF) != StackAdjust)
627 // Offset was too big for a compact unwind encoding.
628 return CU::UNWIND_MODE_DWARF;
630 // Get the encoding of the saved registers when we have a frame pointer.
631 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
632 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
634 CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
635 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
636 CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
638 // If the amount of the stack allocation is the size of a register, then
639 // we "push" the RAX/EAX register onto the stack instead of adjusting the
640 // stack pointer with a SUB instruction. We don't support the push of the
641 // RAX/EAX register with compact unwind. So we check for that situation
643 if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
644 StackSize - PrevStackSize == 1) ||
645 (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
646 return CU::UNWIND_MODE_DWARF;
648 SubtractInstrIdx += InstrOffset;
651 if ((StackSize & 0xFF) == StackSize) {
652 // Frameless stack with a small stack size.
653 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
655 // Encode the stack size.
656 CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
658 if ((StackAdjust & 0x7) != StackAdjust)
659 // The extra stack adjustments are too big for us to handle.
660 return CU::UNWIND_MODE_DWARF;
662 // Frameless stack with an offset too large for us to encode compactly.
663 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
665 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
667 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
669 // Encode any extra stack adjustments (done via push instructions).
670 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
673 // Encode the number of registers saved. (Reverse the list first.)
674 std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
675 CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
677 // Get the encoding of the saved registers when we don't have a frame
679 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
680 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
682 // Encode the register encoding.
683 CompactUnwindEncoding |=
684 RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
687 return CompactUnwindEncoding;
691 /// Get the compact unwind number for a given register. The number
692 /// corresponds to the enum lists in compact_unwind_encoding.h.
693 int getCompactUnwindRegNum(unsigned Reg) const {
694 static const MCPhysReg CU32BitRegs[7] = {
695 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
697 static const MCPhysReg CU64BitRegs[] = {
698 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
700 const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
701 for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
708 /// Return the registers encoded for a compact encoding with a frame
710 uint32_t encodeCompactUnwindRegistersWithFrame() const {
711 // Encode the registers in the order they were saved --- 3-bits per
712 // register. The list of saved registers is assumed to be in reverse
713 // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
715 for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
716 unsigned Reg = SavedRegs[i];
719 int CURegNum = getCompactUnwindRegNum(Reg);
720 if (CURegNum == -1) return ~0U;
722 // Encode the 3-bit register number in order, skipping over 3-bits for
724 RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
727 assert((RegEnc & 0x3FFFF) == RegEnc &&
728 "Invalid compact register encoding!");
732 /// Create the permutation encoding used with frameless stacks. It is
733 /// passed the number of registers to be saved and an array of the registers
735 uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
736 // The saved registers are numbered from 1 to 6. In order to encode the
737 // order in which they were saved, we re-number them according to their
738 // place in the register order. The re-numbering is relative to the last
739 // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
749 for (unsigned i = 0; i < RegCount; ++i) {
750 int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
751 if (CUReg == -1) return ~0U;
752 SavedRegs[i] = CUReg;
756 std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
758 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
759 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
760 unsigned Countless = 0;
761 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
762 if (SavedRegs[j] < SavedRegs[i])
765 RenumRegs[i] = SavedRegs[i] - Countless - 1;
768 // Take the renumbered values and encode them into a 10-bit number.
769 uint32_t permutationEncoding = 0;
772 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
773 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
777 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
778 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
782 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
783 + 3 * RenumRegs[4] + RenumRegs[5];
786 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
790 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
793 permutationEncoding |= RenumRegs[5];
797 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
798 "Invalid compact register encoding!");
799 return permutationEncoding;
803 DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
804 const MCSubtargetInfo &STI, bool Is64Bit)
805 : X86AsmBackend(T, STI), MRI(MRI), Is64Bit(Is64Bit) {
806 memset(SavedRegs, 0, sizeof(SavedRegs));
807 OffsetSize = Is64Bit ? 8 : 4;
808 MoveInstrSize = Is64Bit ? 3 : 2;
809 StackDivide = Is64Bit ? 8 : 4;
813 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
815 DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
816 const MCSubtargetInfo &STI)
817 : DarwinX86AsmBackend(T, MRI, STI, false) {}
819 std::unique_ptr<MCObjectTargetWriter>
820 createObjectTargetWriter() const override {
821 return createX86MachObjectWriter(/*Is64Bit=*/false,
822 MachO::CPU_TYPE_I386,
823 MachO::CPU_SUBTYPE_I386_ALL);
826 /// Generate the compact unwind encoding for the CFI instructions.
827 uint32_t generateCompactUnwindEncoding(
828 ArrayRef<MCCFIInstruction> Instrs) const override {
829 return generateCompactUnwindEncodingImpl(Instrs);
833 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
834 const MachO::CPUSubTypeX86 Subtype;
836 DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
837 const MCSubtargetInfo &STI, MachO::CPUSubTypeX86 st)
838 : DarwinX86AsmBackend(T, MRI, STI, true), Subtype(st) {}
840 std::unique_ptr<MCObjectTargetWriter>
841 createObjectTargetWriter() const override {
842 return createX86MachObjectWriter(/*Is64Bit=*/true, MachO::CPU_TYPE_X86_64,
846 /// Generate the compact unwind encoding for the CFI instructions.
847 uint32_t generateCompactUnwindEncoding(
848 ArrayRef<MCCFIInstruction> Instrs) const override {
849 return generateCompactUnwindEncodingImpl(Instrs);
853 } // end anonymous namespace
855 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
856 const MCSubtargetInfo &STI,
857 const MCRegisterInfo &MRI,
858 const MCTargetOptions &Options) {
859 const Triple &TheTriple = STI.getTargetTriple();
860 if (TheTriple.isOSBinFormatMachO())
861 return new DarwinX86_32AsmBackend(T, MRI, STI);
863 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
864 return new WindowsX86AsmBackend(T, false, STI);
866 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
868 if (TheTriple.isOSIAMCU())
869 return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
871 return new ELFX86_32AsmBackend(T, OSABI, STI);
874 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
875 const MCSubtargetInfo &STI,
876 const MCRegisterInfo &MRI,
877 const MCTargetOptions &Options) {
878 const Triple &TheTriple = STI.getTargetTriple();
879 if (TheTriple.isOSBinFormatMachO()) {
880 MachO::CPUSubTypeX86 CS =
881 StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
882 .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
883 .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
884 return new DarwinX86_64AsmBackend(T, MRI, STI, CS);
887 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
888 return new WindowsX86AsmBackend(T, true, STI);
890 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
892 if (TheTriple.getEnvironment() == Triple::GNUX32)
893 return new ELFX86_X32AsmBackend(T, OSABI, STI);
894 return new ELFX86_64AsmBackend(T, OSABI, STI);