1 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains code to lower X86 MachineInstrs to their corresponding
11 // MCInst records.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86AsmPrinter.h"
16 #include "X86RegisterInfo.h"
17 #include "X86ShuffleDecodeConstantPool.h"
18 #include "InstPrinter/X86ATTInstPrinter.h"
19 #include "MCTargetDesc/X86BaseInfo.h"
20 #include "Utils/X86ShuffleDecode.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineOperand.h"
27 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
28 #include "llvm/CodeGen/StackMaps.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCCodeEmitter.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/MC/MCFixup.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCInstBuilder.h"
39 #include "llvm/MC/MCSection.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/MC/MCSymbolELF.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 
48 using namespace llvm;
49 
50 namespace {
51 
52 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
53 class X86MCInstLower {
54   MCContext &Ctx;
55   const MachineFunction &MF;
56   const TargetMachine &TM;
57   const MCAsmInfo &MAI;
58   X86AsmPrinter &AsmPrinter;
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 
66   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
67   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
68 
69 private:
70   MachineModuleInfoMachO &getMachOMMI() const;
71   Mangler *getMang() const {
72     return AsmPrinter.Mang;
73   }
74 };
75 
76 } // end anonymous namespace
77 
78 // Emit a minimal sequence of nops spanning NumBytes bytes.
79 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
80                      const MCSubtargetInfo &STI);
81 
82 void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
83                                                  const MCSubtargetInfo &STI,
84                                                  MCCodeEmitter *CodeEmitter) {
85   if (InShadow) {
86     SmallString<256> Code;
87     SmallVector<MCFixup, 4> Fixups;
88     raw_svector_ostream VecOS(Code);
89     CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
90     CurrentShadowSize += Code.size();
91     if (CurrentShadowSize >= RequiredShadowSize)
92       InShadow = false; // The shadow is big enough. Stop counting.
93   }
94 }
95 
96 void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
97     MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
98   if (InShadow && CurrentShadowSize < RequiredShadowSize) {
99     InShadow = false;
100     EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
101              MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
102   }
103 }
104 
105 void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
106   OutStreamer->EmitInstruction(Inst, getSubtargetInfo());
107   SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
108 }
109 
110 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
111                                X86AsmPrinter &asmprinter)
112     : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
113       AsmPrinter(asmprinter) {}
114 
115 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
116   return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
117 }
118 
119 
120 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
121 /// operand to an MCSymbol.
122 MCSymbol *X86MCInstLower::
123 GetSymbolFromOperand(const MachineOperand &MO) const {
124   const DataLayout &DL = MF.getDataLayout();
125   assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) && "Isn't a symbol reference");
126 
127   MCSymbol *Sym = nullptr;
128   SmallString<128> Name;
129   StringRef Suffix;
130 
131   switch (MO.getTargetFlags()) {
132   case X86II::MO_DLLIMPORT:
133     // Handle dllimport linkage.
134     Name += "__imp_";
135     break;
136   case X86II::MO_DARWIN_NONLAZY:
137   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
138     Suffix = "$non_lazy_ptr";
139     break;
140   }
141 
142   if (!Suffix.empty())
143     Name += DL.getPrivateGlobalPrefix();
144 
145   if (MO.isGlobal()) {
146     const GlobalValue *GV = MO.getGlobal();
147     AsmPrinter.getNameWithPrefix(Name, GV);
148   } else if (MO.isSymbol()) {
149     Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
150   } else if (MO.isMBB()) {
151     assert(Suffix.empty());
152     Sym = MO.getMBB()->getSymbol();
153   }
154 
155   Name += Suffix;
156   if (!Sym)
157     Sym = Ctx.getOrCreateSymbol(Name);
158 
159   // If the target flags on the operand changes the name of the symbol, do that
160   // before we return the symbol.
161   switch (MO.getTargetFlags()) {
162   default: break;
163   case X86II::MO_DARWIN_NONLAZY:
164   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
165     MachineModuleInfoImpl::StubValueTy &StubSym =
166       getMachOMMI().getGVStubEntry(Sym);
167     if (!StubSym.getPointer()) {
168       assert(MO.isGlobal() && "Extern symbol not handled yet");
169       StubSym =
170         MachineModuleInfoImpl::
171         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
172                     !MO.getGlobal()->hasInternalLinkage());
173     }
174     break;
175   }
176   }
177 
178   return Sym;
179 }
180 
181 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
182                                              MCSymbol *Sym) const {
183   // FIXME: We would like an efficient form for this, so we don't have to do a
184   // lot of extra uniquing.
185   const MCExpr *Expr = nullptr;
186   MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
187 
188   switch (MO.getTargetFlags()) {
189   default: llvm_unreachable("Unknown target flag on GV operand");
190   case X86II::MO_NO_FLAG:    // No flag.
191   // These affect the name of the symbol, not any suffix.
192   case X86II::MO_DARWIN_NONLAZY:
193   case X86II::MO_DLLIMPORT:
194     break;
195 
196   case X86II::MO_TLVP:      RefKind = MCSymbolRefExpr::VK_TLVP; break;
197   case X86II::MO_TLVP_PIC_BASE:
198     Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
199     // Subtract the pic base.
200     Expr = MCBinaryExpr::createSub(Expr,
201                                   MCSymbolRefExpr::create(MF.getPICBaseSymbol(),
202                                                            Ctx),
203                                    Ctx);
204     break;
205   case X86II::MO_SECREL:    RefKind = MCSymbolRefExpr::VK_SECREL; break;
206   case X86II::MO_TLSGD:     RefKind = MCSymbolRefExpr::VK_TLSGD; break;
207   case X86II::MO_TLSLD:     RefKind = MCSymbolRefExpr::VK_TLSLD; break;
208   case X86II::MO_TLSLDM:    RefKind = MCSymbolRefExpr::VK_TLSLDM; break;
209   case X86II::MO_GOTTPOFF:  RefKind = MCSymbolRefExpr::VK_GOTTPOFF; break;
210   case X86II::MO_INDNTPOFF: RefKind = MCSymbolRefExpr::VK_INDNTPOFF; break;
211   case X86II::MO_TPOFF:     RefKind = MCSymbolRefExpr::VK_TPOFF; break;
212   case X86II::MO_DTPOFF:    RefKind = MCSymbolRefExpr::VK_DTPOFF; break;
213   case X86II::MO_NTPOFF:    RefKind = MCSymbolRefExpr::VK_NTPOFF; break;
214   case X86II::MO_GOTNTPOFF: RefKind = MCSymbolRefExpr::VK_GOTNTPOFF; break;
215   case X86II::MO_GOTPCREL:  RefKind = MCSymbolRefExpr::VK_GOTPCREL; break;
216   case X86II::MO_GOT:       RefKind = MCSymbolRefExpr::VK_GOT; break;
217   case X86II::MO_GOTOFF:    RefKind = MCSymbolRefExpr::VK_GOTOFF; break;
218   case X86II::MO_PLT:       RefKind = MCSymbolRefExpr::VK_PLT; break;
219   case X86II::MO_PIC_BASE_OFFSET:
220   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
221     Expr = MCSymbolRefExpr::create(Sym, Ctx);
222     // Subtract the pic base.
223     Expr = MCBinaryExpr::createSub(Expr,
224                             MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx),
225                                    Ctx);
226     if (MO.isJTI()) {
227       assert(MAI.doesSetDirectiveSuppressReloc());
228       // If .set directive is supported, use it to reduce the number of
229       // relocations the assembler will generate for differences between
230       // local labels. This is only safe when the symbols are in the same
231       // section so we are restricting it to jumptable references.
232       MCSymbol *Label = Ctx.createTempSymbol();
233       AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
234       Expr = MCSymbolRefExpr::create(Label, Ctx);
235     }
236     break;
237   }
238 
239   if (!Expr)
240     Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
241 
242   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
243     Expr = MCBinaryExpr::createAdd(Expr,
244                                    MCConstantExpr::create(MO.getOffset(), Ctx),
245                                    Ctx);
246   return MCOperand::createExpr(Expr);
247 }
248 
249 
250 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
251 /// a short fixed-register form.
252 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
253   unsigned ImmOp = Inst.getNumOperands() - 1;
254   assert(Inst.getOperand(0).isReg() &&
255          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
256          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
257            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
258           Inst.getNumOperands() == 2) && "Unexpected instruction!");
259 
260   // Check whether the destination register can be fixed.
261   unsigned Reg = Inst.getOperand(0).getReg();
262   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
263     return;
264 
265   // If so, rewrite the instruction.
266   MCOperand Saved = Inst.getOperand(ImmOp);
267   Inst = MCInst();
268   Inst.setOpcode(Opcode);
269   Inst.addOperand(Saved);
270 }
271 
272 /// \brief If a movsx instruction has a shorter encoding for the used register
273 /// simplify the instruction to use it instead.
274 static void SimplifyMOVSX(MCInst &Inst) {
275   unsigned NewOpcode = 0;
276   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
277   switch (Inst.getOpcode()) {
278   default:
279     llvm_unreachable("Unexpected instruction!");
280   case X86::MOVSX16rr8:  // movsbw %al, %ax   --> cbtw
281     if (Op0 == X86::AX && Op1 == X86::AL)
282       NewOpcode = X86::CBW;
283     break;
284   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
285     if (Op0 == X86::EAX && Op1 == X86::AX)
286       NewOpcode = X86::CWDE;
287     break;
288   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
289     if (Op0 == X86::RAX && Op1 == X86::EAX)
290       NewOpcode = X86::CDQE;
291     break;
292   }
293 
294   if (NewOpcode != 0) {
295     Inst = MCInst();
296     Inst.setOpcode(NewOpcode);
297   }
298 }
299 
300 /// \brief Simplify things like MOV32rm to MOV32o32a.
301 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
302                                   unsigned Opcode) {
303   // Don't make these simplifications in 64-bit mode; other assemblers don't
304   // perform them because they make the code larger.
305   if (Printer.getSubtarget().is64Bit())
306     return;
307 
308   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
309   unsigned AddrBase = IsStore;
310   unsigned RegOp = IsStore ? 0 : 5;
311   unsigned AddrOp = AddrBase + 3;
312   assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
313          Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
314          Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
315          Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
316          Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
317          (Inst.getOperand(AddrOp).isExpr() ||
318           Inst.getOperand(AddrOp).isImm()) &&
319          "Unexpected instruction!");
320 
321   // Check whether the destination register can be fixed.
322   unsigned Reg = Inst.getOperand(RegOp).getReg();
323   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
324     return;
325 
326   // Check whether this is an absolute address.
327   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
328   // to do this here.
329   bool Absolute = true;
330   if (Inst.getOperand(AddrOp).isExpr()) {
331     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
332     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
333       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
334         Absolute = false;
335   }
336 
337   if (Absolute &&
338       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
339        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
340        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
341     return;
342 
343   // If so, rewrite the instruction.
344   MCOperand Saved = Inst.getOperand(AddrOp);
345   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
346   Inst = MCInst();
347   Inst.setOpcode(Opcode);
348   Inst.addOperand(Saved);
349   Inst.addOperand(Seg);
350 }
351 
352 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
353   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
354 }
355 
356 Optional<MCOperand>
357 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
358                                     const MachineOperand &MO) const {
359   switch (MO.getType()) {
360   default:
361     MI->dump();
362     llvm_unreachable("unknown operand type");
363   case MachineOperand::MO_Register:
364     // Ignore all implicit register operands.
365     if (MO.isImplicit())
366       return None;
367     return MCOperand::createReg(MO.getReg());
368   case MachineOperand::MO_Immediate:
369     return MCOperand::createImm(MO.getImm());
370   case MachineOperand::MO_MachineBasicBlock:
371   case MachineOperand::MO_GlobalAddress:
372   case MachineOperand::MO_ExternalSymbol:
373     return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
374   case MachineOperand::MO_MCSymbol:
375     return LowerSymbolOperand(MO, MO.getMCSymbol());
376   case MachineOperand::MO_JumpTableIndex:
377     return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
378   case MachineOperand::MO_ConstantPoolIndex:
379     return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
380   case MachineOperand::MO_BlockAddress:
381     return LowerSymbolOperand(
382         MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
383   case MachineOperand::MO_RegisterMask:
384     // Ignore call clobbers.
385     return None;
386   }
387 }
388 
389 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
390   OutMI.setOpcode(MI->getOpcode());
391 
392   for (const MachineOperand &MO : MI->operands())
393     if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
394       OutMI.addOperand(MaybeMCOp.getValue());
395 
396   // Handle a few special cases to eliminate operand modifiers.
397 ReSimplify:
398   switch (OutMI.getOpcode()) {
399   case X86::LEA64_32r:
400   case X86::LEA64r:
401   case X86::LEA16r:
402   case X86::LEA32r:
403     // LEA should have a segment register, but it must be empty.
404     assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
405            "Unexpected # of LEA operands");
406     assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
407            "LEA has segment specified!");
408     break;
409 
410   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
411   // if one of the registers is extended, but other isn't.
412   case X86::VMOVZPQILo2PQIrr:
413   case X86::VMOVAPDrr:
414   case X86::VMOVAPDYrr:
415   case X86::VMOVAPSrr:
416   case X86::VMOVAPSYrr:
417   case X86::VMOVDQArr:
418   case X86::VMOVDQAYrr:
419   case X86::VMOVDQUrr:
420   case X86::VMOVDQUYrr:
421   case X86::VMOVUPDrr:
422   case X86::VMOVUPDYrr:
423   case X86::VMOVUPSrr:
424   case X86::VMOVUPSYrr: {
425     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
426         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
427       unsigned NewOpc;
428       switch (OutMI.getOpcode()) {
429       default: llvm_unreachable("Invalid opcode");
430       case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr;   break;
431       case X86::VMOVAPDrr:        NewOpc = X86::VMOVAPDrr_REV;  break;
432       case X86::VMOVAPDYrr:       NewOpc = X86::VMOVAPDYrr_REV; break;
433       case X86::VMOVAPSrr:        NewOpc = X86::VMOVAPSrr_REV;  break;
434       case X86::VMOVAPSYrr:       NewOpc = X86::VMOVAPSYrr_REV; break;
435       case X86::VMOVDQArr:        NewOpc = X86::VMOVDQArr_REV;  break;
436       case X86::VMOVDQAYrr:       NewOpc = X86::VMOVDQAYrr_REV; break;
437       case X86::VMOVDQUrr:        NewOpc = X86::VMOVDQUrr_REV;  break;
438       case X86::VMOVDQUYrr:       NewOpc = X86::VMOVDQUYrr_REV; break;
439       case X86::VMOVUPDrr:        NewOpc = X86::VMOVUPDrr_REV;  break;
440       case X86::VMOVUPDYrr:       NewOpc = X86::VMOVUPDYrr_REV; break;
441       case X86::VMOVUPSrr:        NewOpc = X86::VMOVUPSrr_REV;  break;
442       case X86::VMOVUPSYrr:       NewOpc = X86::VMOVUPSYrr_REV; break;
443       }
444       OutMI.setOpcode(NewOpc);
445     }
446     break;
447   }
448   case X86::VMOVSDrr:
449   case X86::VMOVSSrr: {
450     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
451         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
452       unsigned NewOpc;
453       switch (OutMI.getOpcode()) {
454       default: llvm_unreachable("Invalid opcode");
455       case X86::VMOVSDrr:   NewOpc = X86::VMOVSDrr_REV;   break;
456       case X86::VMOVSSrr:   NewOpc = X86::VMOVSSrr_REV;   break;
457       }
458       OutMI.setOpcode(NewOpc);
459     }
460     break;
461   }
462 
463   // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
464   // inputs modeled as normal uses instead of implicit uses.  As such, truncate
465   // off all but the first operand (the callee).  FIXME: Change isel.
466   case X86::TAILJMPr64:
467   case X86::TAILJMPr64_REX:
468   case X86::CALL64r:
469   case X86::CALL64pcrel32: {
470     unsigned Opcode = OutMI.getOpcode();
471     MCOperand Saved = OutMI.getOperand(0);
472     OutMI = MCInst();
473     OutMI.setOpcode(Opcode);
474     OutMI.addOperand(Saved);
475     break;
476   }
477 
478   case X86::EH_RETURN:
479   case X86::EH_RETURN64: {
480     OutMI = MCInst();
481     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
482     break;
483   }
484 
485   case X86::CLEANUPRET: {
486     // Replace CATCHRET with the appropriate RET.
487     OutMI = MCInst();
488     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
489     break;
490   }
491 
492   case X86::CATCHRET: {
493     // Replace CATCHRET with the appropriate RET.
494     const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
495     unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
496     OutMI = MCInst();
497     OutMI.setOpcode(getRetOpcode(Subtarget));
498     OutMI.addOperand(MCOperand::createReg(ReturnReg));
499     break;
500   }
501 
502   // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump instruction.
503   { unsigned Opcode;
504   case X86::TAILJMPr:   Opcode = X86::JMP32r; goto SetTailJmpOpcode;
505   case X86::TAILJMPd:
506   case X86::TAILJMPd64: Opcode = X86::JMP_1;  goto SetTailJmpOpcode;
507   case X86::TAILJMPd_CC:
508     Opcode = X86::GetCondBranchFromCond(
509         static_cast<X86::CondCode>(MI->getOperand(1).getImm()));
510     goto SetTailJmpOpcode;
511 
512   SetTailJmpOpcode:
513     MCOperand Saved = OutMI.getOperand(0);
514     OutMI = MCInst();
515     OutMI.setOpcode(Opcode);
516     OutMI.addOperand(Saved);
517     break;
518   }
519 
520   case X86::DEC16r:
521   case X86::DEC32r:
522   case X86::INC16r:
523   case X86::INC32r:
524     // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
525     if (!AsmPrinter.getSubtarget().is64Bit()) {
526       unsigned Opcode;
527       switch (OutMI.getOpcode()) {
528       default: llvm_unreachable("Invalid opcode");
529       case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
530       case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
531       case X86::INC16r: Opcode = X86::INC16r_alt; break;
532       case X86::INC32r: Opcode = X86::INC32r_alt; break;
533       }
534       OutMI.setOpcode(Opcode);
535     }
536     break;
537 
538   // These are pseudo-ops for OR to help with the OR->ADD transformation.  We do
539   // this with an ugly goto in case the resultant OR uses EAX and needs the
540   // short form.
541   case X86::ADD16rr_DB:   OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
542   case X86::ADD32rr_DB:   OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
543   case X86::ADD64rr_DB:   OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
544   case X86::ADD16ri_DB:   OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
545   case X86::ADD32ri_DB:   OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
546   case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
547   case X86::ADD16ri8_DB:  OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
548   case X86::ADD32ri8_DB:  OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
549   case X86::ADD64ri8_DB:  OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
550 
551   // Atomic load and store require a separate pseudo-inst because Acquire
552   // implies mayStore and Release implies mayLoad; fix these to regular MOV
553   // instructions here
554   case X86::ACQUIRE_MOV8rm:    OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
555   case X86::ACQUIRE_MOV16rm:   OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
556   case X86::ACQUIRE_MOV32rm:   OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
557   case X86::ACQUIRE_MOV64rm:   OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
558   case X86::RELEASE_MOV8mr:    OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
559   case X86::RELEASE_MOV16mr:   OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
560   case X86::RELEASE_MOV32mr:   OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
561   case X86::RELEASE_MOV64mr:   OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
562   case X86::RELEASE_MOV8mi:    OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
563   case X86::RELEASE_MOV16mi:   OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
564   case X86::RELEASE_MOV32mi:   OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
565   case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
566   case X86::RELEASE_ADD8mi:    OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
567   case X86::RELEASE_ADD8mr:    OutMI.setOpcode(X86::ADD8mr); goto ReSimplify;
568   case X86::RELEASE_ADD32mi:   OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
569   case X86::RELEASE_ADD32mr:   OutMI.setOpcode(X86::ADD32mr); goto ReSimplify;
570   case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
571   case X86::RELEASE_ADD64mr:   OutMI.setOpcode(X86::ADD64mr); goto ReSimplify;
572   case X86::RELEASE_AND8mi:    OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
573   case X86::RELEASE_AND8mr:    OutMI.setOpcode(X86::AND8mr); goto ReSimplify;
574   case X86::RELEASE_AND32mi:   OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
575   case X86::RELEASE_AND32mr:   OutMI.setOpcode(X86::AND32mr); goto ReSimplify;
576   case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
577   case X86::RELEASE_AND64mr:   OutMI.setOpcode(X86::AND64mr); goto ReSimplify;
578   case X86::RELEASE_OR8mi:     OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
579   case X86::RELEASE_OR8mr:     OutMI.setOpcode(X86::OR8mr); goto ReSimplify;
580   case X86::RELEASE_OR32mi:    OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
581   case X86::RELEASE_OR32mr:    OutMI.setOpcode(X86::OR32mr); goto ReSimplify;
582   case X86::RELEASE_OR64mi32:  OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
583   case X86::RELEASE_OR64mr:    OutMI.setOpcode(X86::OR64mr); goto ReSimplify;
584   case X86::RELEASE_XOR8mi:    OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
585   case X86::RELEASE_XOR8mr:    OutMI.setOpcode(X86::XOR8mr); goto ReSimplify;
586   case X86::RELEASE_XOR32mi:   OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
587   case X86::RELEASE_XOR32mr:   OutMI.setOpcode(X86::XOR32mr); goto ReSimplify;
588   case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
589   case X86::RELEASE_XOR64mr:   OutMI.setOpcode(X86::XOR64mr); goto ReSimplify;
590   case X86::RELEASE_INC8m:     OutMI.setOpcode(X86::INC8m); goto ReSimplify;
591   case X86::RELEASE_INC16m:    OutMI.setOpcode(X86::INC16m); goto ReSimplify;
592   case X86::RELEASE_INC32m:    OutMI.setOpcode(X86::INC32m); goto ReSimplify;
593   case X86::RELEASE_INC64m:    OutMI.setOpcode(X86::INC64m); goto ReSimplify;
594   case X86::RELEASE_DEC8m:     OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
595   case X86::RELEASE_DEC16m:    OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
596   case X86::RELEASE_DEC32m:    OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
597   case X86::RELEASE_DEC64m:    OutMI.setOpcode(X86::DEC64m); 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 
705   MCSymbolRefExpr::VariantKind SRVK;
706   switch (MI.getOpcode()) {
707     case X86::TLS_addr32:
708     case X86::TLS_addr64:
709       SRVK = MCSymbolRefExpr::VK_TLSGD;
710       break;
711     case X86::TLS_base_addr32:
712       SRVK = MCSymbolRefExpr::VK_TLSLDM;
713       break;
714     case X86::TLS_base_addr64:
715       SRVK = MCSymbolRefExpr::VK_TLSLD;
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);
735     LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
736     LEA.addOperand(MCOperand::createReg(X86::EBX)); // base
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);
743     LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
744     LEA.addOperand(MCOperand::createReg(0));        // base
745     LEA.addOperand(MCOperand::createImm(1));        // scale
746     LEA.addOperand(MCOperand::createReg(X86::EBX)); // index
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,
762                             MCSymbolRefExpr::VK_PLT,
763                             context);
764 
765   EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
766                                                  : X86::CALLpcrel32)
767                             .addExpr(tlsRef));
768 }
769 
770 /// \brief Emit the largest nop instruction smaller than or equal to \p NumBytes
771 /// bytes.  Return the size of nop emitted.
772 static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
773                         const MCSubtargetInfo &STI) {
774   // This works only for 64bit. For 32bit we have to do additional checking if
775   // the CPU supports multi-byte nops.
776   assert(Is64Bit && "EmitNops only supports X86-64");
777 
778   unsigned NopSize;
779   unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
780   Opc = IndexReg = Displacement = SegmentReg = 0;
781   BaseReg = X86::RAX;
782   ScaleVal = 1;
783   switch (NumBytes) {
784   case  0: llvm_unreachable("Zero nops?"); break;
785   case  1: NopSize = 1; Opc = X86::NOOP; break;
786   case  2: NopSize = 2; Opc = X86::XCHG16ar; break;
787   case  3: NopSize = 3; Opc = X86::NOOPL; break;
788   case  4: NopSize = 4; Opc = X86::NOOPL; Displacement = 8; break;
789   case  5: NopSize = 5; Opc = X86::NOOPL; Displacement = 8;
790            IndexReg = X86::RAX; break;
791   case  6: NopSize = 6; Opc = X86::NOOPW; Displacement = 8;
792            IndexReg = X86::RAX; break;
793   case  7: NopSize = 7; Opc = X86::NOOPL; Displacement = 512; break;
794   case  8: NopSize = 8; Opc = X86::NOOPL; Displacement = 512;
795            IndexReg = X86::RAX; break;
796   case  9: NopSize = 9; Opc = X86::NOOPW; Displacement = 512;
797            IndexReg = X86::RAX; break;
798   default: NopSize = 10; Opc = X86::NOOPW; Displacement = 512;
799            IndexReg = X86::RAX; SegmentReg = X86::CS; break;
800   }
801 
802   unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
803   NopSize += NumPrefixes;
804   for (unsigned i = 0; i != NumPrefixes; ++i)
805     OS.EmitBytes("\x66");
806 
807   switch (Opc) {
808   default:
809     llvm_unreachable("Unexpected opcode");
810     break;
811   case X86::NOOP:
812     OS.EmitInstruction(MCInstBuilder(Opc), STI);
813     break;
814   case X86::XCHG16ar:
815     OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
816     break;
817   case X86::NOOPL:
818   case X86::NOOPW:
819     OS.EmitInstruction(MCInstBuilder(Opc)
820                            .addReg(BaseReg)
821                            .addImm(ScaleVal)
822                            .addReg(IndexReg)
823                            .addImm(Displacement)
824                            .addReg(SegmentReg),
825                        STI);
826     break;
827   }
828   assert(NopSize <= NumBytes && "We overemitted?");
829   return NopSize;
830 }
831 
832 /// \brief Emit the optimal amount of multi-byte nops on X86.
833 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
834                      const MCSubtargetInfo &STI) {
835   unsigned NopsToEmit = NumBytes;
836   (void)NopsToEmit;
837   while (NumBytes) {
838     NumBytes -= EmitNop(OS, NumBytes, Is64Bit, STI);
839     assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
840   }
841 }
842 
843 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
844                                     X86MCInstLower &MCIL) {
845   assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
846 
847   StatepointOpers SOpers(&MI);
848   if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
849     EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
850              getSubtargetInfo());
851   } else {
852     // Lower call target and choose correct opcode
853     const MachineOperand &CallTarget = SOpers.getCallTarget();
854     MCOperand CallTargetMCOp;
855     unsigned CallOpcode;
856     switch (CallTarget.getType()) {
857     case MachineOperand::MO_GlobalAddress:
858     case MachineOperand::MO_ExternalSymbol:
859       CallTargetMCOp = MCIL.LowerSymbolOperand(
860           CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
861       CallOpcode = X86::CALL64pcrel32;
862       // Currently, we only support relative addressing with statepoints.
863       // Otherwise, we'll need a scratch register to hold the target
864       // address.  You'll fail asserts during load & relocation if this
865       // symbol is to far away. (TODO: support non-relative addressing)
866       break;
867     case MachineOperand::MO_Immediate:
868       CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
869       CallOpcode = X86::CALL64pcrel32;
870       // Currently, we only support relative addressing with statepoints.
871       // Otherwise, we'll need a scratch register to hold the target
872       // immediate.  You'll fail asserts during load & relocation if this
873       // address is to far away. (TODO: support non-relative addressing)
874       break;
875     case MachineOperand::MO_Register:
876       CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
877       CallOpcode = X86::CALL64r;
878       break;
879     default:
880       llvm_unreachable("Unsupported operand type in statepoint call target");
881       break;
882     }
883 
884     // Emit call
885     MCInst CallInst;
886     CallInst.setOpcode(CallOpcode);
887     CallInst.addOperand(CallTargetMCOp);
888     OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
889   }
890 
891   // Record our statepoint node in the same section used by STACKMAP
892   // and PATCHPOINT
893   SM.recordStatepoint(MI);
894 }
895 
896 void X86AsmPrinter::LowerFAULTING_LOAD_OP(const MachineInstr &MI,
897                                        X86MCInstLower &MCIL) {
898   // FAULTING_LOAD_OP <def>, <MBB handler>, <load opcode>, <load operands>
899 
900   unsigned LoadDefRegister = MI.getOperand(0).getReg();
901   MCSymbol *HandlerLabel = MI.getOperand(1).getMBB()->getSymbol();
902   unsigned LoadOpcode = MI.getOperand(2).getImm();
903   unsigned LoadOperandsBeginIdx = 3;
904 
905   FM.recordFaultingOp(FaultMaps::FaultingLoad, HandlerLabel);
906 
907   MCInst LoadMI;
908   LoadMI.setOpcode(LoadOpcode);
909 
910   if (LoadDefRegister != X86::NoRegister)
911     LoadMI.addOperand(MCOperand::createReg(LoadDefRegister));
912 
913   for (auto I = MI.operands_begin() + LoadOperandsBeginIdx,
914             E = MI.operands_end();
915        I != E; ++I)
916     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, *I))
917       LoadMI.addOperand(MaybeOperand.getValue());
918 
919   OutStreamer->EmitInstruction(LoadMI, getSubtargetInfo());
920 }
921 
922 void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
923                                       X86MCInstLower &MCIL) {
924   // PATCHABLE_OP minsize, opcode, operands
925 
926   unsigned MinSize = MI.getOperand(0).getImm();
927   unsigned Opcode = MI.getOperand(1).getImm();
928 
929   MCInst MCI;
930   MCI.setOpcode(Opcode);
931   for (auto &MO : make_range(MI.operands_begin() + 2, MI.operands_end()))
932     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
933       MCI.addOperand(MaybeOperand.getValue());
934 
935   SmallString<256> Code;
936   SmallVector<MCFixup, 4> Fixups;
937   raw_svector_ostream VecOS(Code);
938   CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
939 
940   if (Code.size() < MinSize) {
941     if (MinSize == 2 && Opcode == X86::PUSH64r) {
942       // This is an optimization that lets us get away without emitting a nop in
943       // many cases.
944       //
945       // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %R9) takes two
946       // bytes too, so the check on MinSize is important.
947       MCI.setOpcode(X86::PUSH64rmr);
948     } else {
949       unsigned NopSize = EmitNop(*OutStreamer, MinSize, Subtarget->is64Bit(),
950                                  getSubtargetInfo());
951       assert(NopSize == MinSize && "Could not implement MinSize!");
952       (void) NopSize;
953     }
954   }
955 
956   OutStreamer->EmitInstruction(MCI, getSubtargetInfo());
957 }
958 
959 // Lower a stackmap of the form:
960 // <id>, <shadowBytes>, ...
961 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
962   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
963   SM.recordStackMap(MI);
964   unsigned NumShadowBytes = MI.getOperand(1).getImm();
965   SMShadowTracker.reset(NumShadowBytes);
966 }
967 
968 // Lower a patchpoint of the form:
969 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
970 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
971                                     X86MCInstLower &MCIL) {
972   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
973 
974   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
975 
976   SM.recordPatchPoint(MI);
977 
978   PatchPointOpers opers(&MI);
979   unsigned ScratchIdx = opers.getNextScratchIdx();
980   unsigned EncodedBytes = 0;
981   const MachineOperand &CalleeMO = opers.getCallTarget();
982 
983   // Check for null target. If target is non-null (i.e. is non-zero or is
984   // symbolic) then emit a call.
985   if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
986     MCOperand CalleeMCOp;
987     switch (CalleeMO.getType()) {
988     default:
989       /// FIXME: Add a verifier check for bad callee types.
990       llvm_unreachable("Unrecognized callee operand type.");
991     case MachineOperand::MO_Immediate:
992       if (CalleeMO.getImm())
993         CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
994       break;
995     case MachineOperand::MO_ExternalSymbol:
996     case MachineOperand::MO_GlobalAddress:
997       CalleeMCOp =
998         MCIL.LowerSymbolOperand(CalleeMO,
999                                 MCIL.GetSymbolFromOperand(CalleeMO));
1000       break;
1001     }
1002 
1003     // Emit MOV to materialize the target address and the CALL to target.
1004     // This is encoded with 12-13 bytes, depending on which register is used.
1005     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
1006     if (X86II::isX86_64ExtendedReg(ScratchReg))
1007       EncodedBytes = 13;
1008     else
1009       EncodedBytes = 12;
1010 
1011     EmitAndCountInstruction(
1012         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1013     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1014   }
1015 
1016   // Emit padding.
1017   unsigned NumBytes = opers.getNumPatchBytes();
1018   assert(NumBytes >= EncodedBytes &&
1019          "Patchpoint can't request size less than the length of a call.");
1020 
1021   EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
1022            getSubtargetInfo());
1023 }
1024 
1025 void X86AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
1026                                SledKind Kind) {
1027   auto Fn = MI.getParent()->getParent()->getFunction();
1028   auto Attr = Fn->getFnAttribute("function-instrument");
1029   bool AlwaysInstrument =
1030       Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
1031   Sleds.emplace_back(
1032       XRayFunctionEntry{Sled, CurrentFnSym, Kind, AlwaysInstrument, Fn});
1033 }
1034 
1035 void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1036                                                   X86MCInstLower &MCIL) {
1037   // We want to emit the following pattern:
1038   //
1039   //   .p2align 1, ...
1040   // .Lxray_sled_N:
1041   //   jmp .tmpN
1042   //   # 9 bytes worth of noops
1043   // .tmpN
1044   //
1045   // We need the 9 bytes because at runtime, we'd be patching over the full 11
1046   // bytes with the following pattern:
1047   //
1048   //   mov %r10, <function id, 32-bit>   // 6 bytes
1049   //   call <relative offset, 32-bits>   // 5 bytes
1050   //
1051   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1052   OutStreamer->EmitCodeAlignment(2);
1053   OutStreamer->EmitLabel(CurSled);
1054   auto Target = OutContext.createTempSymbol();
1055 
1056   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1057   // an operand (computed as an offset from the jmp instruction).
1058   // FIXME: Find another less hacky way do force the relative jump.
1059   OutStreamer->EmitBytes("\xeb\x09");
1060   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1061   OutStreamer->EmitLabel(Target);
1062   recordSled(CurSled, MI, SledKind::FUNCTION_ENTER);
1063 }
1064 
1065 void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1066                                        X86MCInstLower &MCIL) {
1067   // Since PATCHABLE_RET takes the opcode of the return statement as an
1068   // argument, we use that to emit the correct form of the RET that we want.
1069   // i.e. when we see this:
1070   //
1071   //   PATCHABLE_RET X86::RET ...
1072   //
1073   // We should emit the RET followed by sleds.
1074   //
1075   //   .p2align 1, ...
1076   // .Lxray_sled_N:
1077   //   ret  # or equivalent instruction
1078   //   # 10 bytes worth of noops
1079   //
1080   // This just makes sure that the alignment for the next instruction is 2.
1081   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1082   OutStreamer->EmitCodeAlignment(2);
1083   OutStreamer->EmitLabel(CurSled);
1084   unsigned OpCode = MI.getOperand(0).getImm();
1085   MCInst Ret;
1086   Ret.setOpcode(OpCode);
1087   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1088     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1089       Ret.addOperand(MaybeOperand.getValue());
1090   OutStreamer->EmitInstruction(Ret, getSubtargetInfo());
1091   EmitNops(*OutStreamer, 10, Subtarget->is64Bit(), getSubtargetInfo());
1092   recordSled(CurSled, MI, SledKind::FUNCTION_EXIT);
1093 }
1094 
1095 void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI, X86MCInstLower &MCIL) {
1096   // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1097   // instruction so we lower that particular instruction and its operands.
1098   // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1099   // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1100   // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1101   // tail call much like how we have it in PATCHABLE_RET.
1102   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1103   OutStreamer->EmitCodeAlignment(2);
1104   OutStreamer->EmitLabel(CurSled);
1105   auto Target = OutContext.createTempSymbol();
1106 
1107   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1108   // an operand (computed as an offset from the jmp instruction).
1109   // FIXME: Find another less hacky way do force the relative jump.
1110   OutStreamer->EmitBytes("\xeb\x09");
1111   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1112   OutStreamer->EmitLabel(Target);
1113   recordSled(CurSled, MI, SledKind::TAIL_CALL);
1114 
1115   unsigned OpCode = MI.getOperand(0).getImm();
1116   MCInst TC;
1117   TC.setOpcode(OpCode);
1118 
1119   // Before emitting the instruction, add a comment to indicate that this is
1120   // indeed a tail call.
1121   OutStreamer->AddComment("TAILCALL");
1122   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1123     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1124       TC.addOperand(MaybeOperand.getValue());
1125   OutStreamer->EmitInstruction(TC, getSubtargetInfo());
1126 }
1127 
1128 void X86AsmPrinter::EmitXRayTable() {
1129   if (Sleds.empty())
1130     return;
1131   if (Subtarget->isTargetELF()) {
1132     auto PrevSection = OutStreamer->getCurrentSectionOnly();
1133     auto Fn = MF->getFunction();
1134     MCSection *Section = nullptr;
1135     if (Fn->hasComdat()) {
1136       Section = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
1137                                          ELF::SHF_ALLOC | ELF::SHF_GROUP, 0,
1138                                          Fn->getComdat()->getName());
1139     } else {
1140       Section = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
1141                                          ELF::SHF_ALLOC);
1142     }
1143 
1144     // Before we switch over, we force a reference to a label inside the
1145     // xray_instr_map section. Since EmitXRayTable() is always called just
1146     // before the function's end, we assume that this is happening after the
1147     // last return instruction.
1148     //
1149     // We then align the reference to 16 byte boundaries, which we determined
1150     // experimentally to be beneficial to avoid causing decoder stalls.
1151     MCSymbol *Tmp = OutContext.createTempSymbol("xray_synthetic_", true);
1152     OutStreamer->EmitCodeAlignment(16);
1153     OutStreamer->EmitSymbolValue(Tmp, 8, false);
1154     OutStreamer->SwitchSection(Section);
1155     OutStreamer->EmitLabel(Tmp);
1156     for (const auto &Sled : Sleds) {
1157       OutStreamer->EmitSymbolValue(Sled.Sled, 8);
1158       OutStreamer->EmitSymbolValue(CurrentFnSym, 8);
1159       auto Kind = static_cast<uint8_t>(Sled.Kind);
1160       OutStreamer->EmitBytes(
1161           StringRef(reinterpret_cast<const char *>(&Kind), 1));
1162       OutStreamer->EmitBytes(
1163           StringRef(reinterpret_cast<const char *>(&Sled.AlwaysInstrument), 1));
1164       OutStreamer->EmitZeros(14);
1165     }
1166     OutStreamer->SwitchSection(PrevSection);
1167   }
1168   Sleds.clear();
1169 }
1170 
1171 // Returns instruction preceding MBBI in MachineFunction.
1172 // If MBBI is the first instruction of the first basic block, returns null.
1173 static MachineBasicBlock::const_iterator
1174 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
1175   const MachineBasicBlock *MBB = MBBI->getParent();
1176   while (MBBI == MBB->begin()) {
1177     if (MBB == &MBB->getParent()->front())
1178       return MachineBasicBlock::const_iterator();
1179     MBB = MBB->getPrevNode();
1180     MBBI = MBB->end();
1181   }
1182   return --MBBI;
1183 }
1184 
1185 static const Constant *getConstantFromPool(const MachineInstr &MI,
1186                                            const MachineOperand &Op) {
1187   if (!Op.isCPI())
1188     return nullptr;
1189 
1190   ArrayRef<MachineConstantPoolEntry> Constants =
1191       MI.getParent()->getParent()->getConstantPool()->getConstants();
1192   const MachineConstantPoolEntry &ConstantEntry =
1193       Constants[Op.getIndex()];
1194 
1195   // Bail if this is a machine constant pool entry, we won't be able to dig out
1196   // anything useful.
1197   if (ConstantEntry.isMachineConstantPoolEntry())
1198     return nullptr;
1199 
1200   auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
1201   assert((!C || ConstantEntry.getType() == C->getType()) &&
1202          "Expected a constant of the same type!");
1203   return C;
1204 }
1205 
1206 static std::string getShuffleComment(const MachineOperand &DstOp,
1207                                      const MachineOperand &SrcOp1,
1208                                      const MachineOperand &SrcOp2,
1209                                      ArrayRef<int> Mask) {
1210   std::string Comment;
1211 
1212   // Compute the name for a register. This is really goofy because we have
1213   // multiple instruction printers that could (in theory) use different
1214   // names. Fortunately most people use the ATT style (outside of Windows)
1215   // and they actually agree on register naming here. Ultimately, this is
1216   // a comment, and so its OK if it isn't perfect.
1217   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1218     return X86ATTInstPrinter::getRegisterName(RegNum);
1219   };
1220 
1221   // TODO: Add support for specifying an AVX512 style mask register in the comment.
1222   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1223   StringRef Src1Name =
1224       SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
1225   StringRef Src2Name =
1226       SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
1227 
1228   // One source operand, fix the mask to print all elements in one span.
1229   SmallVector<int, 8> ShuffleMask(Mask.begin(), Mask.end());
1230   if (Src1Name == Src2Name)
1231     for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1232       if (ShuffleMask[i] >= e)
1233         ShuffleMask[i] -= e;
1234 
1235   raw_string_ostream CS(Comment);
1236   CS << DstName << " = ";
1237   for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1238     if (i != 0)
1239       CS << ",";
1240     if (ShuffleMask[i] == SM_SentinelZero) {
1241       CS << "zero";
1242       continue;
1243     }
1244 
1245     // Otherwise, it must come from src1 or src2.  Print the span of elements
1246     // that comes from this src.
1247     bool isSrc1 = ShuffleMask[i] < (int)e;
1248     CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1249 
1250     bool IsFirst = true;
1251     while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1252            (ShuffleMask[i] < (int)e) == isSrc1) {
1253       if (!IsFirst)
1254         CS << ',';
1255       else
1256         IsFirst = false;
1257       if (ShuffleMask[i] == SM_SentinelUndef)
1258         CS << "u";
1259       else
1260         CS << ShuffleMask[i] % (int)e;
1261       ++i;
1262     }
1263     CS << ']';
1264     --i; // For loop increments element #.
1265   }
1266   CS.flush();
1267 
1268   return Comment;
1269 }
1270 
1271 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
1272   X86MCInstLower MCInstLowering(*MF, *this);
1273   const X86RegisterInfo *RI = MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1274 
1275   switch (MI->getOpcode()) {
1276   case TargetOpcode::DBG_VALUE:
1277     llvm_unreachable("Should be handled target independently");
1278 
1279   // Emit nothing here but a comment if we can.
1280   case X86::Int_MemBarrier:
1281     OutStreamer->emitRawComment("MEMBARRIER");
1282     return;
1283 
1284 
1285   case X86::EH_RETURN:
1286   case X86::EH_RETURN64: {
1287     // Lower these as normal, but add some comments.
1288     unsigned Reg = MI->getOperand(0).getReg();
1289     OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1290                             X86ATTInstPrinter::getRegisterName(Reg));
1291     break;
1292   }
1293   case X86::CLEANUPRET: {
1294     // Lower these as normal, but add some comments.
1295     OutStreamer->AddComment("CLEANUPRET");
1296     break;
1297   }
1298 
1299   case X86::CATCHRET: {
1300     // Lower these as normal, but add some comments.
1301     OutStreamer->AddComment("CATCHRET");
1302     break;
1303   }
1304 
1305   case X86::TAILJMPr:
1306   case X86::TAILJMPm:
1307   case X86::TAILJMPd:
1308   case X86::TAILJMPd_CC:
1309   case X86::TAILJMPr64:
1310   case X86::TAILJMPm64:
1311   case X86::TAILJMPd64:
1312   case X86::TAILJMPr64_REX:
1313   case X86::TAILJMPm64_REX:
1314     // Lower these as normal, but add some comments.
1315     OutStreamer->AddComment("TAILCALL");
1316     break;
1317 
1318   case X86::TLS_addr32:
1319   case X86::TLS_addr64:
1320   case X86::TLS_base_addr32:
1321   case X86::TLS_base_addr64:
1322     return LowerTlsAddr(MCInstLowering, *MI);
1323 
1324   case X86::MOVPC32r: {
1325     // This is a pseudo op for a two instruction sequence with a label, which
1326     // looks like:
1327     //     call "L1$pb"
1328     // "L1$pb":
1329     //     popl %esi
1330 
1331     // Emit the call.
1332     MCSymbol *PICBase = MF->getPICBaseSymbol();
1333     // FIXME: We would like an efficient form for this, so we don't have to do a
1334     // lot of extra uniquing.
1335     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
1336       .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
1337 
1338     const X86FrameLowering* FrameLowering =
1339         MF->getSubtarget<X86Subtarget>().getFrameLowering();
1340     bool hasFP = FrameLowering->hasFP(*MF);
1341 
1342     // TODO: This is needed only if we require precise CFA.
1343     bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
1344                                !OutStreamer->getDwarfFrameInfos().back().End;
1345 
1346     int stackGrowth = -RI->getSlotSize();
1347 
1348     if (HasActiveDwarfFrame && !hasFP) {
1349       OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
1350     }
1351 
1352     // Emit the label.
1353     OutStreamer->EmitLabel(PICBase);
1354 
1355     // popl $reg
1356     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
1357                             .addReg(MI->getOperand(0).getReg()));
1358 
1359     if (HasActiveDwarfFrame && !hasFP) {
1360       OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
1361     }
1362     return;
1363   }
1364 
1365   case X86::ADD32ri: {
1366     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
1367     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
1368       break;
1369 
1370     // Okay, we have something like:
1371     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
1372 
1373     // For this, we want to print something like:
1374     //   MYGLOBAL + (. - PICBASE)
1375     // However, we can't generate a ".", so just emit a new label here and refer
1376     // to it.
1377     MCSymbol *DotSym = OutContext.createTempSymbol();
1378     OutStreamer->EmitLabel(DotSym);
1379 
1380     // Now that we have emitted the label, lower the complex operand expression.
1381     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
1382 
1383     const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1384     const MCExpr *PICBase =
1385       MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
1386     DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
1387 
1388     DotExpr = MCBinaryExpr::createAdd(MCSymbolRefExpr::create(OpSym,OutContext),
1389                                       DotExpr, OutContext);
1390 
1391     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
1392       .addReg(MI->getOperand(0).getReg())
1393       .addReg(MI->getOperand(1).getReg())
1394       .addExpr(DotExpr));
1395     return;
1396   }
1397   case TargetOpcode::STATEPOINT:
1398     return LowerSTATEPOINT(*MI, MCInstLowering);
1399 
1400   case TargetOpcode::FAULTING_LOAD_OP:
1401     return LowerFAULTING_LOAD_OP(*MI, MCInstLowering);
1402 
1403   case TargetOpcode::PATCHABLE_OP:
1404     return LowerPATCHABLE_OP(*MI, MCInstLowering);
1405 
1406   case TargetOpcode::STACKMAP:
1407     return LowerSTACKMAP(*MI);
1408 
1409   case TargetOpcode::PATCHPOINT:
1410     return LowerPATCHPOINT(*MI, MCInstLowering);
1411 
1412   case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
1413     return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
1414 
1415   case TargetOpcode::PATCHABLE_RET:
1416     return LowerPATCHABLE_RET(*MI, MCInstLowering);
1417 
1418   case TargetOpcode::PATCHABLE_TAIL_CALL:
1419     return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
1420 
1421   case X86::MORESTACK_RET:
1422     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1423     return;
1424 
1425   case X86::MORESTACK_RET_RESTORE_R10:
1426     // Return, then restore R10.
1427     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1428     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
1429                             .addReg(X86::R10)
1430                             .addReg(X86::RAX));
1431     return;
1432 
1433   case X86::SEH_PushReg:
1434     OutStreamer->EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
1435     return;
1436 
1437   case X86::SEH_SaveReg:
1438     OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1439                                    MI->getOperand(1).getImm());
1440     return;
1441 
1442   case X86::SEH_SaveXMM:
1443     OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1444                                    MI->getOperand(1).getImm());
1445     return;
1446 
1447   case X86::SEH_StackAlloc:
1448     OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1449     return;
1450 
1451   case X86::SEH_SetFrame:
1452     OutStreamer->EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1453                                     MI->getOperand(1).getImm());
1454     return;
1455 
1456   case X86::SEH_PushFrame:
1457     OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1458     return;
1459 
1460   case X86::SEH_EndPrologue:
1461     OutStreamer->EmitWinCFIEndProlog();
1462     return;
1463 
1464   case X86::SEH_Epilogue: {
1465     MachineBasicBlock::const_iterator MBBI(MI);
1466     // Check if preceded by a call and emit nop if so.
1467     for (MBBI = PrevCrossBBInst(MBBI);
1468          MBBI != MachineBasicBlock::const_iterator();
1469          MBBI = PrevCrossBBInst(MBBI)) {
1470       // Conservatively assume that pseudo instructions don't emit code and keep
1471       // looking for a call. We may emit an unnecessary nop in some cases.
1472       if (!MBBI->isPseudo()) {
1473         if (MBBI->isCall())
1474           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
1475         break;
1476       }
1477     }
1478     return;
1479   }
1480 
1481   // Lower PSHUFB and VPERMILP normally but add a comment if we can find
1482   // a constant shuffle mask. We won't be able to do this at the MC layer
1483   // because the mask isn't an immediate.
1484   case X86::PSHUFBrm:
1485   case X86::VPSHUFBrm:
1486   case X86::VPSHUFBYrm:
1487   case X86::VPSHUFBZ128rm:
1488   case X86::VPSHUFBZ128rmk:
1489   case X86::VPSHUFBZ128rmkz:
1490   case X86::VPSHUFBZ256rm:
1491   case X86::VPSHUFBZ256rmk:
1492   case X86::VPSHUFBZ256rmkz:
1493   case X86::VPSHUFBZrm:
1494   case X86::VPSHUFBZrmk:
1495   case X86::VPSHUFBZrmkz: {
1496     if (!OutStreamer->isVerboseAsm())
1497       break;
1498     unsigned SrcIdx, MaskIdx;
1499     switch (MI->getOpcode()) {
1500     default: llvm_unreachable("Invalid opcode");
1501     case X86::PSHUFBrm:
1502     case X86::VPSHUFBrm:
1503     case X86::VPSHUFBYrm:
1504     case X86::VPSHUFBZ128rm:
1505     case X86::VPSHUFBZ256rm:
1506     case X86::VPSHUFBZrm:
1507       SrcIdx = 1; MaskIdx = 5; break;
1508     case X86::VPSHUFBZ128rmkz:
1509     case X86::VPSHUFBZ256rmkz:
1510     case X86::VPSHUFBZrmkz:
1511       SrcIdx = 2; MaskIdx = 6; break;
1512     case X86::VPSHUFBZ128rmk:
1513     case X86::VPSHUFBZ256rmk:
1514     case X86::VPSHUFBZrmk:
1515       SrcIdx = 3; MaskIdx = 7; break;
1516     }
1517 
1518     assert(MI->getNumOperands() >= 6 &&
1519            "We should always have at least 6 operands!");
1520     const MachineOperand &DstOp = MI->getOperand(0);
1521     const MachineOperand &SrcOp = MI->getOperand(SrcIdx);
1522     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1523 
1524     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1525       SmallVector<int, 16> Mask;
1526       DecodePSHUFBMask(C, Mask);
1527       if (!Mask.empty())
1528         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, SrcOp, Mask));
1529     }
1530     break;
1531   }
1532 
1533   case X86::VPERMILPDrm:
1534   case X86::VPERMILPDYrm:
1535   case X86::VPERMILPDZ128rm:
1536   case X86::VPERMILPDZ256rm:
1537   case X86::VPERMILPDZrm: {
1538     if (!OutStreamer->isVerboseAsm())
1539       break;
1540     assert(MI->getNumOperands() > 5 &&
1541            "We should always have at least 5 operands!");
1542     const MachineOperand &DstOp = MI->getOperand(0);
1543     const MachineOperand &SrcOp = MI->getOperand(1);
1544     const MachineOperand &MaskOp = MI->getOperand(5);
1545 
1546     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1547       SmallVector<int, 8> Mask;
1548       DecodeVPERMILPMask(C, 64, Mask);
1549       if (!Mask.empty())
1550         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, SrcOp, Mask));
1551     }
1552     break;
1553   }
1554 
1555   case X86::VPERMILPSrm:
1556   case X86::VPERMILPSYrm:
1557   case X86::VPERMILPSZ128rm:
1558   case X86::VPERMILPSZ256rm:
1559   case X86::VPERMILPSZrm: {
1560     if (!OutStreamer->isVerboseAsm())
1561       break;
1562     assert(MI->getNumOperands() > 5 &&
1563            "We should always have at least 5 operands!");
1564     const MachineOperand &DstOp = MI->getOperand(0);
1565     const MachineOperand &SrcOp = MI->getOperand(1);
1566     const MachineOperand &MaskOp = MI->getOperand(5);
1567 
1568     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1569       SmallVector<int, 16> Mask;
1570       DecodeVPERMILPMask(C, 32, Mask);
1571       if (!Mask.empty())
1572         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, SrcOp, Mask));
1573     }
1574     break;
1575   }
1576 
1577   case X86::VPERMIL2PDrm:
1578   case X86::VPERMIL2PSrm:
1579   case X86::VPERMIL2PDrmY:
1580   case X86::VPERMIL2PSrmY: {
1581     if (!OutStreamer->isVerboseAsm())
1582       break;
1583     assert(MI->getNumOperands() > 7 &&
1584       "We should always have at least 7 operands!");
1585     const MachineOperand &DstOp = MI->getOperand(0);
1586     const MachineOperand &SrcOp1 = MI->getOperand(1);
1587     const MachineOperand &SrcOp2 = MI->getOperand(2);
1588     const MachineOperand &MaskOp = MI->getOperand(6);
1589     const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
1590 
1591     if (!CtrlOp.isImm())
1592       break;
1593 
1594     unsigned ElSize;
1595     switch (MI->getOpcode()) {
1596     default: llvm_unreachable("Invalid opcode");
1597     case X86::VPERMIL2PSrm: case X86::VPERMIL2PSrmY: ElSize = 32; break;
1598     case X86::VPERMIL2PDrm: case X86::VPERMIL2PDrmY: ElSize = 64; break;
1599     }
1600 
1601     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1602       SmallVector<int, 16> Mask;
1603       DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Mask);
1604       if (!Mask.empty())
1605         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp1, SrcOp2, Mask));
1606     }
1607     break;
1608   }
1609 
1610   case X86::VPPERMrrm: {
1611     if (!OutStreamer->isVerboseAsm())
1612       break;
1613     assert(MI->getNumOperands() > 6 &&
1614            "We should always have at least 6 operands!");
1615     const MachineOperand &DstOp = MI->getOperand(0);
1616     const MachineOperand &SrcOp1 = MI->getOperand(1);
1617     const MachineOperand &SrcOp2 = MI->getOperand(2);
1618     const MachineOperand &MaskOp = MI->getOperand(6);
1619 
1620     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1621       SmallVector<int, 16> Mask;
1622       DecodeVPPERMMask(C, Mask);
1623       if (!Mask.empty())
1624         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp1, SrcOp2, Mask));
1625     }
1626     break;
1627   }
1628 
1629 #define MOV_CASE(Prefix, Suffix)        \
1630   case X86::Prefix##MOVAPD##Suffix##rm: \
1631   case X86::Prefix##MOVAPS##Suffix##rm: \
1632   case X86::Prefix##MOVUPD##Suffix##rm: \
1633   case X86::Prefix##MOVUPS##Suffix##rm: \
1634   case X86::Prefix##MOVDQA##Suffix##rm: \
1635   case X86::Prefix##MOVDQU##Suffix##rm:
1636 
1637 #define MOV_AVX512_CASE(Suffix)         \
1638   case X86::VMOVDQA64##Suffix##rm:      \
1639   case X86::VMOVDQA32##Suffix##rm:      \
1640   case X86::VMOVDQU64##Suffix##rm:      \
1641   case X86::VMOVDQU32##Suffix##rm:      \
1642   case X86::VMOVDQU16##Suffix##rm:      \
1643   case X86::VMOVDQU8##Suffix##rm:       \
1644   case X86::VMOVAPS##Suffix##rm:        \
1645   case X86::VMOVAPD##Suffix##rm:        \
1646   case X86::VMOVUPS##Suffix##rm:        \
1647   case X86::VMOVUPD##Suffix##rm:
1648 
1649 #define CASE_ALL_MOV_RM()               \
1650   MOV_CASE(, )   /* SSE */              \
1651   MOV_CASE(V, )  /* AVX-128 */          \
1652   MOV_CASE(V, Y) /* AVX-256 */          \
1653   MOV_AVX512_CASE(Z)                    \
1654   MOV_AVX512_CASE(Z256)                 \
1655   MOV_AVX512_CASE(Z128)
1656 
1657   // For loads from a constant pool to a vector register, print the constant
1658   // loaded.
1659   CASE_ALL_MOV_RM()
1660     if (!OutStreamer->isVerboseAsm())
1661       break;
1662     if (MI->getNumOperands() > 4)
1663     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
1664       std::string Comment;
1665       raw_string_ostream CS(Comment);
1666       const MachineOperand &DstOp = MI->getOperand(0);
1667       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
1668       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
1669         CS << "[";
1670         for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
1671           if (i != 0)
1672             CS << ",";
1673           if (CDS->getElementType()->isIntegerTy())
1674             CS << CDS->getElementAsInteger(i);
1675           else if (CDS->getElementType()->isFloatTy())
1676             CS << CDS->getElementAsFloat(i);
1677           else if (CDS->getElementType()->isDoubleTy())
1678             CS << CDS->getElementAsDouble(i);
1679           else
1680             CS << "?";
1681         }
1682         CS << "]";
1683         OutStreamer->AddComment(CS.str());
1684       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
1685         CS << "<";
1686         for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
1687           if (i != 0)
1688             CS << ",";
1689           Constant *COp = CV->getOperand(i);
1690           if (isa<UndefValue>(COp)) {
1691             CS << "u";
1692           } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1693             if (CI->getBitWidth() <= 64) {
1694               CS << CI->getZExtValue();
1695             } else {
1696               // print multi-word constant as (w0,w1)
1697               const auto &Val = CI->getValue();
1698               CS << "(";
1699               for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1700                 if (i > 0)
1701                   CS << ",";
1702                 CS << Val.getRawData()[i];
1703               }
1704               CS << ")";
1705             }
1706           } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1707             SmallString<32> Str;
1708             CF->getValueAPF().toString(Str);
1709             CS << Str;
1710           } else {
1711             CS << "?";
1712           }
1713         }
1714         CS << ">";
1715         OutStreamer->AddComment(CS.str());
1716       }
1717     }
1718     break;
1719   }
1720 
1721   MCInst TmpInst;
1722   MCInstLowering.Lower(MI, TmpInst);
1723 
1724   // Stackmap shadows cannot include branch targets, so we can count the bytes
1725   // in a call towards the shadow, but must ensure that the no thread returns
1726   // in to the stackmap shadow.  The only way to achieve this is if the call
1727   // is at the end of the shadow.
1728   if (MI->isCall()) {
1729     // Count then size of the call towards the shadow
1730     SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
1731     // Then flush the shadow so that we fill with nops before the call, not
1732     // after it.
1733     SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1734     // Then emit the call
1735     OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
1736     return;
1737   }
1738 
1739   EmitAndCountInstruction(TmpInst);
1740 }
1741