xref: /aosp_15_r20/external/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1 //===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "MCTargetDesc/X86FixupKinds.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCFixupKindInfo.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCMachObjectWriter.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCRegisterInfo.h"
21 #include "llvm/MC/MCSectionCOFF.h"
22 #include "llvm/MC/MCSectionELF.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/ELF.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MachO.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31 
getFixupKindLog2Size(unsigned Kind)32 static unsigned getFixupKindLog2Size(unsigned Kind) {
33   switch (Kind) {
34   default:
35     llvm_unreachable("invalid fixup kind!");
36   case FK_PCRel_1:
37   case FK_SecRel_1:
38   case FK_Data_1:
39     return 0;
40   case FK_PCRel_2:
41   case FK_SecRel_2:
42   case FK_Data_2:
43     return 1;
44   case FK_PCRel_4:
45   case X86::reloc_riprel_4byte:
46   case X86::reloc_riprel_4byte_relax:
47   case X86::reloc_riprel_4byte_relax_rex:
48   case X86::reloc_riprel_4byte_movq_load:
49   case X86::reloc_signed_4byte:
50   case X86::reloc_signed_4byte_relax:
51   case X86::reloc_global_offset_table:
52   case FK_SecRel_4:
53   case FK_Data_4:
54     return 2;
55   case FK_PCRel_8:
56   case FK_SecRel_8:
57   case FK_Data_8:
58   case X86::reloc_global_offset_table8:
59     return 3;
60   }
61 }
62 
63 namespace {
64 
65 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
66 public:
X86ELFObjectWriter(bool is64Bit,uint8_t OSABI,uint16_t EMachine,bool HasRelocationAddend,bool foobar)67   X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
68                      bool HasRelocationAddend, bool foobar)
69     : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
70 };
71 
72 class X86AsmBackend : public MCAsmBackend {
73   const StringRef CPU;
74   bool HasNopl;
75   const uint64_t MaxNopLength;
76 public:
X86AsmBackend(const Target & T,StringRef CPU)77   X86AsmBackend(const Target &T, StringRef CPU)
78       : MCAsmBackend(), CPU(CPU),
79         MaxNopLength((CPU == "slm" || CPU == "lakemont") ? 7 : 15) {
80     HasNopl = CPU != "generic" && CPU != "i386" && CPU != "i486" &&
81               CPU != "i586" && CPU != "pentium" && CPU != "pentium-mmx" &&
82               CPU != "i686" && CPU != "k6" && CPU != "k6-2" && CPU != "k6-3" &&
83               CPU != "geode" && CPU != "winchip-c6" && CPU != "winchip2" &&
84               CPU != "c3" && CPU != "c3-2";
85   }
86 
getNumFixupKinds() const87   unsigned getNumFixupKinds() const override {
88     return X86::NumTargetFixupKinds;
89   }
90 
getFixupKindInfo(MCFixupKind Kind) const91   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
92     const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
93         {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
94         {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
95         {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
96         {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
97         {"reloc_signed_4byte", 0, 32, 0},
98         {"reloc_signed_4byte_relax", 0, 32, 0},
99         {"reloc_global_offset_table", 0, 32, 0},
100         {"reloc_global_offset_table8", 0, 64, 0},
101     };
102 
103     if (Kind < FirstTargetFixupKind)
104       return MCAsmBackend::getFixupKindInfo(Kind);
105 
106     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
107            "Invalid kind!");
108     return Infos[Kind - FirstTargetFixupKind];
109   }
110 
applyFixup(const MCFixup & Fixup,char * Data,unsigned DataSize,uint64_t Value,bool IsPCRel) const111   void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
112                   uint64_t Value, bool IsPCRel) const override {
113     unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
114 
115     assert(Fixup.getOffset() + Size <= DataSize &&
116            "Invalid fixup offset!");
117 
118     // Check that uppper bits are either all zeros or all ones.
119     // Specifically ignore overflow/underflow as long as the leakage is
120     // limited to the lower bits. This is to remain compatible with
121     // other assemblers.
122     assert(isIntN(Size * 8 + 1, Value) &&
123            "Value does not fit in the Fixup field");
124 
125     for (unsigned i = 0; i != Size; ++i)
126       Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
127   }
128 
129   bool mayNeedRelaxation(const MCInst &Inst) const override;
130 
131   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
132                             const MCRelaxableFragment *DF,
133                             const MCAsmLayout &Layout) const override;
134 
135   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
136                         MCInst &Res) const override;
137 
138   bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override;
139 };
140 } // end anonymous namespace
141 
getRelaxedOpcodeBranch(const MCInst & Inst,bool is16BitMode)142 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
143   unsigned Op = Inst.getOpcode();
144   switch (Op) {
145   default:
146     return Op;
147   case X86::JAE_1:
148     return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
149   case X86::JA_1:
150     return (is16BitMode) ? X86::JA_2 : X86::JA_4;
151   case X86::JBE_1:
152     return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
153   case X86::JB_1:
154     return (is16BitMode) ? X86::JB_2 : X86::JB_4;
155   case X86::JE_1:
156     return (is16BitMode) ? X86::JE_2 : X86::JE_4;
157   case X86::JGE_1:
158     return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
159   case X86::JG_1:
160     return (is16BitMode) ? X86::JG_2 : X86::JG_4;
161   case X86::JLE_1:
162     return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
163   case X86::JL_1:
164     return (is16BitMode) ? X86::JL_2 : X86::JL_4;
165   case X86::JMP_1:
166     return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
167   case X86::JNE_1:
168     return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
169   case X86::JNO_1:
170     return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
171   case X86::JNP_1:
172     return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
173   case X86::JNS_1:
174     return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
175   case X86::JO_1:
176     return (is16BitMode) ? X86::JO_2 : X86::JO_4;
177   case X86::JP_1:
178     return (is16BitMode) ? X86::JP_2 : X86::JP_4;
179   case X86::JS_1:
180     return (is16BitMode) ? X86::JS_2 : X86::JS_4;
181   }
182 }
183 
getRelaxedOpcodeArith(const MCInst & Inst)184 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
185   unsigned Op = Inst.getOpcode();
186   switch (Op) {
187   default:
188     return Op;
189 
190     // IMUL
191   case X86::IMUL16rri8: return X86::IMUL16rri;
192   case X86::IMUL16rmi8: return X86::IMUL16rmi;
193   case X86::IMUL32rri8: return X86::IMUL32rri;
194   case X86::IMUL32rmi8: return X86::IMUL32rmi;
195   case X86::IMUL64rri8: return X86::IMUL64rri32;
196   case X86::IMUL64rmi8: return X86::IMUL64rmi32;
197 
198     // AND
199   case X86::AND16ri8: return X86::AND16ri;
200   case X86::AND16mi8: return X86::AND16mi;
201   case X86::AND32ri8: return X86::AND32ri;
202   case X86::AND32mi8: return X86::AND32mi;
203   case X86::AND64ri8: return X86::AND64ri32;
204   case X86::AND64mi8: return X86::AND64mi32;
205 
206     // OR
207   case X86::OR16ri8: return X86::OR16ri;
208   case X86::OR16mi8: return X86::OR16mi;
209   case X86::OR32ri8: return X86::OR32ri;
210   case X86::OR32mi8: return X86::OR32mi;
211   case X86::OR64ri8: return X86::OR64ri32;
212   case X86::OR64mi8: return X86::OR64mi32;
213 
214     // XOR
215   case X86::XOR16ri8: return X86::XOR16ri;
216   case X86::XOR16mi8: return X86::XOR16mi;
217   case X86::XOR32ri8: return X86::XOR32ri;
218   case X86::XOR32mi8: return X86::XOR32mi;
219   case X86::XOR64ri8: return X86::XOR64ri32;
220   case X86::XOR64mi8: return X86::XOR64mi32;
221 
222     // ADD
223   case X86::ADD16ri8: return X86::ADD16ri;
224   case X86::ADD16mi8: return X86::ADD16mi;
225   case X86::ADD32ri8: return X86::ADD32ri;
226   case X86::ADD32mi8: return X86::ADD32mi;
227   case X86::ADD64ri8: return X86::ADD64ri32;
228   case X86::ADD64mi8: return X86::ADD64mi32;
229 
230    // ADC
231   case X86::ADC16ri8: return X86::ADC16ri;
232   case X86::ADC16mi8: return X86::ADC16mi;
233   case X86::ADC32ri8: return X86::ADC32ri;
234   case X86::ADC32mi8: return X86::ADC32mi;
235   case X86::ADC64ri8: return X86::ADC64ri32;
236   case X86::ADC64mi8: return X86::ADC64mi32;
237 
238     // SUB
239   case X86::SUB16ri8: return X86::SUB16ri;
240   case X86::SUB16mi8: return X86::SUB16mi;
241   case X86::SUB32ri8: return X86::SUB32ri;
242   case X86::SUB32mi8: return X86::SUB32mi;
243   case X86::SUB64ri8: return X86::SUB64ri32;
244   case X86::SUB64mi8: return X86::SUB64mi32;
245 
246    // SBB
247   case X86::SBB16ri8: return X86::SBB16ri;
248   case X86::SBB16mi8: return X86::SBB16mi;
249   case X86::SBB32ri8: return X86::SBB32ri;
250   case X86::SBB32mi8: return X86::SBB32mi;
251   case X86::SBB64ri8: return X86::SBB64ri32;
252   case X86::SBB64mi8: return X86::SBB64mi32;
253 
254     // CMP
255   case X86::CMP16ri8: return X86::CMP16ri;
256   case X86::CMP16mi8: return X86::CMP16mi;
257   case X86::CMP32ri8: return X86::CMP32ri;
258   case X86::CMP32mi8: return X86::CMP32mi;
259   case X86::CMP64ri8: return X86::CMP64ri32;
260   case X86::CMP64mi8: return X86::CMP64mi32;
261 
262     // PUSH
263   case X86::PUSH32i8:  return X86::PUSHi32;
264   case X86::PUSH16i8:  return X86::PUSHi16;
265   case X86::PUSH64i8:  return X86::PUSH64i32;
266   }
267 }
268 
getRelaxedOpcode(const MCInst & Inst,bool is16BitMode)269 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
270   unsigned R = getRelaxedOpcodeArith(Inst);
271   if (R != Inst.getOpcode())
272     return R;
273   return getRelaxedOpcodeBranch(Inst, is16BitMode);
274 }
275 
mayNeedRelaxation(const MCInst & Inst) const276 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
277   // Branches can always be relaxed in either mode.
278   if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
279     return true;
280 
281   // Check if this instruction is ever relaxable.
282   if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
283     return false;
284 
285 
286   // Check if the relaxable operand has an expression. For the current set of
287   // relaxable instructions, the relaxable operand is always the last operand.
288   unsigned RelaxableOp = Inst.getNumOperands() - 1;
289   if (Inst.getOperand(RelaxableOp).isExpr())
290     return true;
291 
292   return false;
293 }
294 
fixupNeedsRelaxation(const MCFixup & Fixup,uint64_t Value,const MCRelaxableFragment * DF,const MCAsmLayout & Layout) const295 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
296                                          uint64_t Value,
297                                          const MCRelaxableFragment *DF,
298                                          const MCAsmLayout &Layout) const {
299   // Relax if the value is too big for a (signed) i8.
300   return int64_t(Value) != int64_t(int8_t(Value));
301 }
302 
303 // FIXME: Can tblgen help at all here to verify there aren't other instructions
304 // we can relax?
relaxInstruction(const MCInst & Inst,const MCSubtargetInfo & STI,MCInst & Res) const305 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
306                                      const MCSubtargetInfo &STI,
307                                      MCInst &Res) const {
308   // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
309   bool is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
310   unsigned RelaxedOp = getRelaxedOpcode(Inst, is16BitMode);
311 
312   if (RelaxedOp == Inst.getOpcode()) {
313     SmallString<256> Tmp;
314     raw_svector_ostream OS(Tmp);
315     Inst.dump_pretty(OS);
316     OS << "\n";
317     report_fatal_error("unexpected instruction to relax: " + OS.str());
318   }
319 
320   Res = Inst;
321   Res.setOpcode(RelaxedOp);
322 }
323 
324 /// \brief Write a sequence of optimal nops to the output, covering \p Count
325 /// bytes.
326 /// \return - true on success, false on failure
writeNopData(uint64_t Count,MCObjectWriter * OW) const327 bool X86AsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
328   static const uint8_t Nops[10][10] = {
329     // nop
330     {0x90},
331     // xchg %ax,%ax
332     {0x66, 0x90},
333     // nopl (%[re]ax)
334     {0x0f, 0x1f, 0x00},
335     // nopl 0(%[re]ax)
336     {0x0f, 0x1f, 0x40, 0x00},
337     // nopl 0(%[re]ax,%[re]ax,1)
338     {0x0f, 0x1f, 0x44, 0x00, 0x00},
339     // nopw 0(%[re]ax,%[re]ax,1)
340     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
341     // nopl 0L(%[re]ax)
342     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
343     // nopl 0L(%[re]ax,%[re]ax,1)
344     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
345     // nopw 0L(%[re]ax,%[re]ax,1)
346     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
347     // nopw %cs:0L(%[re]ax,%[re]ax,1)
348     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
349   };
350 
351   // This CPU doesn't support long nops. If needed add more.
352   // FIXME: Can we get this from the subtarget somehow?
353   // FIXME: We could generated something better than plain 0x90.
354   if (!HasNopl) {
355     for (uint64_t i = 0; i < Count; ++i)
356       OW->write8(0x90);
357     return true;
358   }
359 
360   // 15 is the longest single nop instruction.  Emit as many 15-byte nops as
361   // needed, then emit a nop of the remaining length.
362   do {
363     const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
364     const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
365     for (uint8_t i = 0; i < Prefixes; i++)
366       OW->write8(0x66);
367     const uint8_t Rest = ThisNopLength - Prefixes;
368     for (uint8_t i = 0; i < Rest; i++)
369       OW->write8(Nops[Rest - 1][i]);
370     Count -= ThisNopLength;
371   } while (Count != 0);
372 
373   return true;
374 }
375 
376 /* *** */
377 
378 namespace {
379 
380 class ELFX86AsmBackend : public X86AsmBackend {
381 public:
382   uint8_t OSABI;
ELFX86AsmBackend(const Target & T,uint8_t OSABI,StringRef CPU)383   ELFX86AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
384       : X86AsmBackend(T, CPU), OSABI(OSABI) {}
385 };
386 
387 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
388 public:
ELFX86_32AsmBackend(const Target & T,uint8_t OSABI,StringRef CPU)389   ELFX86_32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
390     : ELFX86AsmBackend(T, OSABI, CPU) {}
391 
createObjectWriter(raw_pwrite_stream & OS) const392   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
393     return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI, ELF::EM_386);
394   }
395 };
396 
397 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
398 public:
ELFX86_X32AsmBackend(const Target & T,uint8_t OSABI,StringRef CPU)399   ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
400       : ELFX86AsmBackend(T, OSABI, CPU) {}
401 
createObjectWriter(raw_pwrite_stream & OS) const402   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
403     return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
404                                     ELF::EM_X86_64);
405   }
406 };
407 
408 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
409 public:
ELFX86_IAMCUAsmBackend(const Target & T,uint8_t OSABI,StringRef CPU)410   ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
411       : ELFX86AsmBackend(T, OSABI, CPU) {}
412 
createObjectWriter(raw_pwrite_stream & OS) const413   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
414     return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
415                                     ELF::EM_IAMCU);
416   }
417 };
418 
419 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
420 public:
ELFX86_64AsmBackend(const Target & T,uint8_t OSABI,StringRef CPU)421   ELFX86_64AsmBackend(const Target &T, uint8_t OSABI, StringRef CPU)
422     : ELFX86AsmBackend(T, OSABI, CPU) {}
423 
createObjectWriter(raw_pwrite_stream & OS) const424   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
425     return createX86ELFObjectWriter(OS, /*IsELF64*/ true, OSABI, ELF::EM_X86_64);
426   }
427 };
428 
429 class WindowsX86AsmBackend : public X86AsmBackend {
430   bool Is64Bit;
431 
432 public:
WindowsX86AsmBackend(const Target & T,bool is64Bit,StringRef CPU)433   WindowsX86AsmBackend(const Target &T, bool is64Bit, StringRef CPU)
434     : X86AsmBackend(T, CPU)
435     , Is64Bit(is64Bit) {
436   }
437 
getFixupKind(StringRef Name) const438   Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
439     return StringSwitch<Optional<MCFixupKind>>(Name)
440         .Case("dir32", FK_Data_4)
441         .Case("secrel32", FK_SecRel_4)
442         .Case("secidx", FK_SecRel_2)
443         .Default(MCAsmBackend::getFixupKind(Name));
444   }
445 
createObjectWriter(raw_pwrite_stream & OS) const446   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
447     return createX86WinCOFFObjectWriter(OS, Is64Bit);
448   }
449 };
450 
451 namespace CU {
452 
453   /// Compact unwind encoding values.
454   enum CompactUnwindEncodings {
455     /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
456     /// the return address, then [RE]SP is moved to [RE]BP.
457     UNWIND_MODE_BP_FRAME                   = 0x01000000,
458 
459     /// A frameless function with a small constant stack size.
460     UNWIND_MODE_STACK_IMMD                 = 0x02000000,
461 
462     /// A frameless function with a large constant stack size.
463     UNWIND_MODE_STACK_IND                  = 0x03000000,
464 
465     /// No compact unwind encoding is available.
466     UNWIND_MODE_DWARF                      = 0x04000000,
467 
468     /// Mask for encoding the frame registers.
469     UNWIND_BP_FRAME_REGISTERS              = 0x00007FFF,
470 
471     /// Mask for encoding the frameless registers.
472     UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
473   };
474 
475 } // end CU namespace
476 
477 class DarwinX86AsmBackend : public X86AsmBackend {
478   const MCRegisterInfo &MRI;
479 
480   /// \brief Number of registers that can be saved in a compact unwind encoding.
481   enum { CU_NUM_SAVED_REGS = 6 };
482 
483   mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
484   bool Is64Bit;
485 
486   unsigned OffsetSize;                   ///< Offset of a "push" instruction.
487   unsigned MoveInstrSize;                ///< Size of a "move" instruction.
488   unsigned StackDivide;                  ///< Amount to adjust stack size by.
489 protected:
490   /// \brief Size of a "push" instruction for the given register.
PushInstrSize(unsigned Reg) const491   unsigned PushInstrSize(unsigned Reg) const {
492     switch (Reg) {
493       case X86::EBX:
494       case X86::ECX:
495       case X86::EDX:
496       case X86::EDI:
497       case X86::ESI:
498       case X86::EBP:
499       case X86::RBX:
500       case X86::RBP:
501         return 1;
502       case X86::R12:
503       case X86::R13:
504       case X86::R14:
505       case X86::R15:
506         return 2;
507     }
508     return 1;
509   }
510 
511   /// \brief Implementation of algorithm to generate the compact unwind encoding
512   /// for the CFI instructions.
513   uint32_t
generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const514   generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
515     if (Instrs.empty()) return 0;
516 
517     // Reset the saved registers.
518     unsigned SavedRegIdx = 0;
519     memset(SavedRegs, 0, sizeof(SavedRegs));
520 
521     bool HasFP = false;
522 
523     // Encode that we are using EBP/RBP as the frame pointer.
524     uint32_t CompactUnwindEncoding = 0;
525 
526     unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
527     unsigned InstrOffset = 0;
528     unsigned StackAdjust = 0;
529     unsigned StackSize = 0;
530     unsigned PrevStackSize = 0;
531     unsigned NumDefCFAOffsets = 0;
532 
533     for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
534       const MCCFIInstruction &Inst = Instrs[i];
535 
536       switch (Inst.getOperation()) {
537       default:
538         // Any other CFI directives indicate a frame that we aren't prepared
539         // to represent via compact unwind, so just bail out.
540         return 0;
541       case MCCFIInstruction::OpDefCfaRegister: {
542         // Defines a frame pointer. E.g.
543         //
544         //     movq %rsp, %rbp
545         //  L0:
546         //     .cfi_def_cfa_register %rbp
547         //
548         HasFP = true;
549         assert(MRI.getLLVMRegNum(Inst.getRegister(), true) ==
550                (Is64Bit ? X86::RBP : X86::EBP) && "Invalid frame pointer!");
551 
552         // Reset the counts.
553         memset(SavedRegs, 0, sizeof(SavedRegs));
554         StackAdjust = 0;
555         SavedRegIdx = 0;
556         InstrOffset += MoveInstrSize;
557         break;
558       }
559       case MCCFIInstruction::OpDefCfaOffset: {
560         // Defines a new offset for the CFA. E.g.
561         //
562         //  With frame:
563         //
564         //     pushq %rbp
565         //  L0:
566         //     .cfi_def_cfa_offset 16
567         //
568         //  Without frame:
569         //
570         //     subq $72, %rsp
571         //  L0:
572         //     .cfi_def_cfa_offset 80
573         //
574         PrevStackSize = StackSize;
575         StackSize = std::abs(Inst.getOffset()) / StackDivide;
576         ++NumDefCFAOffsets;
577         break;
578       }
579       case MCCFIInstruction::OpOffset: {
580         // Defines a "push" of a callee-saved register. E.g.
581         //
582         //     pushq %r15
583         //     pushq %r14
584         //     pushq %rbx
585         //  L0:
586         //     subq $120, %rsp
587         //  L1:
588         //     .cfi_offset %rbx, -40
589         //     .cfi_offset %r14, -32
590         //     .cfi_offset %r15, -24
591         //
592         if (SavedRegIdx == CU_NUM_SAVED_REGS)
593           // If there are too many saved registers, we cannot use a compact
594           // unwind encoding.
595           return CU::UNWIND_MODE_DWARF;
596 
597         unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
598         SavedRegs[SavedRegIdx++] = Reg;
599         StackAdjust += OffsetSize;
600         InstrOffset += PushInstrSize(Reg);
601         break;
602       }
603       }
604     }
605 
606     StackAdjust /= StackDivide;
607 
608     if (HasFP) {
609       if ((StackAdjust & 0xFF) != StackAdjust)
610         // Offset was too big for a compact unwind encoding.
611         return CU::UNWIND_MODE_DWARF;
612 
613       // Get the encoding of the saved registers when we have a frame pointer.
614       uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
615       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
616 
617       CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
618       CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
619       CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
620     } else {
621       // If the amount of the stack allocation is the size of a register, then
622       // we "push" the RAX/EAX register onto the stack instead of adjusting the
623       // stack pointer with a SUB instruction. We don't support the push of the
624       // RAX/EAX register with compact unwind. So we check for that situation
625       // here.
626       if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
627            StackSize - PrevStackSize == 1) ||
628           (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
629         return CU::UNWIND_MODE_DWARF;
630 
631       SubtractInstrIdx += InstrOffset;
632       ++StackAdjust;
633 
634       if ((StackSize & 0xFF) == StackSize) {
635         // Frameless stack with a small stack size.
636         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
637 
638         // Encode the stack size.
639         CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
640       } else {
641         if ((StackAdjust & 0x7) != StackAdjust)
642           // The extra stack adjustments are too big for us to handle.
643           return CU::UNWIND_MODE_DWARF;
644 
645         // Frameless stack with an offset too large for us to encode compactly.
646         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
647 
648         // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
649         // instruction.
650         CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
651 
652         // Encode any extra stack stack adjustments (done via push
653         // instructions).
654         CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
655       }
656 
657       // Encode the number of registers saved. (Reverse the list first.)
658       std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
659       CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
660 
661       // Get the encoding of the saved registers when we don't have a frame
662       // pointer.
663       uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
664       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
665 
666       // Encode the register encoding.
667       CompactUnwindEncoding |=
668         RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
669     }
670 
671     return CompactUnwindEncoding;
672   }
673 
674 private:
675   /// \brief Get the compact unwind number for a given register. The number
676   /// corresponds to the enum lists in compact_unwind_encoding.h.
getCompactUnwindRegNum(unsigned Reg) const677   int getCompactUnwindRegNum(unsigned Reg) const {
678     static const MCPhysReg CU32BitRegs[7] = {
679       X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
680     };
681     static const MCPhysReg CU64BitRegs[] = {
682       X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
683     };
684     const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
685     for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
686       if (*CURegs == Reg)
687         return Idx;
688 
689     return -1;
690   }
691 
692   /// \brief Return the registers encoded for a compact encoding with a frame
693   /// pointer.
encodeCompactUnwindRegistersWithFrame() const694   uint32_t encodeCompactUnwindRegistersWithFrame() const {
695     // Encode the registers in the order they were saved --- 3-bits per
696     // register. The list of saved registers is assumed to be in reverse
697     // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
698     uint32_t RegEnc = 0;
699     for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
700       unsigned Reg = SavedRegs[i];
701       if (Reg == 0) break;
702 
703       int CURegNum = getCompactUnwindRegNum(Reg);
704       if (CURegNum == -1) return ~0U;
705 
706       // Encode the 3-bit register number in order, skipping over 3-bits for
707       // each register.
708       RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
709     }
710 
711     assert((RegEnc & 0x3FFFF) == RegEnc &&
712            "Invalid compact register encoding!");
713     return RegEnc;
714   }
715 
716   /// \brief Create the permutation encoding used with frameless stacks. It is
717   /// passed the number of registers to be saved and an array of the registers
718   /// saved.
encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const719   uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
720     // The saved registers are numbered from 1 to 6. In order to encode the
721     // order in which they were saved, we re-number them according to their
722     // place in the register order. The re-numbering is relative to the last
723     // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
724     // that order:
725     //
726     //    Orig  Re-Num
727     //    ----  ------
728     //     6       6
729     //     2       2
730     //     4       3
731     //     5       3
732     //
733     for (unsigned i = 0; i < RegCount; ++i) {
734       int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
735       if (CUReg == -1) return ~0U;
736       SavedRegs[i] = CUReg;
737     }
738 
739     // Reverse the list.
740     std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
741 
742     uint32_t RenumRegs[CU_NUM_SAVED_REGS];
743     for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
744       unsigned Countless = 0;
745       for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
746         if (SavedRegs[j] < SavedRegs[i])
747           ++Countless;
748 
749       RenumRegs[i] = SavedRegs[i] - Countless - 1;
750     }
751 
752     // Take the renumbered values and encode them into a 10-bit number.
753     uint32_t permutationEncoding = 0;
754     switch (RegCount) {
755     case 6:
756       permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
757                              + 6 * RenumRegs[2] +  2 * RenumRegs[3]
758                              +     RenumRegs[4];
759       break;
760     case 5:
761       permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
762                              + 6 * RenumRegs[3] +  2 * RenumRegs[4]
763                              +     RenumRegs[5];
764       break;
765     case 4:
766       permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
767                              + 3 * RenumRegs[4] +      RenumRegs[5];
768       break;
769     case 3:
770       permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
771                              +     RenumRegs[5];
772       break;
773     case 2:
774       permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
775       break;
776     case 1:
777       permutationEncoding |=       RenumRegs[5];
778       break;
779     }
780 
781     assert((permutationEncoding & 0x3FF) == permutationEncoding &&
782            "Invalid compact register encoding!");
783     return permutationEncoding;
784   }
785 
786 public:
DarwinX86AsmBackend(const Target & T,const MCRegisterInfo & MRI,StringRef CPU,bool Is64Bit)787   DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI, StringRef CPU,
788                       bool Is64Bit)
789     : X86AsmBackend(T, CPU), MRI(MRI), Is64Bit(Is64Bit) {
790     memset(SavedRegs, 0, sizeof(SavedRegs));
791     OffsetSize = Is64Bit ? 8 : 4;
792     MoveInstrSize = Is64Bit ? 3 : 2;
793     StackDivide = Is64Bit ? 8 : 4;
794   }
795 };
796 
797 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
798 public:
DarwinX86_32AsmBackend(const Target & T,const MCRegisterInfo & MRI,StringRef CPU)799   DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
800                          StringRef CPU)
801       : DarwinX86AsmBackend(T, MRI, CPU, false) {}
802 
createObjectWriter(raw_pwrite_stream & OS) const803   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
804     return createX86MachObjectWriter(OS, /*Is64Bit=*/false,
805                                      MachO::CPU_TYPE_I386,
806                                      MachO::CPU_SUBTYPE_I386_ALL);
807   }
808 
809   /// \brief Generate the compact unwind encoding for the CFI instructions.
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const810   uint32_t generateCompactUnwindEncoding(
811                              ArrayRef<MCCFIInstruction> Instrs) const override {
812     return generateCompactUnwindEncodingImpl(Instrs);
813   }
814 };
815 
816 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
817   const MachO::CPUSubTypeX86 Subtype;
818 public:
DarwinX86_64AsmBackend(const Target & T,const MCRegisterInfo & MRI,StringRef CPU,MachO::CPUSubTypeX86 st)819   DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
820                          StringRef CPU, MachO::CPUSubTypeX86 st)
821       : DarwinX86AsmBackend(T, MRI, CPU, true), Subtype(st) {}
822 
createObjectWriter(raw_pwrite_stream & OS) const823   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
824     return createX86MachObjectWriter(OS, /*Is64Bit=*/true,
825                                      MachO::CPU_TYPE_X86_64, Subtype);
826   }
827 
828   /// \brief Generate the compact unwind encoding for the CFI instructions.
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const829   uint32_t generateCompactUnwindEncoding(
830                              ArrayRef<MCCFIInstruction> Instrs) const override {
831     return generateCompactUnwindEncodingImpl(Instrs);
832   }
833 };
834 
835 } // end anonymous namespace
836 
createX86_32AsmBackend(const Target & T,const MCRegisterInfo & MRI,const Triple & TheTriple,StringRef CPU)837 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
838                                            const MCRegisterInfo &MRI,
839                                            const Triple &TheTriple,
840                                            StringRef CPU) {
841   if (TheTriple.isOSBinFormatMachO())
842     return new DarwinX86_32AsmBackend(T, MRI, CPU);
843 
844   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
845     return new WindowsX86AsmBackend(T, false, CPU);
846 
847   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
848 
849   if (TheTriple.isOSIAMCU())
850     return new ELFX86_IAMCUAsmBackend(T, OSABI, CPU);
851 
852   return new ELFX86_32AsmBackend(T, OSABI, CPU);
853 }
854 
createX86_64AsmBackend(const Target & T,const MCRegisterInfo & MRI,const Triple & TheTriple,StringRef CPU)855 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
856                                            const MCRegisterInfo &MRI,
857                                            const Triple &TheTriple,
858                                            StringRef CPU) {
859   if (TheTriple.isOSBinFormatMachO()) {
860     MachO::CPUSubTypeX86 CS =
861         StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
862             .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
863             .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
864     return new DarwinX86_64AsmBackend(T, MRI, CPU, CS);
865   }
866 
867   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
868     return new WindowsX86AsmBackend(T, true, CPU);
869 
870   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
871 
872   if (TheTriple.getEnvironment() == Triple::GNUX32)
873     return new ELFX86_X32AsmBackend(T, OSABI, CPU);
874   return new ELFX86_64AsmBackend(T, OSABI, CPU);
875 }
876