LLVM  9.0.0svn
X86MCInstLower.cpp
Go to the documentation of this file.
1 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains code to lower X86 MachineInstrs to their corresponding
10 // MCInst records.
11 //
12 //===----------------------------------------------------------------------===//
13 
18 #include "Utils/X86ShuffleDecode.h"
19 #include "X86AsmPrinter.h"
20 #include "X86RegisterInfo.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/SmallString.h"
29 #include "llvm/CodeGen/StackMaps.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCCodeEmitter.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCFixup.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCInstBuilder.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCSectionELF.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCSymbolELF.h"
46 
47 using namespace llvm;
48 
49 namespace {
50 
51 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
52 class X86MCInstLower {
53  MCContext &Ctx;
54  const MachineFunction &MF;
55  const TargetMachine &TM;
56  const MCAsmInfo &MAI;
58 
59 public:
60  X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
61 
62  Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
63  const MachineOperand &MO) const;
64  void Lower(const MachineInstr *MI, MCInst &OutMI) const;
65 
67  MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
68 
69 private:
71 };
72 
73 } // end anonymous namespace
74 
75 // Emit a minimal sequence of nops spanning NumBytes bytes.
76 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
77  const MCSubtargetInfo &STI);
78 
80  const MCSubtargetInfo &STI,
81  MCCodeEmitter *CodeEmitter) {
82  if (InShadow) {
85  raw_svector_ostream VecOS(Code);
86  CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
87  CurrentShadowSize += Code.size();
88  if (CurrentShadowSize >= RequiredShadowSize)
89  InShadow = false; // The shadow is big enough. Stop counting.
90  }
91 }
92 
93 void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
94  MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
95  if (InShadow && CurrentShadowSize < RequiredShadowSize) {
96  InShadow = false;
97  EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
98  MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
99  }
100 }
101 
102 void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
103  OutStreamer->EmitInstruction(Inst, getSubtargetInfo());
104  SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
105 }
106 
107 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
108  X86AsmPrinter &asmprinter)
109  : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
110  AsmPrinter(asmprinter) {}
111 
113  return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
114 }
115 
116 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
117 /// operand to an MCSymbol.
119  const DataLayout &DL = MF.getDataLayout();
120  assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) &&
121  "Isn't a symbol reference");
122 
123  MCSymbol *Sym = nullptr;
125  StringRef Suffix;
126 
127  switch (MO.getTargetFlags()) {
128  case X86II::MO_DLLIMPORT:
129  // Handle dllimport linkage.
130  Name += "__imp_";
131  break;
132  case X86II::MO_COFFSTUB:
133  Name += ".refptr.";
134  break;
137  Suffix = "$non_lazy_ptr";
138  break;
139  }
140 
141  if (!Suffix.empty())
142  Name += DL.getPrivateGlobalPrefix();
143 
144  if (MO.isGlobal()) {
145  const GlobalValue *GV = MO.getGlobal();
146  AsmPrinter.getNameWithPrefix(Name, GV);
147  } else if (MO.isSymbol()) {
149  } else if (MO.isMBB()) {
150  assert(Suffix.empty());
151  Sym = MO.getMBB()->getSymbol();
152  }
153 
154  Name += Suffix;
155  if (!Sym)
156  Sym = Ctx.getOrCreateSymbol(Name);
157 
158  // If the target flags on the operand changes the name of the symbol, do that
159  // before we return the symbol.
160  switch (MO.getTargetFlags()) {
161  default:
162  break;
163  case X86II::MO_COFFSTUB: {
164  MachineModuleInfoCOFF &MMICOFF =
165  MF.getMMI().getObjFileInfo<MachineModuleInfoCOFF>();
166  MachineModuleInfoImpl::StubValueTy &StubSym = MMICOFF.getGVStubEntry(Sym);
167  if (!StubSym.getPointer()) {
168  assert(MO.isGlobal() && "Extern symbol not handled yet");
170  AsmPrinter.getSymbol(MO.getGlobal()), true);
171  }
172  break;
173  }
178  if (!StubSym.getPointer()) {
179  assert(MO.isGlobal() && "Extern symbol not handled yet");
182  !MO.getGlobal()->hasInternalLinkage());
183  }
184  break;
185  }
186  }
187 
188  return Sym;
189 }
190 
192  MCSymbol *Sym) const {
193  // FIXME: We would like an efficient form for this, so we don't have to do a
194  // lot of extra uniquing.
195  const MCExpr *Expr = nullptr;
197 
198  switch (MO.getTargetFlags()) {
199  default:
200  llvm_unreachable("Unknown target flag on GV operand");
201  case X86II::MO_NO_FLAG: // No flag.
202  // These affect the name of the symbol, not any suffix.
204  case X86II::MO_DLLIMPORT:
205  case X86II::MO_COFFSTUB:
206  break;
207 
208  case X86II::MO_TLVP:
209  RefKind = MCSymbolRefExpr::VK_TLVP;
210  break;
213  // Subtract the pic base.
215  Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
216  break;
217  case X86II::MO_SECREL:
218  RefKind = MCSymbolRefExpr::VK_SECREL;
219  break;
220  case X86II::MO_TLSGD:
221  RefKind = MCSymbolRefExpr::VK_TLSGD;
222  break;
223  case X86II::MO_TLSLD:
224  RefKind = MCSymbolRefExpr::VK_TLSLD;
225  break;
226  case X86II::MO_TLSLDM:
227  RefKind = MCSymbolRefExpr::VK_TLSLDM;
228  break;
229  case X86II::MO_GOTTPOFF:
231  break;
232  case X86II::MO_INDNTPOFF:
234  break;
235  case X86II::MO_TPOFF:
236  RefKind = MCSymbolRefExpr::VK_TPOFF;
237  break;
238  case X86II::MO_DTPOFF:
239  RefKind = MCSymbolRefExpr::VK_DTPOFF;
240  break;
241  case X86II::MO_NTPOFF:
242  RefKind = MCSymbolRefExpr::VK_NTPOFF;
243  break;
244  case X86II::MO_GOTNTPOFF:
246  break;
247  case X86II::MO_GOTPCREL:
249  break;
250  case X86II::MO_GOT:
251  RefKind = MCSymbolRefExpr::VK_GOT;
252  break;
253  case X86II::MO_GOTOFF:
254  RefKind = MCSymbolRefExpr::VK_GOTOFF;
255  break;
256  case X86II::MO_PLT:
257  RefKind = MCSymbolRefExpr::VK_PLT;
258  break;
259  case X86II::MO_ABS8:
261  break;
264  Expr = MCSymbolRefExpr::create(Sym, Ctx);
265  // Subtract the pic base.
267  Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
268  if (MO.isJTI()) {
269  assert(MAI.doesSetDirectiveSuppressReloc());
270  // If .set directive is supported, use it to reduce the number of
271  // relocations the assembler will generate for differences between
272  // local labels. This is only safe when the symbols are in the same
273  // section so we are restricting it to jumptable references.
274  MCSymbol *Label = Ctx.createTempSymbol();
275  AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
276  Expr = MCSymbolRefExpr::create(Label, Ctx);
277  }
278  break;
279  }
280 
281  if (!Expr)
282  Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
283 
284  if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
286  Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
287  return MCOperand::createExpr(Expr);
288 }
289 
290 /// Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
291 /// a short fixed-register form.
292 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
293  unsigned ImmOp = Inst.getNumOperands() - 1;
294  assert(Inst.getOperand(0).isReg() &&
295  (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
296  ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
297  Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
298  Inst.getNumOperands() == 2) &&
299  "Unexpected instruction!");
300 
301  // Check whether the destination register can be fixed.
302  unsigned Reg = Inst.getOperand(0).getReg();
303  if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
304  return;
305 
306  // If so, rewrite the instruction.
307  MCOperand Saved = Inst.getOperand(ImmOp);
308  Inst = MCInst();
309  Inst.setOpcode(Opcode);
310  Inst.addOperand(Saved);
311 }
312 
313 /// If a movsx instruction has a shorter encoding for the used register
314 /// simplify the instruction to use it instead.
315 static void SimplifyMOVSX(MCInst &Inst) {
316  unsigned NewOpcode = 0;
317  unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
318  switch (Inst.getOpcode()) {
319  default:
320  llvm_unreachable("Unexpected instruction!");
321  case X86::MOVSX16rr8: // movsbw %al, %ax --> cbtw
322  if (Op0 == X86::AX && Op1 == X86::AL)
323  NewOpcode = X86::CBW;
324  break;
325  case X86::MOVSX32rr16: // movswl %ax, %eax --> cwtl
326  if (Op0 == X86::EAX && Op1 == X86::AX)
327  NewOpcode = X86::CWDE;
328  break;
329  case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
330  if (Op0 == X86::RAX && Op1 == X86::EAX)
331  NewOpcode = X86::CDQE;
332  break;
333  }
334 
335  if (NewOpcode != 0) {
336  Inst = MCInst();
337  Inst.setOpcode(NewOpcode);
338  }
339 }
340 
341 /// Simplify things like MOV32rm to MOV32o32a.
343  unsigned Opcode) {
344  // Don't make these simplifications in 64-bit mode; other assemblers don't
345  // perform them because they make the code larger.
346  if (Printer.getSubtarget().is64Bit())
347  return;
348 
349  bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
350  unsigned AddrBase = IsStore;
351  unsigned RegOp = IsStore ? 0 : 5;
352  unsigned AddrOp = AddrBase + 3;
353  assert(
354  Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
355  Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
356  Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
357  Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
358  Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
359  (Inst.getOperand(AddrOp).isExpr() || Inst.getOperand(AddrOp).isImm()) &&
360  "Unexpected instruction!");
361 
362  // Check whether the destination register can be fixed.
363  unsigned Reg = Inst.getOperand(RegOp).getReg();
364  if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
365  return;
366 
367  // Check whether this is an absolute address.
368  // FIXME: We know TLVP symbol refs aren't, but there should be a better way
369  // to do this here.
370  bool Absolute = true;
371  if (Inst.getOperand(AddrOp).isExpr()) {
372  const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
373  if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
374  if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
375  Absolute = false;
376  }
377 
378  if (Absolute &&
379  (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
380  Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
381  Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
382  return;
383 
384  // If so, rewrite the instruction.
385  MCOperand Saved = Inst.getOperand(AddrOp);
386  MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
387  Inst = MCInst();
388  Inst.setOpcode(Opcode);
389  Inst.addOperand(Saved);
390  Inst.addOperand(Seg);
391 }
392 
393 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
394  return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
395 }
396 
398 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
399  const MachineOperand &MO) const {
400  switch (MO.getType()) {
401  default:
402  MI->print(errs());
403  llvm_unreachable("unknown operand type");
405  // Ignore all implicit register operands.
406  if (MO.isImplicit())
407  return None;
408  return MCOperand::createReg(MO.getReg());
410  return MCOperand::createImm(MO.getImm());
416  return LowerSymbolOperand(MO, MO.getMCSymbol());
422  return LowerSymbolOperand(
425  // Ignore call clobbers.
426  return None;
427  }
428 }
429 
430 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
431  OutMI.setOpcode(MI->getOpcode());
432 
433  for (const MachineOperand &MO : MI->operands())
434  if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
435  OutMI.addOperand(MaybeMCOp.getValue());
436 
437  // Handle a few special cases to eliminate operand modifiers.
438 ReSimplify:
439  switch (OutMI.getOpcode()) {
440  case X86::LEA64_32r:
441  case X86::LEA64r:
442  case X86::LEA16r:
443  case X86::LEA32r:
444  // LEA should have a segment register, but it must be empty.
445  assert(OutMI.getNumOperands() == 1 + X86::AddrNumOperands &&
446  "Unexpected # of LEA operands");
447  assert(OutMI.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
448  "LEA has segment specified!");
449  break;
450 
451  // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
452  // if one of the registers is extended, but other isn't.
453  case X86::VMOVZPQILo2PQIrr:
454  case X86::VMOVAPDrr:
455  case X86::VMOVAPDYrr:
456  case X86::VMOVAPSrr:
457  case X86::VMOVAPSYrr:
458  case X86::VMOVDQArr:
459  case X86::VMOVDQAYrr:
460  case X86::VMOVDQUrr:
461  case X86::VMOVDQUYrr:
462  case X86::VMOVUPDrr:
463  case X86::VMOVUPDYrr:
464  case X86::VMOVUPSrr:
465  case X86::VMOVUPSYrr: {
466  if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
468  unsigned NewOpc;
469  switch (OutMI.getOpcode()) {
470  default: llvm_unreachable("Invalid opcode");
471  case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr; break;
472  case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
473  case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
474  case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
475  case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
476  case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
477  case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
478  case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
479  case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
480  case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
481  case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
482  case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
483  case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
484  }
485  OutMI.setOpcode(NewOpc);
486  }
487  break;
488  }
489  case X86::VMOVSDrr:
490  case X86::VMOVSSrr: {
491  if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
493  unsigned NewOpc;
494  switch (OutMI.getOpcode()) {
495  default: llvm_unreachable("Invalid opcode");
496  case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
497  case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
498  }
499  OutMI.setOpcode(NewOpc);
500  }
501  break;
502  }
503 
504  // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
505  // inputs modeled as normal uses instead of implicit uses. As such, truncate
506  // off all but the first operand (the callee). FIXME: Change isel.
507  case X86::TAILJMPr64:
508  case X86::TAILJMPr64_REX:
509  case X86::CALL64r:
510  case X86::CALL64pcrel32: {
511  unsigned Opcode = OutMI.getOpcode();
512  MCOperand Saved = OutMI.getOperand(0);
513  OutMI = MCInst();
514  OutMI.setOpcode(Opcode);
515  OutMI.addOperand(Saved);
516  break;
517  }
518 
519  case X86::EH_RETURN:
520  case X86::EH_RETURN64: {
521  OutMI = MCInst();
522  OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
523  break;
524  }
525 
526  case X86::CLEANUPRET: {
527  // Replace CLEANUPRET with the appropriate RET.
528  OutMI = MCInst();
529  OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
530  break;
531  }
532 
533  case X86::CATCHRET: {
534  // Replace CATCHRET with the appropriate RET.
535  const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
536  unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
537  OutMI = MCInst();
538  OutMI.setOpcode(getRetOpcode(Subtarget));
539  OutMI.addOperand(MCOperand::createReg(ReturnReg));
540  break;
541  }
542 
543  // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump
544  // instruction.
545  {
546  unsigned Opcode;
547  case X86::TAILJMPr:
548  Opcode = X86::JMP32r;
549  goto SetTailJmpOpcode;
550  case X86::TAILJMPd:
551  case X86::TAILJMPd64:
552  Opcode = X86::JMP_1;
553  goto SetTailJmpOpcode;
554  case X86::TAILJMPd_CC:
555  case X86::TAILJMPd64_CC:
557  static_cast<X86::CondCode>(MI->getOperand(1).getImm()));
558  goto SetTailJmpOpcode;
559 
560  SetTailJmpOpcode:
561  MCOperand Saved = OutMI.getOperand(0);
562  OutMI = MCInst();
563  OutMI.setOpcode(Opcode);
564  OutMI.addOperand(Saved);
565  break;
566  }
567 
568  case X86::DEC16r:
569  case X86::DEC32r:
570  case X86::INC16r:
571  case X86::INC32r:
572  // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
573  if (!AsmPrinter.getSubtarget().is64Bit()) {
574  unsigned Opcode;
575  switch (OutMI.getOpcode()) {
576  default: llvm_unreachable("Invalid opcode");
577  case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
578  case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
579  case X86::INC16r: Opcode = X86::INC16r_alt; break;
580  case X86::INC32r: Opcode = X86::INC32r_alt; break;
581  }
582  OutMI.setOpcode(Opcode);
583  }
584  break;
585 
586  // These are pseudo-ops for OR to help with the OR->ADD transformation. We do
587  // this with an ugly goto in case the resultant OR uses EAX and needs the
588  // short form.
589  case X86::ADD16rr_DB: OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
590  case X86::ADD32rr_DB: OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
591  case X86::ADD64rr_DB: OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
592  case X86::ADD16ri_DB: OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
593  case X86::ADD32ri_DB: OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
594  case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
595  case X86::ADD16ri8_DB: OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
596  case X86::ADD32ri8_DB: OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
597  case X86::ADD64ri8_DB: OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
598 
599  // We don't currently select the correct instruction form for instructions
600  // which have a short %eax, etc. form. Handle this by custom lowering, for
601  // now.
602  //
603  // Note, we are currently not handling the following instructions:
604  // MOV64ao8, MOV64o8a
605  // XCHG16ar, XCHG32ar, XCHG64ar
606  case X86::MOV8mr_NOREX:
607  case X86::MOV8mr:
608  case X86::MOV8rm_NOREX:
609  case X86::MOV8rm:
610  case X86::MOV16mr:
611  case X86::MOV16rm:
612  case X86::MOV32mr:
613  case X86::MOV32rm: {
614  unsigned NewOpc;
615  switch (OutMI.getOpcode()) {
616  default: llvm_unreachable("Invalid opcode");
617  case X86::MOV8mr_NOREX:
618  case X86::MOV8mr: NewOpc = X86::MOV8o32a; break;
619  case X86::MOV8rm_NOREX:
620  case X86::MOV8rm: NewOpc = X86::MOV8ao32; break;
621  case X86::MOV16mr: NewOpc = X86::MOV16o32a; break;
622  case X86::MOV16rm: NewOpc = X86::MOV16ao32; break;
623  case X86::MOV32mr: NewOpc = X86::MOV32o32a; break;
624  case X86::MOV32rm: NewOpc = X86::MOV32ao32; break;
625  }
626  SimplifyShortMoveForm(AsmPrinter, OutMI, NewOpc);
627  break;
628  }
629 
630  case X86::ADC8ri: case X86::ADC16ri: case X86::ADC32ri: case X86::ADC64ri32:
631  case X86::ADD8ri: case X86::ADD16ri: case X86::ADD32ri: case X86::ADD64ri32:
632  case X86::AND8ri: case X86::AND16ri: case X86::AND32ri: case X86::AND64ri32:
633  case X86::CMP8ri: case X86::CMP16ri: case X86::CMP32ri: case X86::CMP64ri32:
634  case X86::OR8ri: case X86::OR16ri: case X86::OR32ri: case X86::OR64ri32:
635  case X86::SBB8ri: case X86::SBB16ri: case X86::SBB32ri: case X86::SBB64ri32:
636  case X86::SUB8ri: case X86::SUB16ri: case X86::SUB32ri: case X86::SUB64ri32:
637  case X86::TEST8ri:case X86::TEST16ri:case X86::TEST32ri:case X86::TEST64ri32:
638  case X86::XOR8ri: case X86::XOR16ri: case X86::XOR32ri: case X86::XOR64ri32: {
639  unsigned NewOpc;
640  switch (OutMI.getOpcode()) {
641  default: llvm_unreachable("Invalid opcode");
642  case X86::ADC8ri: NewOpc = X86::ADC8i8; break;
643  case X86::ADC16ri: NewOpc = X86::ADC16i16; break;
644  case X86::ADC32ri: NewOpc = X86::ADC32i32; break;
645  case X86::ADC64ri32: NewOpc = X86::ADC64i32; break;
646  case X86::ADD8ri: NewOpc = X86::ADD8i8; break;
647  case X86::ADD16ri: NewOpc = X86::ADD16i16; break;
648  case X86::ADD32ri: NewOpc = X86::ADD32i32; break;
649  case X86::ADD64ri32: NewOpc = X86::ADD64i32; break;
650  case X86::AND8ri: NewOpc = X86::AND8i8; break;
651  case X86::AND16ri: NewOpc = X86::AND16i16; break;
652  case X86::AND32ri: NewOpc = X86::AND32i32; break;
653  case X86::AND64ri32: NewOpc = X86::AND64i32; break;
654  case X86::CMP8ri: NewOpc = X86::CMP8i8; break;
655  case X86::CMP16ri: NewOpc = X86::CMP16i16; break;
656  case X86::CMP32ri: NewOpc = X86::CMP32i32; break;
657  case X86::CMP64ri32: NewOpc = X86::CMP64i32; break;
658  case X86::OR8ri: NewOpc = X86::OR8i8; break;
659  case X86::OR16ri: NewOpc = X86::OR16i16; break;
660  case X86::OR32ri: NewOpc = X86::OR32i32; break;
661  case X86::OR64ri32: NewOpc = X86::OR64i32; break;
662  case X86::SBB8ri: NewOpc = X86::SBB8i8; break;
663  case X86::SBB16ri: NewOpc = X86::SBB16i16; break;
664  case X86::SBB32ri: NewOpc = X86::SBB32i32; break;
665  case X86::SBB64ri32: NewOpc = X86::SBB64i32; break;
666  case X86::SUB8ri: NewOpc = X86::SUB8i8; break;
667  case X86::SUB16ri: NewOpc = X86::SUB16i16; break;
668  case X86::SUB32ri: NewOpc = X86::SUB32i32; break;
669  case X86::SUB64ri32: NewOpc = X86::SUB64i32; break;
670  case X86::TEST8ri: NewOpc = X86::TEST8i8; break;
671  case X86::TEST16ri: NewOpc = X86::TEST16i16; break;
672  case X86::TEST32ri: NewOpc = X86::TEST32i32; break;
673  case X86::TEST64ri32: NewOpc = X86::TEST64i32; break;
674  case X86::XOR8ri: NewOpc = X86::XOR8i8; break;
675  case X86::XOR16ri: NewOpc = X86::XOR16i16; break;
676  case X86::XOR32ri: NewOpc = X86::XOR32i32; break;
677  case X86::XOR64ri32: NewOpc = X86::XOR64i32; break;
678  }
679  SimplifyShortImmForm(OutMI, NewOpc);
680  break;
681  }
682 
683  // Try to shrink some forms of movsx.
684  case X86::MOVSX16rr8:
685  case X86::MOVSX32rr16:
686  case X86::MOVSX64rr32:
687  SimplifyMOVSX(OutMI);
688  break;
689  }
690 }
691 
692 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
693  const MachineInstr &MI) {
694 
695  bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
696  MI.getOpcode() == X86::TLS_base_addr64;
697 
698  bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
699 
700  MCContext &context = OutStreamer->getContext();
701 
702  if (needsPadding)
703  EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
704 
706  switch (MI.getOpcode()) {
707  case X86::TLS_addr32:
708  case X86::TLS_addr64:
710  break;
711  case X86::TLS_base_addr32:
713  break;
714  case X86::TLS_base_addr64:
716  break;
717  default:
718  llvm_unreachable("unexpected opcode");
719  }
720 
721  MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
722  const MCSymbolRefExpr *symRef = MCSymbolRefExpr::create(sym, SRVK, context);
723 
724  MCInst LEA;
725  if (is64Bits) {
726  LEA.setOpcode(X86::LEA64r);
727  LEA.addOperand(MCOperand::createReg(X86::RDI)); // dest
728  LEA.addOperand(MCOperand::createReg(X86::RIP)); // base
729  LEA.addOperand(MCOperand::createImm(1)); // scale
730  LEA.addOperand(MCOperand::createReg(0)); // index
731  LEA.addOperand(MCOperand::createExpr(symRef)); // disp
732  LEA.addOperand(MCOperand::createReg(0)); // seg
733  } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
734  LEA.setOpcode(X86::LEA32r);
737  LEA.addOperand(MCOperand::createImm(1)); // scale
738  LEA.addOperand(MCOperand::createReg(0)); // index
739  LEA.addOperand(MCOperand::createExpr(symRef)); // disp
740  LEA.addOperand(MCOperand::createReg(0)); // seg
741  } else {
742  LEA.setOpcode(X86::LEA32r);
744  LEA.addOperand(MCOperand::createReg(0)); // base
745  LEA.addOperand(MCOperand::createImm(1)); // scale
747  LEA.addOperand(MCOperand::createExpr(symRef)); // disp
748  LEA.addOperand(MCOperand::createReg(0)); // seg
749  }
750  EmitAndCountInstruction(LEA);
751 
752  if (needsPadding) {
753  EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
754  EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
755  EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
756  }
757 
758  StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
759  MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name);
760  const MCSymbolRefExpr *tlsRef =
761  MCSymbolRefExpr::create(tlsGetAddr, MCSymbolRefExpr::VK_PLT, context);
762 
763  EmitAndCountInstruction(
764  MCInstBuilder(is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
765  .addExpr(tlsRef));
766 }
767 
768 /// Emit the largest nop instruction smaller than or equal to \p NumBytes
769 /// bytes. Return the size of nop emitted.
770 static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
771  const MCSubtargetInfo &STI) {
772  // This works only for 64bit. For 32bit we have to do additional checking if
773  // the CPU supports multi-byte nops.
774  assert(Is64Bit && "EmitNops only supports X86-64");
775 
776  unsigned NopSize;
777  unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
778  Opc = IndexReg = Displacement = SegmentReg = 0;
779  BaseReg = X86::RAX;
780  ScaleVal = 1;
781  switch (NumBytes) {
782  case 0:
783  llvm_unreachable("Zero nops?");
784  break;
785  case 1:
786  NopSize = 1;
787  Opc = X86::NOOP;
788  break;
789  case 2:
790  NopSize = 2;
791  Opc = X86::XCHG16ar;
792  break;
793  case 3:
794  NopSize = 3;
795  Opc = X86::NOOPL;
796  break;
797  case 4:
798  NopSize = 4;
799  Opc = X86::NOOPL;
800  Displacement = 8;
801  break;
802  case 5:
803  NopSize = 5;
804  Opc = X86::NOOPL;
805  Displacement = 8;
806  IndexReg = X86::RAX;
807  break;
808  case 6:
809  NopSize = 6;
810  Opc = X86::NOOPW;
811  Displacement = 8;
812  IndexReg = X86::RAX;
813  break;
814  case 7:
815  NopSize = 7;
816  Opc = X86::NOOPL;
817  Displacement = 512;
818  break;
819  case 8:
820  NopSize = 8;
821  Opc = X86::NOOPL;
822  Displacement = 512;
823  IndexReg = X86::RAX;
824  break;
825  case 9:
826  NopSize = 9;
827  Opc = X86::NOOPW;
828  Displacement = 512;
829  IndexReg = X86::RAX;
830  break;
831  default:
832  NopSize = 10;
833  Opc = X86::NOOPW;
834  Displacement = 512;
835  IndexReg = X86::RAX;
836  SegmentReg = X86::CS;
837  break;
838  }
839 
840  unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
841  NopSize += NumPrefixes;
842  for (unsigned i = 0; i != NumPrefixes; ++i)
843  OS.EmitBytes("\x66");
844 
845  switch (Opc) {
846  default: llvm_unreachable("Unexpected opcode");
847  case X86::NOOP:
848  OS.EmitInstruction(MCInstBuilder(Opc), STI);
849  break;
850  case X86::XCHG16ar:
851  OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX).addReg(X86::AX), STI);
852  break;
853  case X86::NOOPL:
854  case X86::NOOPW:
856  .addReg(BaseReg)
857  .addImm(ScaleVal)
858  .addReg(IndexReg)
859  .addImm(Displacement)
860  .addReg(SegmentReg),
861  STI);
862  break;
863  }
864  assert(NopSize <= NumBytes && "We overemitted?");
865  return NopSize;
866 }
867 
868 /// Emit the optimal amount of multi-byte nops on X86.
869 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
870  const MCSubtargetInfo &STI) {
871  unsigned NopsToEmit = NumBytes;
872  (void)NopsToEmit;
873  while (NumBytes) {
874  NumBytes -= EmitNop(OS, NumBytes, Is64Bit, STI);
875  assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
876  }
877 }
878 
879 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
880  X86MCInstLower &MCIL) {
881  assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
882 
883  StatepointOpers SOpers(&MI);
884  if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
885  EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
886  getSubtargetInfo());
887  } else {
888  // Lower call target and choose correct opcode
889  const MachineOperand &CallTarget = SOpers.getCallTarget();
890  MCOperand CallTargetMCOp;
891  unsigned CallOpcode;
892  switch (CallTarget.getType()) {
895  CallTargetMCOp = MCIL.LowerSymbolOperand(
896  CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
897  CallOpcode = X86::CALL64pcrel32;
898  // Currently, we only support relative addressing with statepoints.
899  // Otherwise, we'll need a scratch register to hold the target
900  // address. You'll fail asserts during load & relocation if this
901  // symbol is to far away. (TODO: support non-relative addressing)
902  break;
904  CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
905  CallOpcode = X86::CALL64pcrel32;
906  // Currently, we only support relative addressing with statepoints.
907  // Otherwise, we'll need a scratch register to hold the target
908  // immediate. You'll fail asserts during load & relocation if this
909  // address is to far away. (TODO: support non-relative addressing)
910  break;
912  // FIXME: Add retpoline support and remove this.
913  if (Subtarget->useRetpolineIndirectCalls())
914  report_fatal_error("Lowering register statepoints with retpoline not "
915  "yet implemented.");
916  CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
917  CallOpcode = X86::CALL64r;
918  break;
919  default:
920  llvm_unreachable("Unsupported operand type in statepoint call target");
921  break;
922  }
923 
924  // Emit call
926  CallInst.setOpcode(CallOpcode);
927  CallInst.addOperand(CallTargetMCOp);
928  OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
929  }
930 
931  // Record our statepoint node in the same section used by STACKMAP
932  // and PATCHPOINT
933  SM.recordStatepoint(MI);
934 }
935 
936 void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
937  X86MCInstLower &MCIL) {
938  // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
939  // <opcode>, <operands>
940 
941  unsigned DefRegister = FaultingMI.getOperand(0).getReg();
943  static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
944  MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
945  unsigned Opcode = FaultingMI.getOperand(3).getImm();
946  unsigned OperandsBeginIdx = 4;
947 
948  assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
949  FM.recordFaultingOp(FK, HandlerLabel);
950 
951  MCInst MI;
952  MI.setOpcode(Opcode);
953 
954  if (DefRegister != X86::NoRegister)
955  MI.addOperand(MCOperand::createReg(DefRegister));
956 
957  for (auto I = FaultingMI.operands_begin() + OperandsBeginIdx,
958  E = FaultingMI.operands_end();
959  I != E; ++I)
960  if (auto MaybeOperand = MCIL.LowerMachineOperand(&FaultingMI, *I))
961  MI.addOperand(MaybeOperand.getValue());
962 
963  OutStreamer->EmitInstruction(MI, getSubtargetInfo());
964 }
965 
966 void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
967  X86MCInstLower &MCIL) {
968  bool Is64Bits = Subtarget->is64Bit();
969  MCContext &Ctx = OutStreamer->getContext();
970  MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
971  const MCSymbolRefExpr *Op =
973 
974  EmitAndCountInstruction(
975  MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
976  .addExpr(Op));
977 }
978 
979 void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
980  X86MCInstLower &MCIL) {
981  // PATCHABLE_OP minsize, opcode, operands
982 
983  unsigned MinSize = MI.getOperand(0).getImm();
984  unsigned Opcode = MI.getOperand(1).getImm();
985 
986  MCInst MCI;
987  MCI.setOpcode(Opcode);
988  for (auto &MO : make_range(MI.operands_begin() + 2, MI.operands_end()))
989  if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
990  MCI.addOperand(MaybeOperand.getValue());
991 
992  SmallString<256> Code;
994  raw_svector_ostream VecOS(Code);
995  CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
996 
997  if (Code.size() < MinSize) {
998  if (MinSize == 2 && Opcode == X86::PUSH64r) {
999  // This is an optimization that lets us get away without emitting a nop in
1000  // many cases.
1001  //
1002  // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %r9) takes two
1003  // bytes too, so the check on MinSize is important.
1004  MCI.setOpcode(X86::PUSH64rmr);
1005  } else {
1006  unsigned NopSize = EmitNop(*OutStreamer, MinSize, Subtarget->is64Bit(),
1007  getSubtargetInfo());
1008  assert(NopSize == MinSize && "Could not implement MinSize!");
1009  (void)NopSize;
1010  }
1011  }
1012 
1013  OutStreamer->EmitInstruction(MCI, getSubtargetInfo());
1014 }
1015 
1016 // Lower a stackmap of the form:
1017 // <id>, <shadowBytes>, ...
1018 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
1019  SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1020  SM.recordStackMap(MI);
1021  unsigned NumShadowBytes = MI.getOperand(1).getImm();
1022  SMShadowTracker.reset(NumShadowBytes);
1023 }
1024 
1025 // Lower a patchpoint of the form:
1026 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
1027 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
1028  X86MCInstLower &MCIL) {
1029  assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
1030 
1031  SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1032 
1033  SM.recordPatchPoint(MI);
1034 
1035  PatchPointOpers opers(&MI);
1036  unsigned ScratchIdx = opers.getNextScratchIdx();
1037  unsigned EncodedBytes = 0;
1038  const MachineOperand &CalleeMO = opers.getCallTarget();
1039 
1040  // Check for null target. If target is non-null (i.e. is non-zero or is
1041  // symbolic) then emit a call.
1042  if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
1043  MCOperand CalleeMCOp;
1044  switch (CalleeMO.getType()) {
1045  default:
1046  /// FIXME: Add a verifier check for bad callee types.
1047  llvm_unreachable("Unrecognized callee operand type.");
1049  if (CalleeMO.getImm())
1050  CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
1051  break;
1054  CalleeMCOp = MCIL.LowerSymbolOperand(CalleeMO,
1055  MCIL.GetSymbolFromOperand(CalleeMO));
1056  break;
1057  }
1058 
1059  // Emit MOV to materialize the target address and the CALL to target.
1060  // This is encoded with 12-13 bytes, depending on which register is used.
1061  unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
1062  if (X86II::isX86_64ExtendedReg(ScratchReg))
1063  EncodedBytes = 13;
1064  else
1065  EncodedBytes = 12;
1066 
1067  EmitAndCountInstruction(
1068  MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1069  // FIXME: Add retpoline support and remove this.
1070  if (Subtarget->useRetpolineIndirectCalls())
1072  "Lowering patchpoint with retpoline not yet implemented.");
1073  EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1074  }
1075 
1076  // Emit padding.
1077  unsigned NumBytes = opers.getNumPatchBytes();
1078  assert(NumBytes >= EncodedBytes &&
1079  "Patchpoint can't request size less than the length of a call.");
1080 
1081  EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
1082  getSubtargetInfo());
1083 }
1084 
1085 void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
1086  X86MCInstLower &MCIL) {
1087  assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
1088 
1089  // We want to emit the following pattern, which follows the x86 calling
1090  // convention to prepare for the trampoline call to be patched in.
1091  //
1092  // .p2align 1, ...
1093  // .Lxray_event_sled_N:
1094  // jmp +N // jump across the instrumentation sled
1095  // ... // set up arguments in register
1096  // callq __xray_CustomEvent@plt // force dependency to symbol
1097  // ...
1098  // <jump here>
1099  //
1100  // After patching, it would look something like:
1101  //
1102  // nopw (2-byte nop)
1103  // ...
1104  // callq __xrayCustomEvent // already lowered
1105  // ...
1106  //
1107  // ---
1108  // First we emit the label and the jump.
1109  auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
1110  OutStreamer->AddComment("# XRay Custom Event Log");
1111  OutStreamer->EmitCodeAlignment(2);
1112  OutStreamer->EmitLabel(CurSled);
1113 
1114  // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1115  // an operand (computed as an offset from the jmp instruction).
1116  // FIXME: Find another less hacky way do force the relative jump.
1117  OutStreamer->EmitBinaryData("\xeb\x0f");
1118 
1119  // The default C calling convention will place two arguments into %rcx and
1120  // %rdx -- so we only work with those.
1121  unsigned DestRegs[] = {X86::RDI, X86::RSI};
1122  bool UsedMask[] = {false, false};
1123  // Filled out in loop.
1124  unsigned SrcRegs[] = {0, 0};
1125 
1126  // Then we put the operands in the %rdi and %rsi registers. We spill the
1127  // values in the register before we clobber them, and mark them as used in
1128  // UsedMask. In case the arguments are already in the correct register, we use
1129  // emit nops appropriately sized to keep the sled the same size in every
1130  // situation.
1131  for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1132  if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1133  assert(Op->isReg() && "Only support arguments in registers");
1134  SrcRegs[I] = Op->getReg();
1135  if (SrcRegs[I] != DestRegs[I]) {
1136  UsedMask[I] = true;
1137  EmitAndCountInstruction(
1138  MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1139  } else {
1140  EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1141  }
1142  }
1143 
1144  // Now that the register values are stashed, mov arguments into place.
1145  for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1146  if (SrcRegs[I] != DestRegs[I])
1147  EmitAndCountInstruction(
1148  MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1149 
1150  // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
1151  // name of the trampoline to be implemented by the XRay runtime.
1152  auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
1154  if (isPositionIndependent())
1156 
1157  // Emit the call instruction.
1158  EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1159  .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1160 
1161  // Restore caller-saved and used registers.
1162  for (unsigned I = sizeof UsedMask; I-- > 0;)
1163  if (UsedMask[I])
1164  EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1165  else
1166  EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1167 
1168  OutStreamer->AddComment("xray custom event end.");
1169 
1170  // Record the sled version. Older versions of this sled were spelled
1171  // differently, so we let the runtime handle the different offsets we're
1172  // using.
1173  recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 1);
1174 }
1175 
1176 void X86AsmPrinter::LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr &MI,
1177  X86MCInstLower &MCIL) {
1178  assert(Subtarget->is64Bit() && "XRay typed events only supports X86-64");
1179 
1180  // We want to emit the following pattern, which follows the x86 calling
1181  // convention to prepare for the trampoline call to be patched in.
1182  //
1183  // .p2align 1, ...
1184  // .Lxray_event_sled_N:
1185  // jmp +N // jump across the instrumentation sled
1186  // ... // set up arguments in register
1187  // callq __xray_TypedEvent@plt // force dependency to symbol
1188  // ...
1189  // <jump here>
1190  //
1191  // After patching, it would look something like:
1192  //
1193  // nopw (2-byte nop)
1194  // ...
1195  // callq __xrayTypedEvent // already lowered
1196  // ...
1197  //
1198  // ---
1199  // First we emit the label and the jump.
1200  auto CurSled = OutContext.createTempSymbol("xray_typed_event_sled_", true);
1201  OutStreamer->AddComment("# XRay Typed Event Log");
1202  OutStreamer->EmitCodeAlignment(2);
1203  OutStreamer->EmitLabel(CurSled);
1204 
1205  // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1206  // an operand (computed as an offset from the jmp instruction).
1207  // FIXME: Find another less hacky way do force the relative jump.
1208  OutStreamer->EmitBinaryData("\xeb\x14");
1209 
1210  // An x86-64 convention may place three arguments into %rcx, %rdx, and R8,
1211  // so we'll work with those. Or we may be called via SystemV, in which case
1212  // we don't have to do any translation.
1213  unsigned DestRegs[] = {X86::RDI, X86::RSI, X86::RDX};
1214  bool UsedMask[] = {false, false, false};
1215 
1216  // Will fill out src regs in the loop.
1217  unsigned SrcRegs[] = {0, 0, 0};
1218 
1219  // Then we put the operands in the SystemV registers. We spill the values in
1220  // the registers before we clobber them, and mark them as used in UsedMask.
1221  // In case the arguments are already in the correct register, we emit nops
1222  // appropriately sized to keep the sled the same size in every situation.
1223  for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1224  if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1225  // TODO: Is register only support adequate?
1226  assert(Op->isReg() && "Only supports arguments in registers");
1227  SrcRegs[I] = Op->getReg();
1228  if (SrcRegs[I] != DestRegs[I]) {
1229  UsedMask[I] = true;
1230  EmitAndCountInstruction(
1231  MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1232  } else {
1233  EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1234  }
1235  }
1236 
1237  // In the above loop we only stash all of the destination registers or emit
1238  // nops if the arguments are already in the right place. Doing the actually
1239  // moving is postponed until after all the registers are stashed so nothing
1240  // is clobbers. We've already added nops to account for the size of mov and
1241  // push if the register is in the right place, so we only have to worry about
1242  // emitting movs.
1243  for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1244  if (UsedMask[I])
1245  EmitAndCountInstruction(
1246  MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1247 
1248  // We emit a hard dependency on the __xray_TypedEvent symbol, which is the
1249  // name of the trampoline to be implemented by the XRay runtime.
1250  auto TSym = OutContext.getOrCreateSymbol("__xray_TypedEvent");
1252  if (isPositionIndependent())
1254 
1255  // Emit the call instruction.
1256  EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1257  .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1258 
1259  // Restore caller-saved and used registers.
1260  for (unsigned I = sizeof UsedMask; I-- > 0;)
1261  if (UsedMask[I])
1262  EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1263  else
1264  EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1265 
1266  OutStreamer->AddComment("xray typed event end.");
1267 
1268  // Record the sled version.
1269  recordSled(CurSled, MI, SledKind::TYPED_EVENT, 0);
1270 }
1271 
1272 void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1273  X86MCInstLower &MCIL) {
1274  // We want to emit the following pattern:
1275  //
1276  // .p2align 1, ...
1277  // .Lxray_sled_N:
1278  // jmp .tmpN
1279  // # 9 bytes worth of noops
1280  //
1281  // We need the 9 bytes because at runtime, we'd be patching over the full 11
1282  // bytes with the following pattern:
1283  //
1284  // mov %r10, <function id, 32-bit> // 6 bytes
1285  // call <relative offset, 32-bits> // 5 bytes
1286  //
1287  auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1288  OutStreamer->EmitCodeAlignment(2);
1289  OutStreamer->EmitLabel(CurSled);
1290 
1291  // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1292  // an operand (computed as an offset from the jmp instruction).
1293  // FIXME: Find another less hacky way do force the relative jump.
1294  OutStreamer->EmitBytes("\xeb\x09");
1295  EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1296  recordSled(CurSled, MI, SledKind::FUNCTION_ENTER);
1297 }
1298 
1299 void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1300  X86MCInstLower &MCIL) {
1301  // Since PATCHABLE_RET takes the opcode of the return statement as an
1302  // argument, we use that to emit the correct form of the RET that we want.
1303  // i.e. when we see this:
1304  //
1305  // PATCHABLE_RET X86::RET ...
1306  //
1307  // We should emit the RET followed by sleds.
1308  //
1309  // .p2align 1, ...
1310  // .Lxray_sled_N:
1311  // ret # or equivalent instruction
1312  // # 10 bytes worth of noops
1313  //
1314  // This just makes sure that the alignment for the next instruction is 2.
1315  auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1316  OutStreamer->EmitCodeAlignment(2);
1317  OutStreamer->EmitLabel(CurSled);
1318  unsigned OpCode = MI.getOperand(0).getImm();
1319  MCInst Ret;
1320  Ret.setOpcode(OpCode);
1321  for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1322  if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1323  Ret.addOperand(MaybeOperand.getValue());
1324  OutStreamer->EmitInstruction(Ret, getSubtargetInfo());
1325  EmitNops(*OutStreamer, 10, Subtarget->is64Bit(), getSubtargetInfo());
1326  recordSled(CurSled, MI, SledKind::FUNCTION_EXIT);
1327 }
1328 
1329 void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI,
1330  X86MCInstLower &MCIL) {
1331  // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1332  // instruction so we lower that particular instruction and its operands.
1333  // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1334  // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1335  // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1336  // tail call much like how we have it in PATCHABLE_RET.
1337  auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1338  OutStreamer->EmitCodeAlignment(2);
1339  OutStreamer->EmitLabel(CurSled);
1341 
1342  // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1343  // an operand (computed as an offset from the jmp instruction).
1344  // FIXME: Find another less hacky way do force the relative jump.
1345  OutStreamer->EmitBytes("\xeb\x09");
1346  EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1347  OutStreamer->EmitLabel(Target);
1348  recordSled(CurSled, MI, SledKind::TAIL_CALL);
1349 
1350  unsigned OpCode = MI.getOperand(0).getImm();
1351  MCInst TC;
1352  TC.setOpcode(OpCode);
1353 
1354  // Before emitting the instruction, add a comment to indicate that this is
1355  // indeed a tail call.
1356  OutStreamer->AddComment("TAILCALL");
1357  for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1358  if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1359  TC.addOperand(MaybeOperand.getValue());
1360  OutStreamer->EmitInstruction(TC, getSubtargetInfo());
1361 }
1362 
1363 // Returns instruction preceding MBBI in MachineFunction.
1364 // If MBBI is the first instruction of the first basic block, returns null.
1367  const MachineBasicBlock *MBB = MBBI->getParent();
1368  while (MBBI == MBB->begin()) {
1369  if (MBB == &MBB->getParent()->front())
1371  MBB = MBB->getPrevNode();
1372  MBBI = MBB->end();
1373  }
1374  return --MBBI;
1375 }
1376 
1378  const MachineOperand &Op) {
1379  if (!Op.isCPI() || Op.getOffset() != 0)
1380  return nullptr;
1381 
1384  const MachineConstantPoolEntry &ConstantEntry = Constants[Op.getIndex()];
1385 
1386  // Bail if this is a machine constant pool entry, we won't be able to dig out
1387  // anything useful.
1388  if (ConstantEntry.isMachineConstantPoolEntry())
1389  return nullptr;
1390 
1391  const Constant *C = ConstantEntry.Val.ConstVal;
1392  assert((!C || ConstantEntry.getType() == C->getType()) &&
1393  "Expected a constant of the same type!");
1394  return C;
1395 }
1396 
1397 static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx,
1398  unsigned SrcOp2Idx, ArrayRef<int> Mask) {
1399  std::string Comment;
1400 
1401  // Compute the name for a register. This is really goofy because we have
1402  // multiple instruction printers that could (in theory) use different
1403  // names. Fortunately most people use the ATT style (outside of Windows)
1404  // and they actually agree on register naming here. Ultimately, this is
1405  // a comment, and so its OK if it isn't perfect.
1406  auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1407  return X86ATTInstPrinter::getRegisterName(RegNum);
1408  };
1409 
1410  const MachineOperand &DstOp = MI->getOperand(0);
1411  const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
1412  const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
1413 
1414  StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1415  StringRef Src1Name =
1416  SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
1417  StringRef Src2Name =
1418  SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
1419 
1420  // One source operand, fix the mask to print all elements in one span.
1421  SmallVector<int, 8> ShuffleMask(Mask.begin(), Mask.end());
1422  if (Src1Name == Src2Name)
1423  for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1424  if (ShuffleMask[i] >= e)
1425  ShuffleMask[i] -= e;
1426 
1427  raw_string_ostream CS(Comment);
1428  CS << DstName;
1429 
1430  // Handle AVX512 MASK/MASXZ write mask comments.
1431  // MASK: zmmX {%kY}
1432  // MASKZ: zmmX {%kY} {z}
1433  if (SrcOp1Idx > 1) {
1434  assert((SrcOp1Idx == 2 || SrcOp1Idx == 3) && "Unexpected writemask");
1435 
1436  const MachineOperand &WriteMaskOp = MI->getOperand(SrcOp1Idx - 1);
1437  if (WriteMaskOp.isReg()) {
1438  CS << " {%" << GetRegisterName(WriteMaskOp.getReg()) << "}";
1439 
1440  if (SrcOp1Idx == 2) {
1441  CS << " {z}";
1442  }
1443  }
1444  }
1445 
1446  CS << " = ";
1447 
1448  for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1449  if (i != 0)
1450  CS << ",";
1451  if (ShuffleMask[i] == SM_SentinelZero) {
1452  CS << "zero";
1453  continue;
1454  }
1455 
1456  // Otherwise, it must come from src1 or src2. Print the span of elements
1457  // that comes from this src.
1458  bool isSrc1 = ShuffleMask[i] < (int)e;
1459  CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1460 
1461  bool IsFirst = true;
1462  while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1463  (ShuffleMask[i] < (int)e) == isSrc1) {
1464  if (!IsFirst)
1465  CS << ',';
1466  else
1467  IsFirst = false;
1468  if (ShuffleMask[i] == SM_SentinelUndef)
1469  CS << "u";
1470  else
1471  CS << ShuffleMask[i] % (int)e;
1472  ++i;
1473  }
1474  CS << ']';
1475  --i; // For loop increments element #.
1476  }
1477  CS.flush();
1478 
1479  return Comment;
1480 }
1481 
1482 static void printConstant(const APInt &Val, raw_ostream &CS) {
1483  if (Val.getBitWidth() <= 64) {
1484  CS << Val.getZExtValue();
1485  } else {
1486  // print multi-word constant as (w0,w1)
1487  CS << "(";
1488  for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1489  if (i > 0)
1490  CS << ",";
1491  CS << Val.getRawData()[i];
1492  }
1493  CS << ")";
1494  }
1495 }
1496 
1497 static void printConstant(const APFloat &Flt, raw_ostream &CS) {
1498  SmallString<32> Str;
1499  // Force scientific notation to distinquish from integers.
1500  Flt.toString(Str, 0, 0);
1501  CS << Str;
1502 }
1503 
1504 static void printConstant(const Constant *COp, raw_ostream &CS) {
1505  if (isa<UndefValue>(COp)) {
1506  CS << "u";
1507  } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1508  printConstant(CI->getValue(), CS);
1509  } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1510  printConstant(CF->getValueAPF(), CS);
1511  } else {
1512  CS << "?";
1513  }
1514 }
1515 
1516 void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
1517  assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1518  assert(getSubtarget().isOSWindows() && "SEH_ instruction Windows only");
1519  const X86RegisterInfo *RI =
1520  MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1521 
1522  // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
1523  if (EmitFPOData) {
1524  X86TargetStreamer *XTS =
1525  static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
1526  switch (MI->getOpcode()) {
1527  case X86::SEH_PushReg:
1528  XTS->emitFPOPushReg(MI->getOperand(0).getImm());
1529  break;
1530  case X86::SEH_StackAlloc:
1531  XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
1532  break;
1533  case X86::SEH_StackAlign:
1534  XTS->emitFPOStackAlign(MI->getOperand(0).getImm());
1535  break;
1536  case X86::SEH_SetFrame:
1537  assert(MI->getOperand(1).getImm() == 0 &&
1538  ".cv_fpo_setframe takes no offset");
1539  XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
1540  break;
1541  case X86::SEH_EndPrologue:
1542  XTS->emitFPOEndPrologue();
1543  break;
1544  case X86::SEH_SaveReg:
1545  case X86::SEH_SaveXMM:
1546  case X86::SEH_PushFrame:
1547  llvm_unreachable("SEH_ directive incompatible with FPO");
1548  break;
1549  default:
1550  llvm_unreachable("expected SEH_ instruction");
1551  }
1552  return;
1553  }
1554 
1555  // Otherwise, use the .seh_ directives for all other Windows platforms.
1556  switch (MI->getOpcode()) {
1557  case X86::SEH_PushReg:
1558  OutStreamer->EmitWinCFIPushReg(
1559  RI->getSEHRegNum(MI->getOperand(0).getImm()));
1560  break;
1561 
1562  case X86::SEH_SaveReg:
1563  OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1564  MI->getOperand(1).getImm());
1565  break;
1566 
1567  case X86::SEH_SaveXMM:
1568  OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1569  MI->getOperand(1).getImm());
1570  break;
1571 
1572  case X86::SEH_StackAlloc:
1573  OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1574  break;
1575 
1576  case X86::SEH_SetFrame:
1577  OutStreamer->EmitWinCFISetFrame(
1578  RI->getSEHRegNum(MI->getOperand(0).getImm()),
1579  MI->getOperand(1).getImm());
1580  break;
1581 
1582  case X86::SEH_PushFrame:
1583  OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1584  break;
1585 
1586  case X86::SEH_EndPrologue:
1587  OutStreamer->EmitWinCFIEndProlog();
1588  break;
1589 
1590  default:
1591  llvm_unreachable("expected SEH_ instruction");
1592  }
1593 }
1594 
1595 static unsigned getRegisterWidth(const MCOperandInfo &Info) {
1596  if (Info.RegClass == X86::VR128RegClassID ||
1597  Info.RegClass == X86::VR128XRegClassID)
1598  return 128;
1599  if (Info.RegClass == X86::VR256RegClassID ||
1600  Info.RegClass == X86::VR256XRegClassID)
1601  return 256;
1602  if (Info.RegClass == X86::VR512RegClassID)
1603  return 512;
1604  llvm_unreachable("Unknown register class!");
1605 }
1606 
1608  X86MCInstLower MCInstLowering(*MF, *this);
1609  const X86RegisterInfo *RI =
1610  MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1611 
1612  // Add a comment about EVEX-2-VEX compression for AVX-512 instrs that
1613  // are compressed from EVEX encoding to VEX encoding.
1616  OutStreamer->AddComment("EVEX TO VEX Compression ", false);
1617  }
1618 
1619  switch (MI->getOpcode()) {
1620  case TargetOpcode::DBG_VALUE:
1621  llvm_unreachable("Should be handled target independently");
1622 
1623  // Emit nothing here but a comment if we can.
1624  case X86::Int_MemBarrier:
1625  OutStreamer->emitRawComment("MEMBARRIER");
1626  return;
1627 
1628  case X86::EH_RETURN:
1629  case X86::EH_RETURN64: {
1630  // Lower these as normal, but add some comments.
1631  unsigned Reg = MI->getOperand(0).getReg();
1632  OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1634  break;
1635  }
1636  case X86::CLEANUPRET: {
1637  // Lower these as normal, but add some comments.
1638  OutStreamer->AddComment("CLEANUPRET");
1639  break;
1640  }
1641 
1642  case X86::CATCHRET: {
1643  // Lower these as normal, but add some comments.
1644  OutStreamer->AddComment("CATCHRET");
1645  break;
1646  }
1647 
1648  case X86::TAILJMPr:
1649  case X86::TAILJMPm:
1650  case X86::TAILJMPd:
1651  case X86::TAILJMPd_CC:
1652  case X86::TAILJMPr64:
1653  case X86::TAILJMPm64:
1654  case X86::TAILJMPd64:
1655  case X86::TAILJMPd64_CC:
1656  case X86::TAILJMPr64_REX:
1657  case X86::TAILJMPm64_REX:
1658  // Lower these as normal, but add some comments.
1659  OutStreamer->AddComment("TAILCALL");
1660  break;
1661 
1662  case X86::TLS_addr32:
1663  case X86::TLS_addr64:
1664  case X86::TLS_base_addr32:
1665  case X86::TLS_base_addr64:
1666  return LowerTlsAddr(MCInstLowering, *MI);
1667 
1668  case X86::MOVPC32r: {
1669  // This is a pseudo op for a two instruction sequence with a label, which
1670  // looks like:
1671  // call "L1$pb"
1672  // "L1$pb":
1673  // popl %esi
1674 
1675  // Emit the call.
1676  MCSymbol *PICBase = MF->getPICBaseSymbol();
1677  // FIXME: We would like an efficient form for this, so we don't have to do a
1678  // lot of extra uniquing.
1679  EmitAndCountInstruction(
1680  MCInstBuilder(X86::CALLpcrel32)
1681  .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
1682 
1683  const X86FrameLowering *FrameLowering =
1684  MF->getSubtarget<X86Subtarget>().getFrameLowering();
1685  bool hasFP = FrameLowering->hasFP(*MF);
1686 
1687  // TODO: This is needed only if we require precise CFA.
1688  bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
1689  !OutStreamer->getDwarfFrameInfos().back().End;
1690 
1691  int stackGrowth = -RI->getSlotSize();
1692 
1693  if (HasActiveDwarfFrame && !hasFP) {
1694  OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
1695  }
1696 
1697  // Emit the label.
1698  OutStreamer->EmitLabel(PICBase);
1699 
1700  // popl $reg
1701  EmitAndCountInstruction(
1702  MCInstBuilder(X86::POP32r).addReg(MI->getOperand(0).getReg()));
1703 
1704  if (HasActiveDwarfFrame && !hasFP) {
1705  OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
1706  }
1707  return;
1708  }
1709 
1710  case X86::ADD32ri: {
1711  // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
1713  break;
1714 
1715  // Okay, we have something like:
1716  // EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
1717 
1718  // For this, we want to print something like:
1719  // MYGLOBAL + (. - PICBASE)
1720  // However, we can't generate a ".", so just emit a new label here and refer
1721  // to it.
1722  MCSymbol *DotSym = OutContext.createTempSymbol();
1723  OutStreamer->EmitLabel(DotSym);
1724 
1725  // Now that we have emitted the label, lower the complex operand expression.
1726  MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
1727 
1728  const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1729  const MCExpr *PICBase =
1731  DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
1732 
1733  DotExpr = MCBinaryExpr::createAdd(
1734  MCSymbolRefExpr::create(OpSym, OutContext), DotExpr, OutContext);
1735 
1736  EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
1737  .addReg(MI->getOperand(0).getReg())
1738  .addReg(MI->getOperand(1).getReg())
1739  .addExpr(DotExpr));
1740  return;
1741  }
1742  case TargetOpcode::STATEPOINT:
1743  return LowerSTATEPOINT(*MI, MCInstLowering);
1744 
1745  case TargetOpcode::FAULTING_OP:
1746  return LowerFAULTING_OP(*MI, MCInstLowering);
1747 
1748  case TargetOpcode::FENTRY_CALL:
1749  return LowerFENTRY_CALL(*MI, MCInstLowering);
1750 
1751  case TargetOpcode::PATCHABLE_OP:
1752  return LowerPATCHABLE_OP(*MI, MCInstLowering);
1753 
1754  case TargetOpcode::STACKMAP:
1755  return LowerSTACKMAP(*MI);
1756 
1757  case TargetOpcode::PATCHPOINT:
1758  return LowerPATCHPOINT(*MI, MCInstLowering);
1759 
1760  case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
1761  return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
1762 
1763  case TargetOpcode::PATCHABLE_RET:
1764  return LowerPATCHABLE_RET(*MI, MCInstLowering);
1765 
1766  case TargetOpcode::PATCHABLE_TAIL_CALL:
1767  return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
1768 
1769  case TargetOpcode::PATCHABLE_EVENT_CALL:
1770  return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
1771 
1772  case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
1773  return LowerPATCHABLE_TYPED_EVENT_CALL(*MI, MCInstLowering);
1774 
1775  case X86::MORESTACK_RET:
1776  EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1777  return;
1778 
1779  case X86::MORESTACK_RET_RESTORE_R10:
1780  // Return, then restore R10.
1781  EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1782  EmitAndCountInstruction(
1783  MCInstBuilder(X86::MOV64rr).addReg(X86::R10).addReg(X86::RAX));
1784  return;
1785 
1786  case X86::SEH_PushReg:
1787  case X86::SEH_SaveReg:
1788  case X86::SEH_SaveXMM:
1789  case X86::SEH_StackAlloc:
1790  case X86::SEH_StackAlign:
1791  case X86::SEH_SetFrame:
1792  case X86::SEH_PushFrame:
1793  case X86::SEH_EndPrologue:
1794  EmitSEHInstruction(MI);
1795  return;
1796 
1797  case X86::SEH_Epilogue: {
1798  assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1800  // Check if preceded by a call and emit nop if so.
1801  for (MBBI = PrevCrossBBInst(MBBI);
1803  MBBI = PrevCrossBBInst(MBBI)) {
1804  // Conservatively assume that pseudo instructions don't emit code and keep
1805  // looking for a call. We may emit an unnecessary nop in some cases.
1806  if (!MBBI->isPseudo()) {
1807  if (MBBI->isCall())
1808  EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
1809  break;
1810  }
1811  }
1812  return;
1813  }
1814 
1815  // Lower PSHUFB and VPERMILP normally but add a comment if we can find
1816  // a constant shuffle mask. We won't be able to do this at the MC layer
1817  // because the mask isn't an immediate.
1818  case X86::PSHUFBrm:
1819  case X86::VPSHUFBrm:
1820  case X86::VPSHUFBYrm:
1821  case X86::VPSHUFBZ128rm:
1822  case X86::VPSHUFBZ128rmk:
1823  case X86::VPSHUFBZ128rmkz:
1824  case X86::VPSHUFBZ256rm:
1825  case X86::VPSHUFBZ256rmk:
1826  case X86::VPSHUFBZ256rmkz:
1827  case X86::VPSHUFBZrm:
1828  case X86::VPSHUFBZrmk:
1829  case X86::VPSHUFBZrmkz: {
1830  if (!OutStreamer->isVerboseAsm())
1831  break;
1832  unsigned SrcIdx, MaskIdx;
1833  switch (MI->getOpcode()) {
1834  default: llvm_unreachable("Invalid opcode");
1835  case X86::PSHUFBrm:
1836  case X86::VPSHUFBrm:
1837  case X86::VPSHUFBYrm:
1838  case X86::VPSHUFBZ128rm:
1839  case X86::VPSHUFBZ256rm:
1840  case X86::VPSHUFBZrm:
1841  SrcIdx = 1; MaskIdx = 5; break;
1842  case X86::VPSHUFBZ128rmkz:
1843  case X86::VPSHUFBZ256rmkz:
1844  case X86::VPSHUFBZrmkz:
1845  SrcIdx = 2; MaskIdx = 6; break;
1846  case X86::VPSHUFBZ128rmk:
1847  case X86::VPSHUFBZ256rmk:
1848  case X86::VPSHUFBZrmk:
1849  SrcIdx = 3; MaskIdx = 7; break;
1850  }
1851 
1852  assert(MI->getNumOperands() >= 6 &&
1853  "We should always have at least 6 operands!");
1854 
1855  const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1856  if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1857  unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
1859  DecodePSHUFBMask(C, Width, Mask);
1860  if (!Mask.empty())
1861  OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
1862  }
1863  break;
1864  }
1865 
1866  case X86::VPERMILPSrm:
1867  case X86::VPERMILPSYrm:
1868  case X86::VPERMILPSZ128rm:
1869  case X86::VPERMILPSZ128rmk:
1870  case X86::VPERMILPSZ128rmkz:
1871  case X86::VPERMILPSZ256rm:
1872  case X86::VPERMILPSZ256rmk:
1873  case X86::VPERMILPSZ256rmkz:
1874  case X86::VPERMILPSZrm:
1875  case X86::VPERMILPSZrmk:
1876  case X86::VPERMILPSZrmkz:
1877  case X86::VPERMILPDrm:
1878  case X86::VPERMILPDYrm:
1879  case X86::VPERMILPDZ128rm:
1880  case X86::VPERMILPDZ128rmk:
1881  case X86::VPERMILPDZ128rmkz:
1882  case X86::VPERMILPDZ256rm:
1883  case X86::VPERMILPDZ256rmk:
1884  case X86::VPERMILPDZ256rmkz:
1885  case X86::VPERMILPDZrm:
1886  case X86::VPERMILPDZrmk:
1887  case X86::VPERMILPDZrmkz: {
1888  if (!OutStreamer->isVerboseAsm())
1889  break;
1890  unsigned SrcIdx, MaskIdx;
1891  unsigned ElSize;
1892  switch (MI->getOpcode()) {
1893  default: llvm_unreachable("Invalid opcode");
1894  case X86::VPERMILPSrm:
1895  case X86::VPERMILPSYrm:
1896  case X86::VPERMILPSZ128rm:
1897  case X86::VPERMILPSZ256rm:
1898  case X86::VPERMILPSZrm:
1899  SrcIdx = 1; MaskIdx = 5; ElSize = 32; break;
1900  case X86::VPERMILPSZ128rmkz:
1901  case X86::VPERMILPSZ256rmkz:
1902  case X86::VPERMILPSZrmkz:
1903  SrcIdx = 2; MaskIdx = 6; ElSize = 32; break;
1904  case X86::VPERMILPSZ128rmk:
1905  case X86::VPERMILPSZ256rmk:
1906  case X86::VPERMILPSZrmk:
1907  SrcIdx = 3; MaskIdx = 7; ElSize = 32; break;
1908  case X86::VPERMILPDrm:
1909  case X86::VPERMILPDYrm:
1910  case X86::VPERMILPDZ128rm:
1911  case X86::VPERMILPDZ256rm:
1912  case X86::VPERMILPDZrm:
1913  SrcIdx = 1; MaskIdx = 5; ElSize = 64; break;
1914  case X86::VPERMILPDZ128rmkz:
1915  case X86::VPERMILPDZ256rmkz:
1916  case X86::VPERMILPDZrmkz:
1917  SrcIdx = 2; MaskIdx = 6; ElSize = 64; break;
1918  case X86::VPERMILPDZ128rmk:
1919  case X86::VPERMILPDZ256rmk:
1920  case X86::VPERMILPDZrmk:
1921  SrcIdx = 3; MaskIdx = 7; ElSize = 64; break;
1922  }
1923 
1924  assert(MI->getNumOperands() >= 6 &&
1925  "We should always have at least 6 operands!");
1926 
1927  const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1928  if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1929  unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
1931  DecodeVPERMILPMask(C, ElSize, Width, Mask);
1932  if (!Mask.empty())
1933  OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
1934  }
1935  break;
1936  }
1937 
1938  case X86::VPERMIL2PDrm:
1939  case X86::VPERMIL2PSrm:
1940  case X86::VPERMIL2PDYrm:
1941  case X86::VPERMIL2PSYrm: {
1942  if (!OutStreamer->isVerboseAsm())
1943  break;
1944  assert(MI->getNumOperands() >= 8 &&
1945  "We should always have at least 8 operands!");
1946 
1947  const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
1948  if (!CtrlOp.isImm())
1949  break;
1950 
1951  unsigned ElSize;
1952  switch (MI->getOpcode()) {
1953  default: llvm_unreachable("Invalid opcode");
1954  case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
1955  case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
1956  }
1957 
1958  const MachineOperand &MaskOp = MI->getOperand(6);
1959  if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1960  unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
1962  DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Width, Mask);
1963  if (!Mask.empty())
1964  OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask));
1965  }
1966  break;
1967  }
1968 
1969  case X86::VPPERMrrm: {
1970  if (!OutStreamer->isVerboseAsm())
1971  break;
1972  assert(MI->getNumOperands() >= 7 &&
1973  "We should always have at least 7 operands!");
1974 
1975  const MachineOperand &MaskOp = MI->getOperand(6);
1976  if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1977  unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
1979  DecodeVPPERMMask(C, Width, Mask);
1980  if (!Mask.empty())
1981  OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask));
1982  }
1983  break;
1984  }
1985 
1986  case X86::MMX_MOVQ64rm: {
1987  if (!OutStreamer->isVerboseAsm())
1988  break;
1989  if (MI->getNumOperands() <= 4)
1990  break;
1991  if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
1992  std::string Comment;
1993  raw_string_ostream CS(Comment);
1994  const MachineOperand &DstOp = MI->getOperand(0);
1995  CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
1996  if (auto *CF = dyn_cast<ConstantFP>(C)) {
1997  CS << "0x" << CF->getValueAPF().bitcastToAPInt().toString(16, false);
1998  OutStreamer->AddComment(CS.str());
1999  }
2000  }
2001  break;
2002  }
2003 
2004 #define MOV_CASE(Prefix, Suffix) \
2005  case X86::Prefix##MOVAPD##Suffix##rm: \
2006  case X86::Prefix##MOVAPS##Suffix##rm: \
2007  case X86::Prefix##MOVUPD##Suffix##rm: \
2008  case X86::Prefix##MOVUPS##Suffix##rm: \
2009  case X86::Prefix##MOVDQA##Suffix##rm: \
2010  case X86::Prefix##MOVDQU##Suffix##rm:
2011 
2012 #define MOV_AVX512_CASE(Suffix) \
2013  case X86::VMOVDQA64##Suffix##rm: \
2014  case X86::VMOVDQA32##Suffix##rm: \
2015  case X86::VMOVDQU64##Suffix##rm: \
2016  case X86::VMOVDQU32##Suffix##rm: \
2017  case X86::VMOVDQU16##Suffix##rm: \
2018  case X86::VMOVDQU8##Suffix##rm: \
2019  case X86::VMOVAPS##Suffix##rm: \
2020  case X86::VMOVAPD##Suffix##rm: \
2021  case X86::VMOVUPS##Suffix##rm: \
2022  case X86::VMOVUPD##Suffix##rm:
2023 
2024 #define CASE_ALL_MOV_RM() \
2025  MOV_CASE(, ) /* SSE */ \
2026  MOV_CASE(V, ) /* AVX-128 */ \
2027  MOV_CASE(V, Y) /* AVX-256 */ \
2028  MOV_AVX512_CASE(Z) \
2029  MOV_AVX512_CASE(Z256) \
2030  MOV_AVX512_CASE(Z128)
2031 
2032  // For loads from a constant pool to a vector register, print the constant
2033  // loaded.
2034  CASE_ALL_MOV_RM()
2035  case X86::VBROADCASTF128:
2036  case X86::VBROADCASTI128:
2037  case X86::VBROADCASTF32X4Z256rm:
2038  case X86::VBROADCASTF32X4rm:
2039  case X86::VBROADCASTF32X8rm:
2040  case X86::VBROADCASTF64X2Z128rm:
2041  case X86::VBROADCASTF64X2rm:
2042  case X86::VBROADCASTF64X4rm:
2043  case X86::VBROADCASTI32X4Z256rm:
2044  case X86::VBROADCASTI32X4rm:
2045  case X86::VBROADCASTI32X8rm:
2046  case X86::VBROADCASTI64X2Z128rm:
2047  case X86::VBROADCASTI64X2rm:
2048  case X86::VBROADCASTI64X4rm:
2049  if (!OutStreamer->isVerboseAsm())
2050  break;
2051  if (MI->getNumOperands() <= 4)
2052  break;
2053  if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2054  int NumLanes = 1;
2055  // Override NumLanes for the broadcast instructions.
2056  switch (MI->getOpcode()) {
2057  case X86::VBROADCASTF128: NumLanes = 2; break;
2058  case X86::VBROADCASTI128: NumLanes = 2; break;
2059  case X86::VBROADCASTF32X4Z256rm: NumLanes = 2; break;
2060  case X86::VBROADCASTF32X4rm: NumLanes = 4; break;
2061  case X86::VBROADCASTF32X8rm: NumLanes = 2; break;
2062  case X86::VBROADCASTF64X2Z128rm: NumLanes = 2; break;
2063  case X86::VBROADCASTF64X2rm: NumLanes = 4; break;
2064  case X86::VBROADCASTF64X4rm: NumLanes = 2; break;
2065  case X86::VBROADCASTI32X4Z256rm: NumLanes = 2; break;
2066  case X86::VBROADCASTI32X4rm: NumLanes = 4; break;
2067  case X86::VBROADCASTI32X8rm: NumLanes = 2; break;
2068  case X86::VBROADCASTI64X2Z128rm: NumLanes = 2; break;
2069  case X86::VBROADCASTI64X2rm: NumLanes = 4; break;
2070  case X86::VBROADCASTI64X4rm: NumLanes = 2; break;
2071  }
2072 
2073  std::string Comment;
2074  raw_string_ostream CS(Comment);
2075  const MachineOperand &DstOp = MI->getOperand(0);
2076  CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2077  if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
2078  CS << "[";
2079  for (int l = 0; l != NumLanes; ++l) {
2080  for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements;
2081  ++i) {
2082  if (i != 0 || l != 0)
2083  CS << ",";
2084  if (CDS->getElementType()->isIntegerTy())
2085  printConstant(CDS->getElementAsAPInt(i), CS);
2086  else if (CDS->getElementType()->isHalfTy() ||
2087  CDS->getElementType()->isFloatTy() ||
2088  CDS->getElementType()->isDoubleTy())
2089  printConstant(CDS->getElementAsAPFloat(i), CS);
2090  else
2091  CS << "?";
2092  }
2093  }
2094  CS << "]";
2095  OutStreamer->AddComment(CS.str());
2096  } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
2097  CS << "<";
2098  for (int l = 0; l != NumLanes; ++l) {
2099  for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands;
2100  ++i) {
2101  if (i != 0 || l != 0)
2102  CS << ",";
2103  printConstant(CV->getOperand(i), CS);
2104  }
2105  }
2106  CS << ">";
2107  OutStreamer->AddComment(CS.str());
2108  }
2109  }
2110  break;
2111  case X86::MOVDDUPrm:
2112  case X86::VMOVDDUPrm:
2113  case X86::VMOVDDUPZ128rm:
2114  case X86::VBROADCASTSSrm:
2115  case X86::VBROADCASTSSYrm:
2116  case X86::VBROADCASTSSZ128m:
2117  case X86::VBROADCASTSSZ256m:
2118  case X86::VBROADCASTSSZm:
2119  case X86::VBROADCASTSDYrm:
2120  case X86::VBROADCASTSDZ256m:
2121  case X86::VBROADCASTSDZm:
2122  case X86::VPBROADCASTBrm:
2123  case X86::VPBROADCASTBYrm:
2124  case X86::VPBROADCASTBZ128m:
2125  case X86::VPBROADCASTBZ256m:
2126  case X86::VPBROADCASTBZm:
2127  case X86::VPBROADCASTDrm:
2128  case X86::VPBROADCASTDYrm:
2129  case X86::VPBROADCASTDZ128m:
2130  case X86::VPBROADCASTDZ256m:
2131  case X86::VPBROADCASTDZm:
2132  case X86::VPBROADCASTQrm:
2133  case X86::VPBROADCASTQYrm:
2134  case X86::VPBROADCASTQZ128m:
2135  case X86::VPBROADCASTQZ256m:
2136  case X86::VPBROADCASTQZm:
2137  case X86::VPBROADCASTWrm:
2138  case X86::VPBROADCASTWYrm:
2139  case X86::VPBROADCASTWZ128m:
2140  case X86::VPBROADCASTWZ256m:
2141  case X86::VPBROADCASTWZm:
2142  if (!OutStreamer->isVerboseAsm())
2143  break;
2144  if (MI->getNumOperands() <= 4)
2145  break;
2146  if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2147  int NumElts;
2148  switch (MI->getOpcode()) {
2149  default: llvm_unreachable("Invalid opcode");
2150  case X86::MOVDDUPrm: NumElts = 2; break;
2151  case X86::VMOVDDUPrm: NumElts = 2; break;
2152  case X86::VMOVDDUPZ128rm: NumElts = 2; break;
2153  case X86::VBROADCASTSSrm: NumElts = 4; break;
2154  case X86::VBROADCASTSSYrm: NumElts = 8; break;
2155  case X86::VBROADCASTSSZ128m: NumElts = 4; break;
2156  case X86::VBROADCASTSSZ256m: NumElts = 8; break;
2157  case X86::VBROADCASTSSZm: NumElts = 16; break;
2158  case X86::VBROADCASTSDYrm: NumElts = 4; break;
2159  case X86::VBROADCASTSDZ256m: NumElts = 4; break;
2160  case X86::VBROADCASTSDZm: NumElts = 8; break;
2161  case X86::VPBROADCASTBrm: NumElts = 16; break;
2162  case X86::VPBROADCASTBYrm: NumElts = 32; break;
2163  case X86::VPBROADCASTBZ128m: NumElts = 16; break;
2164  case X86::VPBROADCASTBZ256m: NumElts = 32; break;
2165  case X86::VPBROADCASTBZm: NumElts = 64; break;
2166  case X86::VPBROADCASTDrm: NumElts = 4; break;
2167  case X86::VPBROADCASTDYrm: NumElts = 8; break;
2168  case X86::VPBROADCASTDZ128m: NumElts = 4; break;
2169  case X86::VPBROADCASTDZ256m: NumElts = 8; break;
2170  case X86::VPBROADCASTDZm: NumElts = 16; break;
2171  case X86::VPBROADCASTQrm: NumElts = 2; break;
2172  case X86::VPBROADCASTQYrm: NumElts = 4; break;
2173  case X86::VPBROADCASTQZ128m: NumElts = 2; break;
2174  case X86::VPBROADCASTQZ256m: NumElts = 4; break;
2175  case X86::VPBROADCASTQZm: NumElts = 8; break;
2176  case X86::VPBROADCASTWrm: NumElts = 8; break;
2177  case X86::VPBROADCASTWYrm: NumElts = 16; break;
2178  case X86::VPBROADCASTWZ128m: NumElts = 8; break;
2179  case X86::VPBROADCASTWZ256m: NumElts = 16; break;
2180  case X86::VPBROADCASTWZm: NumElts = 32; break;
2181  }
2182 
2183  std::string Comment;
2184  raw_string_ostream CS(Comment);
2185  const MachineOperand &DstOp = MI->getOperand(0);
2186  CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2187  CS << "[";
2188  for (int i = 0; i != NumElts; ++i) {
2189  if (i != 0)
2190  CS << ",";
2191  printConstant(C, CS);
2192  }
2193  CS << "]";
2194  OutStreamer->AddComment(CS.str());
2195  }
2196  }
2197 
2198  MCInst TmpInst;
2199  MCInstLowering.Lower(MI, TmpInst);
2200 
2201  // Stackmap shadows cannot include branch targets, so we can count the bytes
2202  // in a call towards the shadow, but must ensure that the no thread returns
2203  // in to the stackmap shadow. The only way to achieve this is if the call
2204  // is at the end of the shadow.
2205  if (MI->isCall()) {
2206  // Count then size of the call towards the shadow
2207  SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
2208  // Then flush the shadow so that we fill with nops before the call, not
2209  // after it.
2210  SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
2211  // Then emit the call
2212  OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
2213  return;
2214  }
2215 
2216  EmitAndCountInstruction(TmpInst);
2217 }
unsigned getTargetFlags() const
MO_SECREL - On a symbol operand this indicates that the immediate is the offset from beginning of sec...
Definition: X86BaseInfo.h:225
const NoneType None
Definition: None.h:23
unsigned GetCondBranchFromCond(CondCode CC)
uint64_t CallInst * C
bool is64Bit() const
Is this x86_64? (disregarding specific ABI / programming model)
Definition: X86Subtarget.h:521
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
bool isImm() const
Definition: MCInst.h:58
mop_iterator operands_end()
Definition: MachineInstr.h:453
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
unsigned getNextScratchIdx(unsigned StartIdx=0) const
Get the next scratch register operand index.
Definition: StackMaps.cpp:69
static const char * getRegisterName(unsigned RegNo)
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1562
virtual void EmitWinCFIPushReg(unsigned Register, SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:761
MO_COFFSTUB - On a symbol operand "FOO", this indicates that the reference is actually to the "...
Definition: X86BaseInfo.h:235
virtual bool emitFPOSetFrame(unsigned Reg, SMLoc L={})=0
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:632
AddrSegmentReg - The operand # of the segment in the memory operand.
Definition: X86BaseInfo.h:38
MachineBasicBlock * getMBB() const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:322
MCTargetOptions MCOptions
Machine level options.
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:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
PointerTy getPointer() const
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned char TargetFlags=0)
void setTargetFlags(unsigned F)
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:293
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
void DecodeVPPERMMask(ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a VPPERM mask from a raw array of constants such as from BUILD_VECTOR.
iterator begin() const
Definition: ArrayRef.h:136
MO_TLSLD - On a symbol operand this indicates that the immediate is the offset of the GOT entry with ...
Definition: X86BaseInfo.h:133
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
MO_TLVP_PIC_BASE - On a symbol operand this indicates that the immediate is some TLS offset from the ...
Definition: X86BaseInfo.h:219
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:88
static MachineModuleInfoMachO & getMachOMMI(AsmPrinter &AP)
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:136
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1515
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:220
virtual void EmitWinCFISaveXMM(unsigned Register, unsigned Offset, SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:828
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
unsigned getReg() const
getReg - Returns the register number.
virtual void EmitBytes(StringRef Data)
Emit the bytes in Data into the output.
Address of indexed Jump Table for switch.
This class represents a function call, abstracting a target machine&#39;s calling convention.
unsigned Reg
bool isReg() const
Definition: MCInst.h:57
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx, unsigned SrcOp2Idx, ArrayRef< int > Mask)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:509
MachineBasicBlock reference.
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
MachineInstrBundleIterator< const MachineInstr > const_iterator
MO_GOTPCREL - On a symbol operand this indicates that the immediate is offset to the GOT entry for th...
Definition: X86BaseInfo.h:107
MO_DTPOFF - On a symbol operand this indicates that the immediate is the offset of the GOT entry with...
Definition: X86BaseInfo.h:176
static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI)
Emit the optimal amount of multi-byte nops on X86.
virtual bool emitFPOPushReg(unsigned Reg, SMLoc L={})=0
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
print alias Alias Set Printer
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
unsigned getSlotSize() const
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
Definition: MCStreamer.cpp:955
union llvm::MachineConstantPoolEntry::@163 Val
The constant itself.
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
Mask of preserved registers.
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
MCContext & getContext() const
Definition: MCStreamer.h:250
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
CLEANUPRET - Represents a return from a cleanup block funclet.
Definition: ISDOpcodes.h:694
MO_DARWIN_NONLAZY_PIC_BASE - On a symbol operand "FOO", this indicates that the reference is actually...
Definition: X86BaseInfo.h:207
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:115
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
virtual bool emitFPOStackAlloc(unsigned StackAlloc, SMLoc L={})=0
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
void DecodeVPERMILPMask(unsigned NumElts, unsigned ScalarBits, ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a VPERMILPD/VPERMILPS variable mask from a raw array of constants.
virtual void encodeInstruction(const MCInst &Inst, raw_ostream &OS, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
EncodeInstruction - Encode the given Inst to bytes on the output stream OS.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
Name of external global symbol.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:165
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
const char * getSymbolName() const
#define CASE_ALL_MOV_RM()
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:64
Context object for machine code objects.
Definition: MCContext.h:62
void recordFaultingOp(FaultKind FaultTy, const MCSymbol *HandlerLabel)
Definition: FaultMaps.cpp:30
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition: MCStreamer.h:311
bool hasFP(const MachineFunction &MF) const override
hasFP - Return true if the specified function should have a dedicated frame pointer register...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:405
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:545
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition: APFloat.h:1166
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:197
MO_GOT - On a symbol operand this indicates that the immediate is the offset to the GOT entry for the...
Definition: X86BaseInfo.h:92
MO_GOTTPOFF - On a symbol operand this indicates that the immediate is the offset of the GOT entry wi...
Definition: X86BaseInfo.h:151
MO_ABS8 - On a symbol operand this indicates that the symbol is known to be an absolute symbol in ran...
Definition: X86BaseInfo.h:230
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
virtual void emitRawComment(const Twine &T, bool TabPrefix=true)
Print T and prefix it with the comment string (normally #) and optionally a tab.
Definition: MCStreamer.cpp:110
This class is a data container for one entry in a MachineConstantPool.
virtual void EmitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
const MCExpr * getExpr() const
Definition: MCInst.h:95
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:460
MO_DARWIN_NONLAZY - On a symbol operand "FOO", this indicates that the reference is actually to the "...
Definition: X86BaseInfo.h:202
void recordStatepoint(const MachineInstr &MI)
Generate a stackmap record for a statepoint instruction.
Definition: StackMaps.cpp:393
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1251
virtual bool emitFPOStackAlign(unsigned Align, SMLoc L={})=0
bool isX86_64ExtendedReg(unsigned RegNo)
isX86_64ExtendedReg - Is the MachineOperand a x86-64 extended (r8 or higher) register? e.g.
Definition: X86BaseInfo.h:769
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:55
int64_t getImm() const
Definition: MCInst.h:75
Address of a global value.
Streaming machine code generation interface.
Definition: MCStreamer.h:188
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:216
MCTargetStreamer * getTargetStreamer()
Definition: MCStreamer.h:257
MO_GOT_ABSOLUTE_ADDRESS - On a symbol operand, this represents a relocation of: SYMBOL_LABEL + [...
Definition: X86BaseInfo.h:80
PointerIntPair - This class implements a pair of a pointer and small integer.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MO_GOTNTPOFF - On a symbol operand this indicates that the immediate is the offset of the GOT entry w...
Definition: X86BaseInfo.h:192
MO_TLVP - On a symbol operand this indicates that the immediate is some TLS offset.
Definition: X86BaseInfo.h:213
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
const GlobalValue * getGlobal() const
MO_TLSLDM - On a symbol operand this indicates that the immediate is the offset of the GOT entry with...
Definition: X86BaseInfo.h:143
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:21
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:425
bool hasInternalLinkage() const
Definition: GlobalValue.h:433
Address of a basic block.
bool isExpr() const
Definition: MCInst.h:60
static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst, unsigned Opcode)
Simplify things like MOV32rm to MOV32o32a.
MO_NTPOFF - On a symbol operand this indicates that the immediate is the negative thread-pointer offs...
Definition: X86BaseInfo.h:184
MI-level patchpoint operands.
Definition: StackMaps.h:76
unsigned getNumOperands() const
Definition: MCInst.h:181
int getSEHRegNum(unsigned i) const
void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
static const Constant * getConstantFromPool(const MachineInstr &MI, const MachineOperand &Op)
const MachineBasicBlock & front() const
bool useRetpolineIndirectCalls() const
Definition: X86Subtarget.h:671
size_t size() const
Definition: SmallVector.h:52
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
StubValueTy & getGVStubEntry(MCSymbol *Sym)
void DecodeVPERMIL2PMask(unsigned NumElts, unsigned ScalarBits, unsigned M2Z, ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a VPERMIL2PD/VPERMIL2PS variable mask from a raw array of constants.
virtual void EmitWinCFISetFrame(unsigned Register, unsigned Offset, SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:772
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:498
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void recordPatchPoint(const MachineInstr &MI)
Generate a stackmap record for a patchpoint instruction.
Definition: StackMaps.cpp:372
MO_TLSGD - On a symbol operand this indicates that the immediate is the offset of the GOT entry with ...
Definition: X86BaseInfo.h:123
const std::vector< MachineConstantPoolEntry > & getConstants() const
virtual void EmitWinCFIPushFrame(bool Code, SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:843
MO_TPOFF - On a symbol operand this indicates that the immediate is the thread-pointer offset for the...
Definition: X86BaseInfo.h:168
static void printConstant(const APInt &Val, raw_ostream &CS)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void setOpcode(unsigned Op)
Definition: MCInst.h:170
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
static MCOperand LowerSymbolOperand(const MachineInstr *MI, const MachineOperand &MO, AsmPrinter &AP)
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:430
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
virtual void EmitWinCFIEndProlog(SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:857
virtual void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit=0)
Emit nops until the byte alignment ByteAlignment is reached.
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:179
AddrNumOperands - Total number of operands in a memory reference.
Definition: X86BaseInfo.h:41
virtual void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:794
iterator end() const
Definition: ArrayRef.h:137
X86 target streamer implementing x86-only assembly directives.
int64_t getImm() const
MCSymbol reference (for debug/eh info)
StubValueTy & getGVStubEntry(MCSymbol *Sym)
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
Definition: APInt.h:69
void recordStackMap(const MachineInstr &MI)
Generate a stackmap record for a stackmap instruction.
Definition: StackMaps.cpp:363
virtual bool emitFPOEndPrologue(SMLoc L={})=0
CATCHRET - Represents a return from a catch block funclet.
Definition: ISDOpcodes.h:690
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:674
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MO_GOTOFF - On a symbol operand this indicates that the immediate is the offset to the location of th...
Definition: X86BaseInfo.h:99
static unsigned getRetOpcode(const X86Subtarget &Subtarget)
unsigned getNumFrameInfos()
Definition: MCStreamer.h:269
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
MO_INDNTPOFF - On a symbol operand this indicates that the immediate is the absolute address of the G...
Definition: X86BaseInfo.h:160
virtual void EmitWinCFISaveReg(unsigned Register, unsigned Offset, SMLoc Loc=SMLoc())
Definition: MCStreamer.cpp:811
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:122
int16_t RegClass
This specifies the register class enumeration of the operand if the operand is a register.
Definition: MCInstrDesc.h:72
TargetOptions Options
Definition: TargetMachine.h:96
int64_t getOffset() const
Return the offset from the symbol in this operand.
const BlockAddress * getBlockAddress() const
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
Generic base class for all target subtargets.
MI-level Statepoint operands.
Definition: StackMaps.h:154
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given patchpoint should emit.
Definition: StackMaps.h:104
void EmitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents &#39;eh_return&#39; gcc dwarf builtin...
Definition: ISDOpcodes.h:101
MO_PLT - On a symbol operand this indicates that the immediate is offset to the PLT entry of symbol n...
Definition: X86BaseInfo.h:114
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:482
MCSymbol * getMCSymbol() const
mop_iterator operands_begin()
Definition: MachineInstr.h:452
static const char * name
ArrayRef< MCDwarfFrameInfo > getDwarfFrameInfos() const
Definition: MCStreamer.h:270
MCSymbol * getPICBaseSymbol() const
getPICBaseSymbol - Return a function-local symbol to represent the PIC base.
const MCOperandInfo * OpInfo
Definition: MCInstrDesc.h:174
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:346
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:58
MO_PIC_BASE_OFFSET - On a symbol operand this indicates that the immediate should get the value of th...
Definition: X86BaseInfo.h:85
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:111
static MachineBasicBlock::const_iterator PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI)
IRTranslator LLVM IR MI
const MachineOperand & getCallTarget() const
Returns the target of the underlying call.
Definition: StackMaps.h:109
void addOperand(const MCOperand &Op)
Definition: MCInst.h:183
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
Address of indexed Constant in Constant Pool.
static MCSymbol * GetSymbolFromOperand(const MachineOperand &MO, AsmPrinter &AP)
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition: MCInstrDesc.h:66
unsigned getOpcode() const
Definition: MCInst.h:171
virtual bool isVerboseAsm() const
Return true if this streamer supports verbose assembly and if it is enabled.
Definition: MCStreamer.h:288
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:34
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:122
static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI)
Emit the largest nop instruction smaller than or equal to NumBytes bytes.
const X86Subtarget & getSubtarget() const
static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode)
Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with a short fixed-register form...
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:163
virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment)
Definition: MCStreamer.cpp:433
static void SimplifyMOVSX(MCInst &Inst)
If a movsx instruction has a shorter encoding for the used register simplify the instruction to use i...
uint8_t getAsmPrinterFlags() const
Return the asm printer flags bitvector.
Definition: MachineInstr.h:268
MO_DLLIMPORT - On a symbol operand "FOO", this indicates that the reference is actually to the "__imp...
Definition: X86BaseInfo.h:197
bool isImplicit() const
void DecodePSHUFBMask(ArrayRef< uint64_t > RawMask, const APInt &UndefElts, SmallVectorImpl< int > &ShuffleMask)
Decode a PSHUFB mask from a raw array of constants such as from BUILD_VECTOR.
static unsigned getRegisterWidth(const MCOperandInfo &Info)