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