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