]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / X86 / MCTargetDesc / X86AsmBackend.cpp
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 X86::reloc_branch_4byte_pcrel:
50   case FK_SecRel_4:
51   case FK_Data_4:
52     return 2;
53   case FK_PCRel_8:
54   case FK_SecRel_8:
55   case FK_Data_8:
56   case X86::reloc_global_offset_table8:
57     return 3;
58   }
59 }
60
61 namespace {
62
63 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
64 public:
65   X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
66                      bool HasRelocationAddend, bool foobar)
67     : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
68 };
69
70 class X86AsmBackend : public MCAsmBackend {
71   const MCSubtargetInfo &STI;
72 public:
73   X86AsmBackend(const Target &T, const MCSubtargetInfo &STI)
74       : MCAsmBackend(support::little), STI(STI) {}
75
76   unsigned getNumFixupKinds() const override {
77     return X86::NumTargetFixupKinds;
78   }
79
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},
91     };
92
93     if (Kind < FirstTargetFixupKind)
94       return MCAsmBackend::getFixupKindInfo(Kind);
95
96     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
97            "Invalid kind!");
98     assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
99     return Infos[Kind - FirstTargetFixupKind];
100   }
101
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());
107
108     assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
109
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
113     // other assemblers.
114     assert(isIntN(Size * 8 + 1, Value) &&
115            "Value does not fit in the Fixup field");
116
117     for (unsigned i = 0; i != Size; ++i)
118       Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
119   }
120
121   bool mayNeedRelaxation(const MCInst &Inst,
122                          const MCSubtargetInfo &STI) const override;
123
124   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
125                             const MCRelaxableFragment *DF,
126                             const MCAsmLayout &Layout) const override;
127
128   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
129                         MCInst &Res) const override;
130
131   bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
132 };
133 } // end anonymous namespace
134
135 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
136   unsigned Op = Inst.getOpcode();
137   switch (Op) {
138   default:
139     return Op;
140   case X86::JAE_1:
141     return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
142   case X86::JA_1:
143     return (is16BitMode) ? X86::JA_2 : X86::JA_4;
144   case X86::JBE_1:
145     return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
146   case X86::JB_1:
147     return (is16BitMode) ? X86::JB_2 : X86::JB_4;
148   case X86::JE_1:
149     return (is16BitMode) ? X86::JE_2 : X86::JE_4;
150   case X86::JGE_1:
151     return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
152   case X86::JG_1:
153     return (is16BitMode) ? X86::JG_2 : X86::JG_4;
154   case X86::JLE_1:
155     return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
156   case X86::JL_1:
157     return (is16BitMode) ? X86::JL_2 : X86::JL_4;
158   case X86::JMP_1:
159     return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
160   case X86::JNE_1:
161     return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
162   case X86::JNO_1:
163     return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
164   case X86::JNP_1:
165     return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
166   case X86::JNS_1:
167     return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
168   case X86::JO_1:
169     return (is16BitMode) ? X86::JO_2 : X86::JO_4;
170   case X86::JP_1:
171     return (is16BitMode) ? X86::JP_2 : X86::JP_4;
172   case X86::JS_1:
173     return (is16BitMode) ? X86::JS_2 : X86::JS_4;
174   }
175 }
176
177 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
178   unsigned Op = Inst.getOpcode();
179   switch (Op) {
180   default:
181     return Op;
182
183     // IMUL
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;
190
191     // AND
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;
198
199     // OR
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;
206
207     // XOR
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;
214
215     // ADD
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;
222
223    // ADC
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;
230
231     // SUB
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;
238
239    // SBB
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;
246
247     // CMP
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;
254
255     // PUSH
256   case X86::PUSH32i8:  return X86::PUSHi32;
257   case X86::PUSH16i8:  return X86::PUSHi16;
258   case X86::PUSH64i8:  return X86::PUSH64i32;
259   }
260 }
261
262 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
263   unsigned R = getRelaxedOpcodeArith(Inst);
264   if (R != Inst.getOpcode())
265     return R;
266   return getRelaxedOpcodeBranch(Inst, is16BitMode);
267 }
268
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())
273     return true;
274
275   // Check if this instruction is ever relaxable.
276   if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
277     return false;
278
279
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())
284     return true;
285
286   return false;
287 }
288
289 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
290                                          uint64_t Value,
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));
295 }
296
297 // FIXME: Can tblgen help at all here to verify there aren't other instructions
298 // we can relax?
299 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
300                                      const MCSubtargetInfo &STI,
301                                      MCInst &Res) const {
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);
305
306   if (RelaxedOp == Inst.getOpcode()) {
307     SmallString<256> Tmp;
308     raw_svector_ostream OS(Tmp);
309     Inst.dump_pretty(OS);
310     OS << "\n";
311     report_fatal_error("unexpected instruction to relax: " + OS.str());
312   }
313
314   Res = Inst;
315   Res.setOpcode(RelaxedOp);
316 }
317
318 /// Write a sequence of optimal nops to the output, covering \p Count
319 /// bytes.
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] = {
323     // nop
324     "\x90",
325     // xchg %ax,%ax
326     "\x66\x90",
327     // nopl (%[re]ax)
328     "\x0f\x1f\x00",
329     // nopl 0(%[re]ax)
330     "\x0f\x1f\x40\x00",
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",
335     // nopl 0L(%[re]ax)
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",
343   };
344
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)
349       OS << '\x90';
350     return true;
351   }
352
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])
357     MaxNopLength = 7;
358   else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
359     MaxNopLength = 15;
360   else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
361     MaxNopLength = 11;
362
363   // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
364   // length.
365   do {
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++)
369       OS << '\x66';
370     const uint8_t Rest = ThisNopLength - Prefixes;
371     if (Rest != 0)
372       OS.write(Nops[Rest - 1], Rest);
373     Count -= ThisNopLength;
374   } while (Count != 0);
375
376   return true;
377 }
378
379 /* *** */
380
381 namespace {
382
383 class ELFX86AsmBackend : public X86AsmBackend {
384 public:
385   uint8_t OSABI;
386   ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
387       : X86AsmBackend(T, STI), OSABI(OSABI) {}
388 };
389
390 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
391 public:
392   ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
393                       const MCSubtargetInfo &STI)
394     : ELFX86AsmBackend(T, OSABI, STI) {}
395
396   std::unique_ptr<MCObjectTargetWriter>
397   createObjectTargetWriter() const override {
398     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
399   }
400 };
401
402 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
403 public:
404   ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
405                        const MCSubtargetInfo &STI)
406       : ELFX86AsmBackend(T, OSABI, STI) {}
407
408   std::unique_ptr<MCObjectTargetWriter>
409   createObjectTargetWriter() const override {
410     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
411                                     ELF::EM_X86_64);
412   }
413 };
414
415 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
416 public:
417   ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
418                          const MCSubtargetInfo &STI)
419       : ELFX86AsmBackend(T, OSABI, STI) {}
420
421   std::unique_ptr<MCObjectTargetWriter>
422   createObjectTargetWriter() const override {
423     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
424                                     ELF::EM_IAMCU);
425   }
426 };
427
428 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
429 public:
430   ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
431                       const MCSubtargetInfo &STI)
432     : ELFX86AsmBackend(T, OSABI, STI) {}
433
434   std::unique_ptr<MCObjectTargetWriter>
435   createObjectTargetWriter() const override {
436     return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
437   }
438 };
439
440 class WindowsX86AsmBackend : public X86AsmBackend {
441   bool Is64Bit;
442
443 public:
444   WindowsX86AsmBackend(const Target &T, bool is64Bit,
445                        const MCSubtargetInfo &STI)
446     : X86AsmBackend(T, STI)
447     , Is64Bit(is64Bit) {
448   }
449
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));
456   }
457
458   std::unique_ptr<MCObjectTargetWriter>
459   createObjectTargetWriter() const override {
460     return createX86WinCOFFObjectWriter(Is64Bit);
461   }
462 };
463
464 namespace CU {
465
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,
471
472     /// A frameless function with a small constant stack size.
473     UNWIND_MODE_STACK_IMMD                 = 0x02000000,
474
475     /// A frameless function with a large constant stack size.
476     UNWIND_MODE_STACK_IND                  = 0x03000000,
477
478     /// No compact unwind encoding is available.
479     UNWIND_MODE_DWARF                      = 0x04000000,
480
481     /// Mask for encoding the frame registers.
482     UNWIND_BP_FRAME_REGISTERS              = 0x00007FFF,
483
484     /// Mask for encoding the frameless registers.
485     UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
486   };
487
488 } // end CU namespace
489
490 class DarwinX86AsmBackend : public X86AsmBackend {
491   const MCRegisterInfo &MRI;
492
493   /// Number of registers that can be saved in a compact unwind encoding.
494   enum { CU_NUM_SAVED_REGS = 6 };
495
496   mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
497   bool Is64Bit;
498
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.
502 protected:
503   /// Size of a "push" instruction for the given register.
504   unsigned PushInstrSize(unsigned Reg) const {
505     switch (Reg) {
506       case X86::EBX:
507       case X86::ECX:
508       case X86::EDX:
509       case X86::EDI:
510       case X86::ESI:
511       case X86::EBP:
512       case X86::RBX:
513       case X86::RBP:
514         return 1;
515       case X86::R12:
516       case X86::R13:
517       case X86::R14:
518       case X86::R15:
519         return 2;
520     }
521     return 1;
522   }
523
524   /// Implementation of algorithm to generate the compact unwind encoding
525   /// for the CFI instructions.
526   uint32_t
527   generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
528     if (Instrs.empty()) return 0;
529
530     // Reset the saved registers.
531     unsigned SavedRegIdx = 0;
532     memset(SavedRegs, 0, sizeof(SavedRegs));
533
534     bool HasFP = false;
535
536     // Encode that we are using EBP/RBP as the frame pointer.
537     uint32_t CompactUnwindEncoding = 0;
538
539     unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
540     unsigned InstrOffset = 0;
541     unsigned StackAdjust = 0;
542     unsigned StackSize = 0;
543     unsigned NumDefCFAOffsets = 0;
544
545     for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
546       const MCCFIInstruction &Inst = Instrs[i];
547
548       switch (Inst.getOperation()) {
549       default:
550         // Any other CFI directives indicate a frame that we aren't prepared
551         // to represent via compact unwind, so just bail out.
552         return 0;
553       case MCCFIInstruction::OpDefCfaRegister: {
554         // Defines a frame pointer. E.g.
555         //
556         //     movq %rsp, %rbp
557         //  L0:
558         //     .cfi_def_cfa_register %rbp
559         //
560         HasFP = true;
561
562         // If the frame pointer is other than esp/rsp, we do not have a way to
563         // generate a compact unwinding representation, so bail out.
564         if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
565             (Is64Bit ? X86::RBP : X86::EBP))
566           return 0;
567
568         // Reset the counts.
569         memset(SavedRegs, 0, sizeof(SavedRegs));
570         StackAdjust = 0;
571         SavedRegIdx = 0;
572         InstrOffset += MoveInstrSize;
573         break;
574       }
575       case MCCFIInstruction::OpDefCfaOffset: {
576         // Defines a new offset for the CFA. E.g.
577         //
578         //  With frame:
579         //
580         //     pushq %rbp
581         //  L0:
582         //     .cfi_def_cfa_offset 16
583         //
584         //  Without frame:
585         //
586         //     subq $72, %rsp
587         //  L0:
588         //     .cfi_def_cfa_offset 80
589         //
590         StackSize = std::abs(Inst.getOffset()) / StackDivide;
591         ++NumDefCFAOffsets;
592         break;
593       }
594       case MCCFIInstruction::OpOffset: {
595         // Defines a "push" of a callee-saved register. E.g.
596         //
597         //     pushq %r15
598         //     pushq %r14
599         //     pushq %rbx
600         //  L0:
601         //     subq $120, %rsp
602         //  L1:
603         //     .cfi_offset %rbx, -40
604         //     .cfi_offset %r14, -32
605         //     .cfi_offset %r15, -24
606         //
607         if (SavedRegIdx == CU_NUM_SAVED_REGS)
608           // If there are too many saved registers, we cannot use a compact
609           // unwind encoding.
610           return CU::UNWIND_MODE_DWARF;
611
612         unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
613         SavedRegs[SavedRegIdx++] = Reg;
614         StackAdjust += OffsetSize;
615         InstrOffset += PushInstrSize(Reg);
616         break;
617       }
618       }
619     }
620
621     StackAdjust /= StackDivide;
622
623     if (HasFP) {
624       if ((StackAdjust & 0xFF) != StackAdjust)
625         // Offset was too big for a compact unwind encoding.
626         return CU::UNWIND_MODE_DWARF;
627
628       // Get the encoding of the saved registers when we have a frame pointer.
629       uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
630       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
631
632       CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
633       CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
634       CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
635     } else {
636       SubtractInstrIdx += InstrOffset;
637       ++StackAdjust;
638
639       if ((StackSize & 0xFF) == StackSize) {
640         // Frameless stack with a small stack size.
641         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
642
643         // Encode the stack size.
644         CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
645       } else {
646         if ((StackAdjust & 0x7) != StackAdjust)
647           // The extra stack adjustments are too big for us to handle.
648           return CU::UNWIND_MODE_DWARF;
649
650         // Frameless stack with an offset too large for us to encode compactly.
651         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
652
653         // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
654         // instruction.
655         CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
656
657         // Encode any extra stack adjustments (done via push instructions).
658         CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
659       }
660
661       // Encode the number of registers saved. (Reverse the list first.)
662       std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
663       CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
664
665       // Get the encoding of the saved registers when we don't have a frame
666       // pointer.
667       uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
668       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
669
670       // Encode the register encoding.
671       CompactUnwindEncoding |=
672         RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
673     }
674
675     return CompactUnwindEncoding;
676   }
677
678 private:
679   /// Get the compact unwind number for a given register. The number
680   /// corresponds to the enum lists in compact_unwind_encoding.h.
681   int getCompactUnwindRegNum(unsigned Reg) const {
682     static const MCPhysReg CU32BitRegs[7] = {
683       X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
684     };
685     static const MCPhysReg CU64BitRegs[] = {
686       X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
687     };
688     const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
689     for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
690       if (*CURegs == Reg)
691         return Idx;
692
693     return -1;
694   }
695
696   /// Return the registers encoded for a compact encoding with a frame
697   /// pointer.
698   uint32_t encodeCompactUnwindRegistersWithFrame() const {
699     // Encode the registers in the order they were saved --- 3-bits per
700     // register. The list of saved registers is assumed to be in reverse
701     // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
702     uint32_t RegEnc = 0;
703     for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
704       unsigned Reg = SavedRegs[i];
705       if (Reg == 0) break;
706
707       int CURegNum = getCompactUnwindRegNum(Reg);
708       if (CURegNum == -1) return ~0U;
709
710       // Encode the 3-bit register number in order, skipping over 3-bits for
711       // each register.
712       RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
713     }
714
715     assert((RegEnc & 0x3FFFF) == RegEnc &&
716            "Invalid compact register encoding!");
717     return RegEnc;
718   }
719
720   /// Create the permutation encoding used with frameless stacks. It is
721   /// passed the number of registers to be saved and an array of the registers
722   /// saved.
723   uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
724     // The saved registers are numbered from 1 to 6. In order to encode the
725     // order in which they were saved, we re-number them according to their
726     // place in the register order. The re-numbering is relative to the last
727     // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
728     // that order:
729     //
730     //    Orig  Re-Num
731     //    ----  ------
732     //     6       6
733     //     2       2
734     //     4       3
735     //     5       3
736     //
737     for (unsigned i = 0; i < RegCount; ++i) {
738       int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
739       if (CUReg == -1) return ~0U;
740       SavedRegs[i] = CUReg;
741     }
742
743     // Reverse the list.
744     std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
745
746     uint32_t RenumRegs[CU_NUM_SAVED_REGS];
747     for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
748       unsigned Countless = 0;
749       for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
750         if (SavedRegs[j] < SavedRegs[i])
751           ++Countless;
752
753       RenumRegs[i] = SavedRegs[i] - Countless - 1;
754     }
755
756     // Take the renumbered values and encode them into a 10-bit number.
757     uint32_t permutationEncoding = 0;
758     switch (RegCount) {
759     case 6:
760       permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
761                              + 6 * RenumRegs[2] +  2 * RenumRegs[3]
762                              +     RenumRegs[4];
763       break;
764     case 5:
765       permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
766                              + 6 * RenumRegs[3] +  2 * RenumRegs[4]
767                              +     RenumRegs[5];
768       break;
769     case 4:
770       permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
771                              + 3 * RenumRegs[4] +      RenumRegs[5];
772       break;
773     case 3:
774       permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
775                              +     RenumRegs[5];
776       break;
777     case 2:
778       permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
779       break;
780     case 1:
781       permutationEncoding |=       RenumRegs[5];
782       break;
783     }
784
785     assert((permutationEncoding & 0x3FF) == permutationEncoding &&
786            "Invalid compact register encoding!");
787     return permutationEncoding;
788   }
789
790 public:
791   DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
792                       const MCSubtargetInfo &STI, bool Is64Bit)
793     : X86AsmBackend(T, STI), MRI(MRI), Is64Bit(Is64Bit) {
794     memset(SavedRegs, 0, sizeof(SavedRegs));
795     OffsetSize = Is64Bit ? 8 : 4;
796     MoveInstrSize = Is64Bit ? 3 : 2;
797     StackDivide = Is64Bit ? 8 : 4;
798   }
799 };
800
801 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
802 public:
803   DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
804                          const MCSubtargetInfo &STI)
805       : DarwinX86AsmBackend(T, MRI, STI, false) {}
806
807   std::unique_ptr<MCObjectTargetWriter>
808   createObjectTargetWriter() const override {
809     return createX86MachObjectWriter(/*Is64Bit=*/false,
810                                      MachO::CPU_TYPE_I386,
811                                      MachO::CPU_SUBTYPE_I386_ALL);
812   }
813
814   /// Generate the compact unwind encoding for the CFI instructions.
815   uint32_t generateCompactUnwindEncoding(
816                              ArrayRef<MCCFIInstruction> Instrs) const override {
817     return generateCompactUnwindEncodingImpl(Instrs);
818   }
819 };
820
821 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
822   const MachO::CPUSubTypeX86 Subtype;
823 public:
824   DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
825                          const MCSubtargetInfo &STI, MachO::CPUSubTypeX86 st)
826       : DarwinX86AsmBackend(T, MRI, STI, true), Subtype(st) {}
827
828   std::unique_ptr<MCObjectTargetWriter>
829   createObjectTargetWriter() const override {
830     return createX86MachObjectWriter(/*Is64Bit=*/true, MachO::CPU_TYPE_X86_64,
831                                      Subtype);
832   }
833
834   /// Generate the compact unwind encoding for the CFI instructions.
835   uint32_t generateCompactUnwindEncoding(
836                              ArrayRef<MCCFIInstruction> Instrs) const override {
837     return generateCompactUnwindEncodingImpl(Instrs);
838   }
839 };
840
841 } // end anonymous namespace
842
843 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
844                                            const MCSubtargetInfo &STI,
845                                            const MCRegisterInfo &MRI,
846                                            const MCTargetOptions &Options) {
847   const Triple &TheTriple = STI.getTargetTriple();
848   if (TheTriple.isOSBinFormatMachO())
849     return new DarwinX86_32AsmBackend(T, MRI, STI);
850
851   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
852     return new WindowsX86AsmBackend(T, false, STI);
853
854   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
855
856   if (TheTriple.isOSIAMCU())
857     return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
858
859   return new ELFX86_32AsmBackend(T, OSABI, STI);
860 }
861
862 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
863                                            const MCSubtargetInfo &STI,
864                                            const MCRegisterInfo &MRI,
865                                            const MCTargetOptions &Options) {
866   const Triple &TheTriple = STI.getTargetTriple();
867   if (TheTriple.isOSBinFormatMachO()) {
868     MachO::CPUSubTypeX86 CS =
869         StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
870             .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
871             .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
872     return new DarwinX86_64AsmBackend(T, MRI, STI, CS);
873   }
874
875   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
876     return new WindowsX86AsmBackend(T, true, STI);
877
878   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
879
880   if (TheTriple.getEnvironment() == Triple::GNUX32)
881     return new ELFX86_X32AsmBackend(T, OSABI, STI);
882   return new ELFX86_64AsmBackend(T, OSABI, STI);
883 }