LLVM  7.0.0svn
X86AsmBackend.cpp
Go to the documentation of this file.
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 
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/BinaryFormat/ELF.h"
15 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionMachO.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:
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:
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(), STI(STI) {}
75 
76  unsigned getNumFixupKinds() const override {
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,
104  uint64_t Value, bool IsResolved) const override {
105  unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
106 
107  assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
108 
109  // Check that uppper bits are either all zeros or all ones.
110  // Specifically ignore overflow/underflow as long as the leakage is
111  // limited to the lower bits. This is to remain compatible with
112  // other assemblers.
113  assert(isIntN(Size * 8 + 1, Value) &&
114  "Value does not fit in the Fixup field");
115 
116  for (unsigned i = 0; i != Size; ++i)
117  Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
118  }
119 
120  bool mayNeedRelaxation(const MCInst &Inst) const override;
121 
122  bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
123  const MCRelaxableFragment *DF,
124  const MCAsmLayout &Layout) const override;
125 
126  void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
127  MCInst &Res) const override;
128 
129  bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override;
130 };
131 } // end anonymous namespace
132 
133 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
134  unsigned Op = Inst.getOpcode();
135  switch (Op) {
136  default:
137  return Op;
138  case X86::JAE_1:
139  return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
140  case X86::JA_1:
141  return (is16BitMode) ? X86::JA_2 : X86::JA_4;
142  case X86::JBE_1:
143  return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
144  case X86::JB_1:
145  return (is16BitMode) ? X86::JB_2 : X86::JB_4;
146  case X86::JE_1:
147  return (is16BitMode) ? X86::JE_2 : X86::JE_4;
148  case X86::JGE_1:
149  return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
150  case X86::JG_1:
151  return (is16BitMode) ? X86::JG_2 : X86::JG_4;
152  case X86::JLE_1:
153  return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
154  case X86::JL_1:
155  return (is16BitMode) ? X86::JL_2 : X86::JL_4;
156  case X86::JMP_1:
157  return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
158  case X86::JNE_1:
159  return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
160  case X86::JNO_1:
161  return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
162  case X86::JNP_1:
163  return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
164  case X86::JNS_1:
165  return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
166  case X86::JO_1:
167  return (is16BitMode) ? X86::JO_2 : X86::JO_4;
168  case X86::JP_1:
169  return (is16BitMode) ? X86::JP_2 : X86::JP_4;
170  case X86::JS_1:
171  return (is16BitMode) ? X86::JS_2 : X86::JS_4;
172  }
173 }
174 
175 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
176  unsigned Op = Inst.getOpcode();
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  // ADC
222  case X86::ADC16ri8: return X86::ADC16ri;
223  case X86::ADC16mi8: return X86::ADC16mi;
224  case X86::ADC32ri8: return X86::ADC32ri;
225  case X86::ADC32mi8: return X86::ADC32mi;
226  case X86::ADC64ri8: return X86::ADC64ri32;
227  case X86::ADC64mi8: return X86::ADC64mi32;
228 
229  // SUB
230  case X86::SUB16ri8: return X86::SUB16ri;
231  case X86::SUB16mi8: return X86::SUB16mi;
232  case X86::SUB32ri8: return X86::SUB32ri;
233  case X86::SUB32mi8: return X86::SUB32mi;
234  case X86::SUB64ri8: return X86::SUB64ri32;
235  case X86::SUB64mi8: return X86::SUB64mi32;
236 
237  // SBB
238  case X86::SBB16ri8: return X86::SBB16ri;
239  case X86::SBB16mi8: return X86::SBB16mi;
240  case X86::SBB32ri8: return X86::SBB32ri;
241  case X86::SBB32mi8: return X86::SBB32mi;
242  case X86::SBB64ri8: return X86::SBB64ri32;
243  case X86::SBB64mi8: return X86::SBB64mi32;
244 
245  // CMP
246  case X86::CMP16ri8: return X86::CMP16ri;
247  case X86::CMP16mi8: return X86::CMP16mi;
248  case X86::CMP32ri8: return X86::CMP32ri;
249  case X86::CMP32mi8: return X86::CMP32mi;
250  case X86::CMP64ri8: return X86::CMP64ri32;
251  case X86::CMP64mi8: return X86::CMP64mi32;
252 
253  // PUSH
254  case X86::PUSH32i8: return X86::PUSHi32;
255  case X86::PUSH16i8: return X86::PUSHi16;
256  case X86::PUSH64i8: return X86::PUSH64i32;
257  }
258 }
259 
260 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
261  unsigned R = getRelaxedOpcodeArith(Inst);
262  if (R != Inst.getOpcode())
263  return R;
264  return getRelaxedOpcodeBranch(Inst, is16BitMode);
265 }
266 
267 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
268  // Branches can always be relaxed in either mode.
269  if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
270  return true;
271 
272  // Check if this instruction is ever relaxable.
273  if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
274  return false;
275 
276 
277  // Check if the relaxable operand has an expression. For the current set of
278  // relaxable instructions, the relaxable operand is always the last operand.
279  unsigned RelaxableOp = Inst.getNumOperands() - 1;
280  if (Inst.getOperand(RelaxableOp).isExpr())
281  return true;
282 
283  return false;
284 }
285 
286 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
287  uint64_t Value,
288  const MCRelaxableFragment *DF,
289  const MCAsmLayout &Layout) const {
290  // Relax if the value is too big for a (signed) i8.
291  return int64_t(Value) != int64_t(int8_t(Value));
292 }
293 
294 // FIXME: Can tblgen help at all here to verify there aren't other instructions
295 // we can relax?
296 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
297  const MCSubtargetInfo &STI,
298  MCInst &Res) const {
299  // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
300  bool is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
301  unsigned RelaxedOp = getRelaxedOpcode(Inst, is16BitMode);
302 
303  if (RelaxedOp == Inst.getOpcode()) {
304  SmallString<256> Tmp;
305  raw_svector_ostream OS(Tmp);
306  Inst.dump_pretty(OS);
307  OS << "\n";
308  report_fatal_error("unexpected instruction to relax: " + OS.str());
309  }
310 
311  Res = Inst;
312  Res.setOpcode(RelaxedOp);
313 }
314 
315 /// \brief Write a sequence of optimal nops to the output, covering \p Count
316 /// bytes.
317 /// \return - true on success, false on failure
318 bool X86AsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
319  static const uint8_t Nops[10][10] = {
320  // nop
321  {0x90},
322  // xchg %ax,%ax
323  {0x66, 0x90},
324  // nopl (%[re]ax)
325  {0x0f, 0x1f, 0x00},
326  // nopl 0(%[re]ax)
327  {0x0f, 0x1f, 0x40, 0x00},
328  // nopl 0(%[re]ax,%[re]ax,1)
329  {0x0f, 0x1f, 0x44, 0x00, 0x00},
330  // nopw 0(%[re]ax,%[re]ax,1)
331  {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
332  // nopl 0L(%[re]ax)
333  {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
334  // nopl 0L(%[re]ax,%[re]ax,1)
335  {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
336  // nopw 0L(%[re]ax,%[re]ax,1)
337  {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
338  // nopw %cs:0L(%[re]ax,%[re]ax,1)
339  {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
340  };
341 
342  // This CPU doesn't support long nops. If needed add more.
343  // FIXME: We could generated something better than plain 0x90.
344  if (!STI.getFeatureBits()[X86::FeatureNOPL]) {
345  for (uint64_t i = 0; i < Count; ++i)
346  OW->write8(0x90);
347  return true;
348  }
349 
350  // 15-bytes is the longest single NOP instruction, but 10-bytes is
351  // commonly the longest that can be efficiently decoded.
352  uint64_t MaxNopLength = 10;
353  if (STI.getFeatureBits()[X86::ProcIntelSLM])
354  MaxNopLength = 7;
355  else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
356  MaxNopLength = 15;
357  else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
358  MaxNopLength = 11;
359 
360  // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
361  // length.
362  do {
363  const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
364  const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
365  for (uint8_t i = 0; i < Prefixes; i++)
366  OW->write8(0x66);
367  const uint8_t Rest = ThisNopLength - Prefixes;
368  for (uint8_t i = 0; i < Rest; i++)
369  OW->write8(Nops[Rest - 1][i]);
370  Count -= ThisNopLength;
371  } while (Count != 0);
372 
373  return true;
374 }
375 
376 /* *** */
377 
378 namespace {
379 
380 class ELFX86AsmBackend : public X86AsmBackend {
381 public:
382  uint8_t OSABI;
383  ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
384  : X86AsmBackend(T, STI), OSABI(OSABI) {}
385 };
386 
387 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
388 public:
389  ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
390  const MCSubtargetInfo &STI)
391  : ELFX86AsmBackend(T, OSABI, STI) {}
392 
393  std::unique_ptr<MCObjectWriter>
394  createObjectWriter(raw_pwrite_stream &OS) const override {
395  return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI, ELF::EM_386);
396  }
397 };
398 
399 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
400 public:
401  ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
402  const MCSubtargetInfo &STI)
403  : ELFX86AsmBackend(T, OSABI, STI) {}
404 
405  std::unique_ptr<MCObjectWriter>
406  createObjectWriter(raw_pwrite_stream &OS) const override {
407  return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
409  }
410 };
411 
412 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
413 public:
414  ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
415  const MCSubtargetInfo &STI)
416  : ELFX86AsmBackend(T, OSABI, STI) {}
417 
418  std::unique_ptr<MCObjectWriter>
419  createObjectWriter(raw_pwrite_stream &OS) const override {
420  return createX86ELFObjectWriter(OS, /*IsELF64*/ false, OSABI,
421  ELF::EM_IAMCU);
422  }
423 };
424 
425 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
426 public:
427  ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
428  const MCSubtargetInfo &STI)
429  : ELFX86AsmBackend(T, OSABI, STI) {}
430 
431  std::unique_ptr<MCObjectWriter>
432  createObjectWriter(raw_pwrite_stream &OS) const override {
433  return createX86ELFObjectWriter(OS, /*IsELF64*/ true, OSABI, ELF::EM_X86_64);
434  }
435 };
436 
437 class WindowsX86AsmBackend : public X86AsmBackend {
438  bool Is64Bit;
439 
440 public:
441  WindowsX86AsmBackend(const Target &T, bool is64Bit,
442  const MCSubtargetInfo &STI)
443  : X86AsmBackend(T, STI)
444  , Is64Bit(is64Bit) {
445  }
446 
447  Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
449  .Case("dir32", FK_Data_4)
450  .Case("secrel32", FK_SecRel_4)
451  .Case("secidx", FK_SecRel_2)
453  }
454 
455  std::unique_ptr<MCObjectWriter>
456  createObjectWriter(raw_pwrite_stream &OS) const override {
457  return createX86WinCOFFObjectWriter(OS, Is64Bit);
458  }
459 };
460 
461 namespace CU {
462 
463  /// Compact unwind encoding values.
465  /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
466  /// the return address, then [RE]SP is moved to [RE]BP.
467  UNWIND_MODE_BP_FRAME = 0x01000000,
468 
469  /// A frameless function with a small constant stack size.
470  UNWIND_MODE_STACK_IMMD = 0x02000000,
471 
472  /// A frameless function with a large constant stack size.
473  UNWIND_MODE_STACK_IND = 0x03000000,
474 
475  /// No compact unwind encoding is available.
476  UNWIND_MODE_DWARF = 0x04000000,
477 
478  /// Mask for encoding the frame registers.
479  UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
480 
481  /// Mask for encoding the frameless registers.
482  UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
483  };
484 
485 } // end CU namespace
486 
487 class DarwinX86AsmBackend : public X86AsmBackend {
488  const MCRegisterInfo &MRI;
489 
490  /// \brief Number of registers that can be saved in a compact unwind encoding.
491  enum { CU_NUM_SAVED_REGS = 6 };
492 
493  mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
494  bool Is64Bit;
495 
496  unsigned OffsetSize; ///< Offset of a "push" instruction.
497  unsigned MoveInstrSize; ///< Size of a "move" instruction.
498  unsigned StackDivide; ///< Amount to adjust stack size by.
499 protected:
500  /// \brief Size of a "push" instruction for the given register.
501  unsigned PushInstrSize(unsigned Reg) const {
502  switch (Reg) {
503  case X86::EBX:
504  case X86::ECX:
505  case X86::EDX:
506  case X86::EDI:
507  case X86::ESI:
508  case X86::EBP:
509  case X86::RBX:
510  case X86::RBP:
511  return 1;
512  case X86::R12:
513  case X86::R13:
514  case X86::R14:
515  case X86::R15:
516  return 2;
517  }
518  return 1;
519  }
520 
521  /// \brief Implementation of algorithm to generate the compact unwind encoding
522  /// for the CFI instructions.
523  uint32_t
524  generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
525  if (Instrs.empty()) return 0;
526 
527  // Reset the saved registers.
528  unsigned SavedRegIdx = 0;
529  memset(SavedRegs, 0, sizeof(SavedRegs));
530 
531  bool HasFP = false;
532 
533  // Encode that we are using EBP/RBP as the frame pointer.
534  uint32_t CompactUnwindEncoding = 0;
535 
536  unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
537  unsigned InstrOffset = 0;
538  unsigned StackAdjust = 0;
539  unsigned StackSize = 0;
540  unsigned PrevStackSize = 0;
541  unsigned NumDefCFAOffsets = 0;
542 
543  for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
544  const MCCFIInstruction &Inst = Instrs[i];
545 
546  switch (Inst.getOperation()) {
547  default:
548  // Any other CFI directives indicate a frame that we aren't prepared
549  // to represent via compact unwind, so just bail out.
550  return 0;
552  // Defines a frame pointer. E.g.
553  //
554  // movq %rsp, %rbp
555  // L0:
556  // .cfi_def_cfa_register %rbp
557  //
558  HasFP = true;
559 
560  // If the frame pointer is other than esp/rsp, we do not have a way to
561  // generate a compact unwinding representation, so bail out.
562  if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
563  (Is64Bit ? X86::RBP : X86::EBP))
564  return 0;
565 
566  // Reset the counts.
567  memset(SavedRegs, 0, sizeof(SavedRegs));
568  StackAdjust = 0;
569  SavedRegIdx = 0;
570  InstrOffset += MoveInstrSize;
571  break;
572  }
574  // Defines a new offset for the CFA. E.g.
575  //
576  // With frame:
577  //
578  // pushq %rbp
579  // L0:
580  // .cfi_def_cfa_offset 16
581  //
582  // Without frame:
583  //
584  // subq $72, %rsp
585  // L0:
586  // .cfi_def_cfa_offset 80
587  //
588  PrevStackSize = StackSize;
589  StackSize = std::abs(Inst.getOffset()) / StackDivide;
590  ++NumDefCFAOffsets;
591  break;
592  }
594  // Defines a "push" of a callee-saved register. E.g.
595  //
596  // pushq %r15
597  // pushq %r14
598  // pushq %rbx
599  // L0:
600  // subq $120, %rsp
601  // L1:
602  // .cfi_offset %rbx, -40
603  // .cfi_offset %r14, -32
604  // .cfi_offset %r15, -24
605  //
606  if (SavedRegIdx == CU_NUM_SAVED_REGS)
607  // If there are too many saved registers, we cannot use a compact
608  // unwind encoding.
609  return CU::UNWIND_MODE_DWARF;
610 
611  unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
612  SavedRegs[SavedRegIdx++] = Reg;
613  StackAdjust += OffsetSize;
614  InstrOffset += PushInstrSize(Reg);
615  break;
616  }
617  }
618  }
619 
620  StackAdjust /= StackDivide;
621 
622  if (HasFP) {
623  if ((StackAdjust & 0xFF) != StackAdjust)
624  // Offset was too big for a compact unwind encoding.
625  return CU::UNWIND_MODE_DWARF;
626 
627  // Get the encoding of the saved registers when we have a frame pointer.
628  uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
629  if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
630 
631  CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
632  CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
633  CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
634  } else {
635  // If the amount of the stack allocation is the size of a register, then
636  // we "push" the RAX/EAX register onto the stack instead of adjusting the
637  // stack pointer with a SUB instruction. We don't support the push of the
638  // RAX/EAX register with compact unwind. So we check for that situation
639  // here.
640  if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
641  StackSize - PrevStackSize == 1) ||
642  (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
643  return CU::UNWIND_MODE_DWARF;
644 
645  SubtractInstrIdx += InstrOffset;
646  ++StackAdjust;
647 
648  if ((StackSize & 0xFF) == StackSize) {
649  // Frameless stack with a small stack size.
650  CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
651 
652  // Encode the stack size.
653  CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
654  } else {
655  if ((StackAdjust & 0x7) != StackAdjust)
656  // The extra stack adjustments are too big for us to handle.
657  return CU::UNWIND_MODE_DWARF;
658 
659  // Frameless stack with an offset too large for us to encode compactly.
660  CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
661 
662  // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
663  // instruction.
664  CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
665 
666  // Encode any extra stack stack adjustments (done via push
667  // instructions).
668  CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
669  }
670 
671  // Encode the number of registers saved. (Reverse the list first.)
672  std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
673  CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
674 
675  // Get the encoding of the saved registers when we don't have a frame
676  // pointer.
677  uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
678  if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
679 
680  // Encode the register encoding.
681  CompactUnwindEncoding |=
682  RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
683  }
684 
685  return CompactUnwindEncoding;
686  }
687 
688 private:
689  /// \brief Get the compact unwind number for a given register. The number
690  /// corresponds to the enum lists in compact_unwind_encoding.h.
691  int getCompactUnwindRegNum(unsigned Reg) const {
692  static const MCPhysReg CU32BitRegs[7] = {
693  X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
694  };
695  static const MCPhysReg CU64BitRegs[] = {
696  X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
697  };
698  const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
699  for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
700  if (*CURegs == Reg)
701  return Idx;
702 
703  return -1;
704  }
705 
706  /// \brief Return the registers encoded for a compact encoding with a frame
707  /// pointer.
708  uint32_t encodeCompactUnwindRegistersWithFrame() const {
709  // Encode the registers in the order they were saved --- 3-bits per
710  // register. The list of saved registers is assumed to be in reverse
711  // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
712  uint32_t RegEnc = 0;
713  for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
714  unsigned Reg = SavedRegs[i];
715  if (Reg == 0) break;
716 
717  int CURegNum = getCompactUnwindRegNum(Reg);
718  if (CURegNum == -1) return ~0U;
719 
720  // Encode the 3-bit register number in order, skipping over 3-bits for
721  // each register.
722  RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
723  }
724 
725  assert((RegEnc & 0x3FFFF) == RegEnc &&
726  "Invalid compact register encoding!");
727  return RegEnc;
728  }
729 
730  /// \brief Create the permutation encoding used with frameless stacks. It is
731  /// passed the number of registers to be saved and an array of the registers
732  /// saved.
733  uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
734  // The saved registers are numbered from 1 to 6. In order to encode the
735  // order in which they were saved, we re-number them according to their
736  // place in the register order. The re-numbering is relative to the last
737  // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
738  // that order:
739  //
740  // Orig Re-Num
741  // ---- ------
742  // 6 6
743  // 2 2
744  // 4 3
745  // 5 3
746  //
747  for (unsigned i = 0; i < RegCount; ++i) {
748  int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
749  if (CUReg == -1) return ~0U;
750  SavedRegs[i] = CUReg;
751  }
752 
753  // Reverse the list.
754  std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
755 
756  uint32_t RenumRegs[CU_NUM_SAVED_REGS];
757  for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
758  unsigned Countless = 0;
759  for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
760  if (SavedRegs[j] < SavedRegs[i])
761  ++Countless;
762 
763  RenumRegs[i] = SavedRegs[i] - Countless - 1;
764  }
765 
766  // Take the renumbered values and encode them into a 10-bit number.
767  uint32_t permutationEncoding = 0;
768  switch (RegCount) {
769  case 6:
770  permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
771  + 6 * RenumRegs[2] + 2 * RenumRegs[3]
772  + RenumRegs[4];
773  break;
774  case 5:
775  permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
776  + 6 * RenumRegs[3] + 2 * RenumRegs[4]
777  + RenumRegs[5];
778  break;
779  case 4:
780  permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
781  + 3 * RenumRegs[4] + RenumRegs[5];
782  break;
783  case 3:
784  permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
785  + RenumRegs[5];
786  break;
787  case 2:
788  permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
789  break;
790  case 1:
791  permutationEncoding |= RenumRegs[5];
792  break;
793  }
794 
795  assert((permutationEncoding & 0x3FF) == permutationEncoding &&
796  "Invalid compact register encoding!");
797  return permutationEncoding;
798  }
799 
800 public:
801  DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
802  const MCSubtargetInfo &STI, bool Is64Bit)
803  : X86AsmBackend(T, STI), MRI(MRI), Is64Bit(Is64Bit) {
804  memset(SavedRegs, 0, sizeof(SavedRegs));
805  OffsetSize = Is64Bit ? 8 : 4;
806  MoveInstrSize = Is64Bit ? 3 : 2;
807  StackDivide = Is64Bit ? 8 : 4;
808  }
809 };
810 
811 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
812 public:
813  DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
814  const MCSubtargetInfo &STI)
815  : DarwinX86AsmBackend(T, MRI, STI, false) {}
816 
817  std::unique_ptr<MCObjectWriter>
818  createObjectWriter(raw_pwrite_stream &OS) const override {
819  return createX86MachObjectWriter(OS, /*Is64Bit=*/false,
822  }
823 
824  /// \brief Generate the compact unwind encoding for the CFI instructions.
825  uint32_t generateCompactUnwindEncoding(
826  ArrayRef<MCCFIInstruction> Instrs) const override {
827  return generateCompactUnwindEncodingImpl(Instrs);
828  }
829 };
830 
831 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
832  const MachO::CPUSubTypeX86 Subtype;
833 public:
834  DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
835  const MCSubtargetInfo &STI, MachO::CPUSubTypeX86 st)
836  : DarwinX86AsmBackend(T, MRI, STI, true), Subtype(st) {}
837 
838  std::unique_ptr<MCObjectWriter>
839  createObjectWriter(raw_pwrite_stream &OS) const override {
840  return createX86MachObjectWriter(OS, /*Is64Bit=*/true,
841  MachO::CPU_TYPE_X86_64, Subtype);
842  }
843 
844  /// \brief Generate the compact unwind encoding for the CFI instructions.
845  uint32_t generateCompactUnwindEncoding(
846  ArrayRef<MCCFIInstruction> Instrs) const override {
847  return generateCompactUnwindEncodingImpl(Instrs);
848  }
849 };
850 
851 } // end anonymous namespace
852 
854  const MCSubtargetInfo &STI,
855  const MCRegisterInfo &MRI,
856  const MCTargetOptions &Options) {
857  const Triple &TheTriple = STI.getTargetTriple();
858  if (TheTriple.isOSBinFormatMachO())
859  return new DarwinX86_32AsmBackend(T, MRI, STI);
860 
861  if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
862  return new WindowsX86AsmBackend(T, false, STI);
863 
864  uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
865 
866  if (TheTriple.isOSIAMCU())
867  return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
868 
869  return new ELFX86_32AsmBackend(T, OSABI, STI);
870 }
871 
873  const MCSubtargetInfo &STI,
874  const MCRegisterInfo &MRI,
875  const MCTargetOptions &Options) {
876  const Triple &TheTriple = STI.getTargetTriple();
877  if (TheTriple.isOSBinFormatMachO()) {
880  .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
882  return new DarwinX86_64AsmBackend(T, MRI, STI, CS);
883  }
884 
885  if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
886  return new WindowsX86AsmBackend(T, true, STI);
887 
888  uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
889 
890  if (TheTriple.getEnvironment() == Triple::GNUX32)
891  return new ELFX86_X32AsmBackend(T, OSABI, STI);
892  return new ELFX86_64AsmBackend(T, OSABI, STI);
893 }
std::unique_ptr< MCObjectWriter > createX86MachObjectWriter(raw_pwrite_stream &OS, bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype)
Construct an X86 Mach-O object writer.
A eight-byte pc relative fixup.
Definition: MCFixup.h:31
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
This represents an "assembler immediate".
Definition: MCValue.h:40
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:294
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
void dump_pretty(raw_ostream &OS, const MCInstPrinter *Printer=nullptr, StringRef Separator=" ") const
Dump the MCInst as prettily as possible using the additional MC structures, if given.
Definition: MCInst.cpp:54
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:489
Defines the object file and target independent interfaces used by the assembler backend to write nati...
void write8(uint8_t Value)
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:66
const Triple & getTargetTriple() const
getTargetTriple - Return the target triple string.
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
A one-byte pc relative fixup.
Definition: MCFixup.h:28
MCAsmBackend * createX86_32AsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
const FeatureBitset & getFeatureBits() const
getFeatureBits - Return the feature bits.
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:29
Reg
All possible values of the reg field in the ModR/M byte.
MCAsmBackend * createX86_64AsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
A four-byte section relative fixup.
Definition: MCFixup.h:42
A four-byte fixup.
Definition: MCFixup.h:26
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:233
LLVM_ATTRIBUTE_ALWAYS_INLINE StringSwitch & Case(const char(&S)[N], const T &Value)
Definition: StringSwitch.h:74
std::unique_ptr< MCObjectWriter > createX86ELFObjectWriter(raw_pwrite_stream &OS, bool IsELF64, uint8_t OSABI, uint16_t EMachine)
Construct an X86 ELF object writer.
A two-byte section relative fixup.
Definition: MCFixup.h:41
CompactUnwindEncodings
Compact unwind encoding values.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:159
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:562
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:257
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
unsigned const MachineRegisterInfo * MRI
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:291
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:593
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static bool is64Bit(const char *name)
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:23
int getOffset() const
Definition: MCDwarf.h:517
OpType getOperation() const
Definition: MCDwarf.h:501
bool isExpr() const
Definition: MCInst.h:61
unsigned getNumOperands() const
Definition: MCInst.h:182
uint32_t getOffset() const
Definition: MCFixup.h:95
static unsigned getFixupKindLog2Size(unsigned Kind)
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:598
static unsigned getRelaxedOpcodeArith(const MCInst &Inst)
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:390
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A one-byte fixup.
Definition: MCFixup.h:24
LLVM_ATTRIBUTE_ALWAYS_INLINE R Default(const T &Value) const
Definition: StringSwitch.h:244
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
PowerPC TLS Dynamic Call Fixup
unsigned getRegister() const
Definition: MCDwarf.h:504
bool isOSIAMCU() const
Definition: Triple.h:500
StringRef getArchName() const
getArchName - Get the architecture (first) component of the triple.
Definition: Triple.cpp:942
void setOpcode(unsigned Op)
Definition: MCInst.h:171
A two-byte pc relative fixup.
Definition: MCFixup.h:29
A four-byte pc relative fixup.
Definition: MCFixup.h:30
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:180
virtual Optional< MCFixupKind > getFixupKind(StringRef Name) const
Map a relocation name used in .reloc to a fixup kind.
EnvironmentType getEnvironment() const
getEnvironment - Get the parsed environment type of this triple.
Definition: Triple.h:303
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:514
static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode)
Target - Wrapper for Target specific information.
A one-byte section relative fixup.
Definition: MCFixup.h:40
static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode)
A eight-byte section relative fixup.
Definition: MCFixup.h:43
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:1213
MCSubtargetInfo - Generic base class for all target subtargets.
A eight-byte fixup.
Definition: MCFixup.h:27
Target independent information on a fixup kind.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:337
const unsigned Kind
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:40
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
std::unique_ptr< MCObjectWriter > createX86WinCOFFObjectWriter(raw_pwrite_stream &OS, bool Is64Bit)
Construct an X86 Win COFF object writer.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
unsigned getOpcode() const
Definition: MCInst.h:172
A two-byte fixup.
Definition: MCFixup.h:25
int getLLVMRegNum(unsigned RegNum, bool isEH) const
Map a dwarf register back to a target register.
MCFixupKind getKind() const
Definition: MCFixup.h:93
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144