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 "InstPrinter/X86ATTInstPrinter.h"
16 #include "InstPrinter/X86InstComments.h"
17 #include "MCTargetDesc/X86BaseInfo.h"
18 #include "MCTargetDesc/X86TargetStreamer.h"
19 #include "Utils/X86ShuffleDecode.h"
20 #include "X86AsmPrinter.h"
21 #include "X86RegisterInfo.h"
22 #include "X86ShuffleDecodeConstantPool.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/BinaryFormat/ELF.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
30 #include "llvm/CodeGen/MachineOperand.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCCodeEmitter.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCFixup.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCInstBuilder.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/MC/MCStreamer.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/MC/MCSymbolELF.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 
51 using namespace llvm;
52 
53 namespace {
54 
55 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
56 class X86MCInstLower {
57   MCContext &Ctx;
58   const MachineFunction &MF;
59   const TargetMachine &TM;
60   const MCAsmInfo &MAI;
61   X86AsmPrinter &AsmPrinter;
62 public:
63   X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
64 
65   Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
66                                           const MachineOperand &MO) const;
67   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
68 
69   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
70   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
71 
72 private:
73   MachineModuleInfoMachO &getMachOMMI() const;
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(), EnablePrintSchedInfo);
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_ABS8:      RefKind = MCSymbolRefExpr::VK_X86_ABS8; break;
220   case X86II::MO_PIC_BASE_OFFSET:
221   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
222     Expr = MCSymbolRefExpr::create(Sym, Ctx);
223     // Subtract the pic base.
224     Expr = MCBinaryExpr::createSub(Expr,
225                             MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx),
226                                    Ctx);
227     if (MO.isJTI()) {
228       assert(MAI.doesSetDirectiveSuppressReloc());
229       // If .set directive is supported, use it to reduce the number of
230       // relocations the assembler will generate for differences between
231       // local labels. This is only safe when the symbols are in the same
232       // section so we are restricting it to jumptable references.
233       MCSymbol *Label = Ctx.createTempSymbol();
234       AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
235       Expr = MCSymbolRefExpr::create(Label, Ctx);
236     }
237     break;
238   }
239 
240   if (!Expr)
241     Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
242 
243   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
244     Expr = MCBinaryExpr::createAdd(Expr,
245                                    MCConstantExpr::create(MO.getOffset(), Ctx),
246                                    Ctx);
247   return MCOperand::createExpr(Expr);
248 }
249 
250 
251 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
252 /// a short fixed-register form.
253 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
254   unsigned ImmOp = Inst.getNumOperands() - 1;
255   assert(Inst.getOperand(0).isReg() &&
256          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
257          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
258            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
259           Inst.getNumOperands() == 2) && "Unexpected instruction!");
260 
261   // Check whether the destination register can be fixed.
262   unsigned Reg = Inst.getOperand(0).getReg();
263   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
264     return;
265 
266   // If so, rewrite the instruction.
267   MCOperand Saved = Inst.getOperand(ImmOp);
268   Inst = MCInst();
269   Inst.setOpcode(Opcode);
270   Inst.addOperand(Saved);
271 }
272 
273 /// \brief If a movsx instruction has a shorter encoding for the used register
274 /// simplify the instruction to use it instead.
275 static void SimplifyMOVSX(MCInst &Inst) {
276   unsigned NewOpcode = 0;
277   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
278   switch (Inst.getOpcode()) {
279   default:
280     llvm_unreachable("Unexpected instruction!");
281   case X86::MOVSX16rr8:  // movsbw %al, %ax   --> cbtw
282     if (Op0 == X86::AX && Op1 == X86::AL)
283       NewOpcode = X86::CBW;
284     break;
285   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
286     if (Op0 == X86::EAX && Op1 == X86::AX)
287       NewOpcode = X86::CWDE;
288     break;
289   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
290     if (Op0 == X86::RAX && Op1 == X86::EAX)
291       NewOpcode = X86::CDQE;
292     break;
293   }
294 
295   if (NewOpcode != 0) {
296     Inst = MCInst();
297     Inst.setOpcode(NewOpcode);
298   }
299 }
300 
301 /// \brief Simplify things like MOV32rm to MOV32o32a.
302 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
303                                   unsigned Opcode) {
304   // Don't make these simplifications in 64-bit mode; other assemblers don't
305   // perform them because they make the code larger.
306   if (Printer.getSubtarget().is64Bit())
307     return;
308 
309   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
310   unsigned AddrBase = IsStore;
311   unsigned RegOp = IsStore ? 0 : 5;
312   unsigned AddrOp = AddrBase + 3;
313   assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
314          Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
315          Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
316          Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
317          Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
318          (Inst.getOperand(AddrOp).isExpr() ||
319           Inst.getOperand(AddrOp).isImm()) &&
320          "Unexpected instruction!");
321 
322   // Check whether the destination register can be fixed.
323   unsigned Reg = Inst.getOperand(RegOp).getReg();
324   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
325     return;
326 
327   // Check whether this is an absolute address.
328   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
329   // to do this here.
330   bool Absolute = true;
331   if (Inst.getOperand(AddrOp).isExpr()) {
332     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
333     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
334       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
335         Absolute = false;
336   }
337 
338   if (Absolute &&
339       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
340        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
341        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
342     return;
343 
344   // If so, rewrite the instruction.
345   MCOperand Saved = Inst.getOperand(AddrOp);
346   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
347   Inst = MCInst();
348   Inst.setOpcode(Opcode);
349   Inst.addOperand(Saved);
350   Inst.addOperand(Seg);
351 }
352 
353 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
354   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
355 }
356 
357 Optional<MCOperand>
358 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
359                                     const MachineOperand &MO) const {
360   switch (MO.getType()) {
361   default:
362     MI->print(errs());
363     llvm_unreachable("unknown operand type");
364   case MachineOperand::MO_Register:
365     // Ignore all implicit register operands.
366     if (MO.isImplicit())
367       return None;
368     return MCOperand::createReg(MO.getReg());
369   case MachineOperand::MO_Immediate:
370     return MCOperand::createImm(MO.getImm());
371   case MachineOperand::MO_MachineBasicBlock:
372   case MachineOperand::MO_GlobalAddress:
373   case MachineOperand::MO_ExternalSymbol:
374     return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
375   case MachineOperand::MO_MCSymbol:
376     return LowerSymbolOperand(MO, MO.getMCSymbol());
377   case MachineOperand::MO_JumpTableIndex:
378     return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
379   case MachineOperand::MO_ConstantPoolIndex:
380     return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
381   case MachineOperand::MO_BlockAddress:
382     return LowerSymbolOperand(
383         MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
384   case MachineOperand::MO_RegisterMask:
385     // Ignore call clobbers.
386     return None;
387   }
388 }
389 
390 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
391   OutMI.setOpcode(MI->getOpcode());
392 
393   for (const MachineOperand &MO : MI->operands())
394     if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
395       OutMI.addOperand(MaybeMCOp.getValue());
396 
397   // Handle a few special cases to eliminate operand modifiers.
398 ReSimplify:
399   switch (OutMI.getOpcode()) {
400   case X86::LEA64_32r:
401   case X86::LEA64r:
402   case X86::LEA16r:
403   case X86::LEA32r:
404     // LEA should have a segment register, but it must be empty.
405     assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
406            "Unexpected # of LEA operands");
407     assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
408            "LEA has segment specified!");
409     break;
410 
411   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
412   // if one of the registers is extended, but other isn't.
413   case X86::VMOVZPQILo2PQIrr:
414   case X86::VMOVAPDrr:
415   case X86::VMOVAPDYrr:
416   case X86::VMOVAPSrr:
417   case X86::VMOVAPSYrr:
418   case X86::VMOVDQArr:
419   case X86::VMOVDQAYrr:
420   case X86::VMOVDQUrr:
421   case X86::VMOVDQUYrr:
422   case X86::VMOVUPDrr:
423   case X86::VMOVUPDYrr:
424   case X86::VMOVUPSrr:
425   case X86::VMOVUPSYrr: {
426     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
427         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
428       unsigned NewOpc;
429       switch (OutMI.getOpcode()) {
430       default: llvm_unreachable("Invalid opcode");
431       case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr;   break;
432       case X86::VMOVAPDrr:        NewOpc = X86::VMOVAPDrr_REV;  break;
433       case X86::VMOVAPDYrr:       NewOpc = X86::VMOVAPDYrr_REV; break;
434       case X86::VMOVAPSrr:        NewOpc = X86::VMOVAPSrr_REV;  break;
435       case X86::VMOVAPSYrr:       NewOpc = X86::VMOVAPSYrr_REV; break;
436       case X86::VMOVDQArr:        NewOpc = X86::VMOVDQArr_REV;  break;
437       case X86::VMOVDQAYrr:       NewOpc = X86::VMOVDQAYrr_REV; break;
438       case X86::VMOVDQUrr:        NewOpc = X86::VMOVDQUrr_REV;  break;
439       case X86::VMOVDQUYrr:       NewOpc = X86::VMOVDQUYrr_REV; break;
440       case X86::VMOVUPDrr:        NewOpc = X86::VMOVUPDrr_REV;  break;
441       case X86::VMOVUPDYrr:       NewOpc = X86::VMOVUPDYrr_REV; break;
442       case X86::VMOVUPSrr:        NewOpc = X86::VMOVUPSrr_REV;  break;
443       case X86::VMOVUPSYrr:       NewOpc = X86::VMOVUPSYrr_REV; break;
444       }
445       OutMI.setOpcode(NewOpc);
446     }
447     break;
448   }
449   case X86::VMOVSDrr:
450   case X86::VMOVSSrr: {
451     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
452         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
453       unsigned NewOpc;
454       switch (OutMI.getOpcode()) {
455       default: llvm_unreachable("Invalid opcode");
456       case X86::VMOVSDrr:   NewOpc = X86::VMOVSDrr_REV;   break;
457       case X86::VMOVSSrr:   NewOpc = X86::VMOVSSrr_REV;   break;
458       }
459       OutMI.setOpcode(NewOpc);
460     }
461     break;
462   }
463 
464   // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
465   // inputs modeled as normal uses instead of implicit uses.  As such, truncate
466   // off all but the first operand (the callee).  FIXME: Change isel.
467   case X86::TAILJMPr64:
468   case X86::TAILJMPr64_REX:
469   case X86::CALL64r:
470   case X86::CALL64pcrel32: {
471     unsigned Opcode = OutMI.getOpcode();
472     MCOperand Saved = OutMI.getOperand(0);
473     OutMI = MCInst();
474     OutMI.setOpcode(Opcode);
475     OutMI.addOperand(Saved);
476     break;
477   }
478 
479   case X86::EH_RETURN:
480   case X86::EH_RETURN64: {
481     OutMI = MCInst();
482     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
483     break;
484   }
485 
486   case X86::CLEANUPRET: {
487     // Replace CATCHRET with the appropriate RET.
488     OutMI = MCInst();
489     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
490     break;
491   }
492 
493   case X86::CATCHRET: {
494     // Replace CATCHRET with the appropriate RET.
495     const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
496     unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
497     OutMI = MCInst();
498     OutMI.setOpcode(getRetOpcode(Subtarget));
499     OutMI.addOperand(MCOperand::createReg(ReturnReg));
500     break;
501   }
502 
503   // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump instruction.
504   { unsigned Opcode;
505   case X86::TAILJMPr:   Opcode = X86::JMP32r; goto SetTailJmpOpcode;
506   case X86::TAILJMPd:
507   case X86::TAILJMPd64: Opcode = X86::JMP_1;  goto SetTailJmpOpcode;
508   case X86::TAILJMPd_CC:
509   case X86::TAILJMPd64_CC:
510     Opcode = X86::GetCondBranchFromCond(
511         static_cast<X86::CondCode>(MI->getOperand(1).getImm()));
512     goto SetTailJmpOpcode;
513 
514   SetTailJmpOpcode:
515     MCOperand Saved = OutMI.getOperand(0);
516     OutMI = MCInst();
517     OutMI.setOpcode(Opcode);
518     OutMI.addOperand(Saved);
519     break;
520   }
521 
522   case X86::DEC16r:
523   case X86::DEC32r:
524   case X86::INC16r:
525   case X86::INC32r:
526     // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
527     if (!AsmPrinter.getSubtarget().is64Bit()) {
528       unsigned Opcode;
529       switch (OutMI.getOpcode()) {
530       default: llvm_unreachable("Invalid opcode");
531       case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
532       case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
533       case X86::INC16r: Opcode = X86::INC16r_alt; break;
534       case X86::INC32r: Opcode = X86::INC32r_alt; break;
535       }
536       OutMI.setOpcode(Opcode);
537     }
538     break;
539 
540   // These are pseudo-ops for OR to help with the OR->ADD transformation.  We do
541   // this with an ugly goto in case the resultant OR uses EAX and needs the
542   // short form.
543   case X86::ADD16rr_DB:   OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
544   case X86::ADD32rr_DB:   OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
545   case X86::ADD64rr_DB:   OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
546   case X86::ADD16ri_DB:   OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
547   case X86::ADD32ri_DB:   OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
548   case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
549   case X86::ADD16ri8_DB:  OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
550   case X86::ADD32ri8_DB:  OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
551   case X86::ADD64ri8_DB:  OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
552 
553   // Atomic load and store require a separate pseudo-inst because Acquire
554   // implies mayStore and Release implies mayLoad; fix these to regular MOV
555   // instructions here
556   case X86::ACQUIRE_MOV8rm:    OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
557   case X86::ACQUIRE_MOV16rm:   OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
558   case X86::ACQUIRE_MOV32rm:   OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
559   case X86::ACQUIRE_MOV64rm:   OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
560   case X86::RELEASE_MOV8mr:    OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
561   case X86::RELEASE_MOV16mr:   OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
562   case X86::RELEASE_MOV32mr:   OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
563   case X86::RELEASE_MOV64mr:   OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
564   case X86::RELEASE_MOV8mi:    OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
565   case X86::RELEASE_MOV16mi:   OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
566   case X86::RELEASE_MOV32mi:   OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
567   case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
568   case X86::RELEASE_ADD8mi:    OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
569   case X86::RELEASE_ADD8mr:    OutMI.setOpcode(X86::ADD8mr); goto ReSimplify;
570   case X86::RELEASE_ADD32mi:   OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
571   case X86::RELEASE_ADD32mr:   OutMI.setOpcode(X86::ADD32mr); goto ReSimplify;
572   case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
573   case X86::RELEASE_ADD64mr:   OutMI.setOpcode(X86::ADD64mr); goto ReSimplify;
574   case X86::RELEASE_AND8mi:    OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
575   case X86::RELEASE_AND8mr:    OutMI.setOpcode(X86::AND8mr); goto ReSimplify;
576   case X86::RELEASE_AND32mi:   OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
577   case X86::RELEASE_AND32mr:   OutMI.setOpcode(X86::AND32mr); goto ReSimplify;
578   case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
579   case X86::RELEASE_AND64mr:   OutMI.setOpcode(X86::AND64mr); goto ReSimplify;
580   case X86::RELEASE_OR8mi:     OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
581   case X86::RELEASE_OR8mr:     OutMI.setOpcode(X86::OR8mr); goto ReSimplify;
582   case X86::RELEASE_OR32mi:    OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
583   case X86::RELEASE_OR32mr:    OutMI.setOpcode(X86::OR32mr); goto ReSimplify;
584   case X86::RELEASE_OR64mi32:  OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
585   case X86::RELEASE_OR64mr:    OutMI.setOpcode(X86::OR64mr); goto ReSimplify;
586   case X86::RELEASE_XOR8mi:    OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
587   case X86::RELEASE_XOR8mr:    OutMI.setOpcode(X86::XOR8mr); goto ReSimplify;
588   case X86::RELEASE_XOR32mi:   OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
589   case X86::RELEASE_XOR32mr:   OutMI.setOpcode(X86::XOR32mr); goto ReSimplify;
590   case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
591   case X86::RELEASE_XOR64mr:   OutMI.setOpcode(X86::XOR64mr); goto ReSimplify;
592   case X86::RELEASE_INC8m:     OutMI.setOpcode(X86::INC8m); goto ReSimplify;
593   case X86::RELEASE_INC16m:    OutMI.setOpcode(X86::INC16m); goto ReSimplify;
594   case X86::RELEASE_INC32m:    OutMI.setOpcode(X86::INC32m); goto ReSimplify;
595   case X86::RELEASE_INC64m:    OutMI.setOpcode(X86::INC64m); goto ReSimplify;
596   case X86::RELEASE_DEC8m:     OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
597   case X86::RELEASE_DEC16m:    OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
598   case X86::RELEASE_DEC32m:    OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
599   case X86::RELEASE_DEC64m:    OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
600 
601   // We don't currently select the correct instruction form for instructions
602   // which have a short %eax, etc. form. Handle this by custom lowering, for
603   // now.
604   //
605   // Note, we are currently not handling the following instructions:
606   // MOV64ao8, MOV64o8a
607   // XCHG16ar, XCHG32ar, XCHG64ar
608   case X86::MOV8mr_NOREX:
609   case X86::MOV8mr:
610   case X86::MOV8rm_NOREX:
611   case X86::MOV8rm:
612   case X86::MOV16mr:
613   case X86::MOV16rm:
614   case X86::MOV32mr:
615   case X86::MOV32rm: {
616     unsigned NewOpc;
617     switch (OutMI.getOpcode()) {
618     default: llvm_unreachable("Invalid opcode");
619     case X86::MOV8mr_NOREX:
620     case X86::MOV8mr:     NewOpc = X86::MOV8o32a; break;
621     case X86::MOV8rm_NOREX:
622     case X86::MOV8rm:     NewOpc = X86::MOV8ao32; break;
623     case X86::MOV16mr:    NewOpc = X86::MOV16o32a; break;
624     case X86::MOV16rm:    NewOpc = X86::MOV16ao32; break;
625     case X86::MOV32mr:    NewOpc = X86::MOV32o32a; break;
626     case X86::MOV32rm:    NewOpc = X86::MOV32ao32; break;
627     }
628     SimplifyShortMoveForm(AsmPrinter, OutMI, NewOpc);
629     break;
630   }
631 
632   case X86::ADC8ri: case X86::ADC16ri: case X86::ADC32ri: case X86::ADC64ri32:
633   case X86::ADD8ri: case X86::ADD16ri: case X86::ADD32ri: case X86::ADD64ri32:
634   case X86::AND8ri: case X86::AND16ri: case X86::AND32ri: case X86::AND64ri32:
635   case X86::CMP8ri: case X86::CMP16ri: case X86::CMP32ri: case X86::CMP64ri32:
636   case X86::OR8ri:  case X86::OR16ri:  case X86::OR32ri:  case X86::OR64ri32:
637   case X86::SBB8ri: case X86::SBB16ri: case X86::SBB32ri: case X86::SBB64ri32:
638   case X86::SUB8ri: case X86::SUB16ri: case X86::SUB32ri: case X86::SUB64ri32:
639   case X86::TEST8ri:case X86::TEST16ri:case X86::TEST32ri:case X86::TEST64ri32:
640   case X86::XOR8ri: case X86::XOR16ri: case X86::XOR32ri: case X86::XOR64ri32: {
641     unsigned NewOpc;
642     switch (OutMI.getOpcode()) {
643     default: llvm_unreachable("Invalid opcode");
644     case X86::ADC8ri:     NewOpc = X86::ADC8i8;    break;
645     case X86::ADC16ri:    NewOpc = X86::ADC16i16;  break;
646     case X86::ADC32ri:    NewOpc = X86::ADC32i32;  break;
647     case X86::ADC64ri32:  NewOpc = X86::ADC64i32;  break;
648     case X86::ADD8ri:     NewOpc = X86::ADD8i8;    break;
649     case X86::ADD16ri:    NewOpc = X86::ADD16i16;  break;
650     case X86::ADD32ri:    NewOpc = X86::ADD32i32;  break;
651     case X86::ADD64ri32:  NewOpc = X86::ADD64i32;  break;
652     case X86::AND8ri:     NewOpc = X86::AND8i8;    break;
653     case X86::AND16ri:    NewOpc = X86::AND16i16;  break;
654     case X86::AND32ri:    NewOpc = X86::AND32i32;  break;
655     case X86::AND64ri32:  NewOpc = X86::AND64i32;  break;
656     case X86::CMP8ri:     NewOpc = X86::CMP8i8;    break;
657     case X86::CMP16ri:    NewOpc = X86::CMP16i16;  break;
658     case X86::CMP32ri:    NewOpc = X86::CMP32i32;  break;
659     case X86::CMP64ri32:  NewOpc = X86::CMP64i32;  break;
660     case X86::OR8ri:      NewOpc = X86::OR8i8;     break;
661     case X86::OR16ri:     NewOpc = X86::OR16i16;   break;
662     case X86::OR32ri:     NewOpc = X86::OR32i32;   break;
663     case X86::OR64ri32:   NewOpc = X86::OR64i32;   break;
664     case X86::SBB8ri:     NewOpc = X86::SBB8i8;    break;
665     case X86::SBB16ri:    NewOpc = X86::SBB16i16;  break;
666     case X86::SBB32ri:    NewOpc = X86::SBB32i32;  break;
667     case X86::SBB64ri32:  NewOpc = X86::SBB64i32;  break;
668     case X86::SUB8ri:     NewOpc = X86::SUB8i8;    break;
669     case X86::SUB16ri:    NewOpc = X86::SUB16i16;  break;
670     case X86::SUB32ri:    NewOpc = X86::SUB32i32;  break;
671     case X86::SUB64ri32:  NewOpc = X86::SUB64i32;  break;
672     case X86::TEST8ri:    NewOpc = X86::TEST8i8;   break;
673     case X86::TEST16ri:   NewOpc = X86::TEST16i16; break;
674     case X86::TEST32ri:   NewOpc = X86::TEST32i32; break;
675     case X86::TEST64ri32: NewOpc = X86::TEST64i32; break;
676     case X86::XOR8ri:     NewOpc = X86::XOR8i8;    break;
677     case X86::XOR16ri:    NewOpc = X86::XOR16i16;  break;
678     case X86::XOR32ri:    NewOpc = X86::XOR32i32;  break;
679     case X86::XOR64ri32:  NewOpc = X86::XOR64i32;  break;
680     }
681     SimplifyShortImmForm(OutMI, NewOpc);
682     break;
683   }
684 
685   // Try to shrink some forms of movsx.
686   case X86::MOVSX16rr8:
687   case X86::MOVSX32rr16:
688   case X86::MOVSX64rr32:
689     SimplifyMOVSX(OutMI);
690     break;
691   }
692 }
693 
694 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
695                                  const MachineInstr &MI) {
696 
697   bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
698                   MI.getOpcode() == X86::TLS_base_addr64;
699 
700   bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
701 
702   MCContext &context = OutStreamer->getContext();
703 
704   if (needsPadding)
705     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
706 
707   MCSymbolRefExpr::VariantKind SRVK;
708   switch (MI.getOpcode()) {
709     case X86::TLS_addr32:
710     case X86::TLS_addr64:
711       SRVK = MCSymbolRefExpr::VK_TLSGD;
712       break;
713     case X86::TLS_base_addr32:
714       SRVK = MCSymbolRefExpr::VK_TLSLDM;
715       break;
716     case X86::TLS_base_addr64:
717       SRVK = MCSymbolRefExpr::VK_TLSLD;
718       break;
719     default:
720       llvm_unreachable("unexpected opcode");
721   }
722 
723   MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
724   const MCSymbolRefExpr *symRef = MCSymbolRefExpr::create(sym, SRVK, context);
725 
726   MCInst LEA;
727   if (is64Bits) {
728     LEA.setOpcode(X86::LEA64r);
729     LEA.addOperand(MCOperand::createReg(X86::RDI)); // dest
730     LEA.addOperand(MCOperand::createReg(X86::RIP)); // base
731     LEA.addOperand(MCOperand::createImm(1));        // scale
732     LEA.addOperand(MCOperand::createReg(0));        // index
733     LEA.addOperand(MCOperand::createExpr(symRef));  // disp
734     LEA.addOperand(MCOperand::createReg(0));        // seg
735   } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
736     LEA.setOpcode(X86::LEA32r);
737     LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
738     LEA.addOperand(MCOperand::createReg(X86::EBX)); // base
739     LEA.addOperand(MCOperand::createImm(1));        // scale
740     LEA.addOperand(MCOperand::createReg(0));        // index
741     LEA.addOperand(MCOperand::createExpr(symRef));  // disp
742     LEA.addOperand(MCOperand::createReg(0));        // seg
743   } else {
744     LEA.setOpcode(X86::LEA32r);
745     LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
746     LEA.addOperand(MCOperand::createReg(0));        // base
747     LEA.addOperand(MCOperand::createImm(1));        // scale
748     LEA.addOperand(MCOperand::createReg(X86::EBX)); // index
749     LEA.addOperand(MCOperand::createExpr(symRef));  // disp
750     LEA.addOperand(MCOperand::createReg(0));        // seg
751   }
752   EmitAndCountInstruction(LEA);
753 
754   if (needsPadding) {
755     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
756     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
757     EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
758   }
759 
760   StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
761   MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name);
762   const MCSymbolRefExpr *tlsRef =
763     MCSymbolRefExpr::create(tlsGetAddr,
764                             MCSymbolRefExpr::VK_PLT,
765                             context);
766 
767   EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
768                                                  : X86::CALLpcrel32)
769                             .addExpr(tlsRef));
770 }
771 
772 /// \brief Emit the largest nop instruction smaller than or equal to \p NumBytes
773 /// bytes.  Return the size of nop emitted.
774 static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
775                         const MCSubtargetInfo &STI) {
776   // This works only for 64bit. For 32bit we have to do additional checking if
777   // the CPU supports multi-byte nops.
778   assert(Is64Bit && "EmitNops only supports X86-64");
779 
780   unsigned NopSize;
781   unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
782   Opc = IndexReg = Displacement = SegmentReg = 0;
783   BaseReg = X86::RAX;
784   ScaleVal = 1;
785   switch (NumBytes) {
786   case  0: llvm_unreachable("Zero nops?"); break;
787   case  1: NopSize = 1; Opc = X86::NOOP; break;
788   case  2: NopSize = 2; Opc = X86::XCHG16ar; break;
789   case  3: NopSize = 3; Opc = X86::NOOPL; break;
790   case  4: NopSize = 4; Opc = X86::NOOPL; Displacement = 8; break;
791   case  5: NopSize = 5; Opc = X86::NOOPL; Displacement = 8;
792            IndexReg = X86::RAX; break;
793   case  6: NopSize = 6; Opc = X86::NOOPW; Displacement = 8;
794            IndexReg = X86::RAX; break;
795   case  7: NopSize = 7; Opc = X86::NOOPL; Displacement = 512; break;
796   case  8: NopSize = 8; Opc = X86::NOOPL; Displacement = 512;
797            IndexReg = X86::RAX; break;
798   case  9: NopSize = 9; Opc = X86::NOOPW; Displacement = 512;
799            IndexReg = X86::RAX; break;
800   default: NopSize = 10; Opc = X86::NOOPW; Displacement = 512;
801            IndexReg = X86::RAX; SegmentReg = X86::CS; break;
802   }
803 
804   unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
805   NopSize += NumPrefixes;
806   for (unsigned i = 0; i != NumPrefixes; ++i)
807     OS.EmitBytes("\x66");
808 
809   switch (Opc) {
810   default:
811     llvm_unreachable("Unexpected opcode");
812     break;
813   case X86::NOOP:
814     OS.EmitInstruction(MCInstBuilder(Opc), STI);
815     break;
816   case X86::XCHG16ar:
817     OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
818     break;
819   case X86::NOOPL:
820   case X86::NOOPW:
821     OS.EmitInstruction(MCInstBuilder(Opc)
822                            .addReg(BaseReg)
823                            .addImm(ScaleVal)
824                            .addReg(IndexReg)
825                            .addImm(Displacement)
826                            .addReg(SegmentReg),
827                        STI);
828     break;
829   }
830   assert(NopSize <= NumBytes && "We overemitted?");
831   return NopSize;
832 }
833 
834 /// \brief Emit the optimal amount of multi-byte nops on X86.
835 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
836                      const MCSubtargetInfo &STI) {
837   unsigned NopsToEmit = NumBytes;
838   (void)NopsToEmit;
839   while (NumBytes) {
840     NumBytes -= EmitNop(OS, NumBytes, Is64Bit, STI);
841     assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
842   }
843 }
844 
845 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
846                                     X86MCInstLower &MCIL) {
847   assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
848 
849   StatepointOpers SOpers(&MI);
850   if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
851     EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
852              getSubtargetInfo());
853   } else {
854     // Lower call target and choose correct opcode
855     const MachineOperand &CallTarget = SOpers.getCallTarget();
856     MCOperand CallTargetMCOp;
857     unsigned CallOpcode;
858     switch (CallTarget.getType()) {
859     case MachineOperand::MO_GlobalAddress:
860     case MachineOperand::MO_ExternalSymbol:
861       CallTargetMCOp = MCIL.LowerSymbolOperand(
862           CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
863       CallOpcode = X86::CALL64pcrel32;
864       // Currently, we only support relative addressing with statepoints.
865       // Otherwise, we'll need a scratch register to hold the target
866       // address.  You'll fail asserts during load & relocation if this
867       // symbol is to far away. (TODO: support non-relative addressing)
868       break;
869     case MachineOperand::MO_Immediate:
870       CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
871       CallOpcode = X86::CALL64pcrel32;
872       // Currently, we only support relative addressing with statepoints.
873       // Otherwise, we'll need a scratch register to hold the target
874       // immediate.  You'll fail asserts during load & relocation if this
875       // address is to far away. (TODO: support non-relative addressing)
876       break;
877     case MachineOperand::MO_Register:
878       CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
879       CallOpcode = X86::CALL64r;
880       break;
881     default:
882       llvm_unreachable("Unsupported operand type in statepoint call target");
883       break;
884     }
885 
886     // Emit call
887     MCInst CallInst;
888     CallInst.setOpcode(CallOpcode);
889     CallInst.addOperand(CallTargetMCOp);
890     OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
891   }
892 
893   // Record our statepoint node in the same section used by STACKMAP
894   // and PATCHPOINT
895   SM.recordStatepoint(MI);
896 }
897 
898 void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
899                                      X86MCInstLower &MCIL) {
900   // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
901   //                  <opcode>, <operands>
902 
903   unsigned DefRegister = FaultingMI.getOperand(0).getReg();
904   FaultMaps::FaultKind FK =
905       static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
906   MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
907   unsigned Opcode = FaultingMI.getOperand(3).getImm();
908   unsigned OperandsBeginIdx = 4;
909 
910   assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
911   FM.recordFaultingOp(FK, HandlerLabel);
912 
913   MCInst MI;
914   MI.setOpcode(Opcode);
915 
916   if (DefRegister != X86::NoRegister)
917     MI.addOperand(MCOperand::createReg(DefRegister));
918 
919   for (auto I = FaultingMI.operands_begin() + OperandsBeginIdx,
920             E = FaultingMI.operands_end();
921        I != E; ++I)
922     if (auto MaybeOperand = MCIL.LowerMachineOperand(&FaultingMI, *I))
923       MI.addOperand(MaybeOperand.getValue());
924 
925   OutStreamer->EmitInstruction(MI, getSubtargetInfo());
926 }
927 
928 void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
929                                      X86MCInstLower &MCIL) {
930   bool Is64Bits = Subtarget->is64Bit();
931   MCContext &Ctx = OutStreamer->getContext();
932   MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
933   const MCSymbolRefExpr *Op =
934       MCSymbolRefExpr::create(fentry, MCSymbolRefExpr::VK_None, Ctx);
935 
936   EmitAndCountInstruction(
937       MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
938           .addExpr(Op));
939 }
940 
941 void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
942                                       X86MCInstLower &MCIL) {
943   // PATCHABLE_OP minsize, opcode, operands
944 
945   unsigned MinSize = MI.getOperand(0).getImm();
946   unsigned Opcode = MI.getOperand(1).getImm();
947 
948   MCInst MCI;
949   MCI.setOpcode(Opcode);
950   for (auto &MO : make_range(MI.operands_begin() + 2, MI.operands_end()))
951     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
952       MCI.addOperand(MaybeOperand.getValue());
953 
954   SmallString<256> Code;
955   SmallVector<MCFixup, 4> Fixups;
956   raw_svector_ostream VecOS(Code);
957   CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
958 
959   if (Code.size() < MinSize) {
960     if (MinSize == 2 && Opcode == X86::PUSH64r) {
961       // This is an optimization that lets us get away without emitting a nop in
962       // many cases.
963       //
964       // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %R9) takes two
965       // bytes too, so the check on MinSize is important.
966       MCI.setOpcode(X86::PUSH64rmr);
967     } else {
968       unsigned NopSize = EmitNop(*OutStreamer, MinSize, Subtarget->is64Bit(),
969                                  getSubtargetInfo());
970       assert(NopSize == MinSize && "Could not implement MinSize!");
971       (void) NopSize;
972     }
973   }
974 
975   OutStreamer->EmitInstruction(MCI, getSubtargetInfo());
976 }
977 
978 // Lower a stackmap of the form:
979 // <id>, <shadowBytes>, ...
980 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
981   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
982   SM.recordStackMap(MI);
983   unsigned NumShadowBytes = MI.getOperand(1).getImm();
984   SMShadowTracker.reset(NumShadowBytes);
985 }
986 
987 // Lower a patchpoint of the form:
988 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
989 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
990                                     X86MCInstLower &MCIL) {
991   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
992 
993   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
994 
995   SM.recordPatchPoint(MI);
996 
997   PatchPointOpers opers(&MI);
998   unsigned ScratchIdx = opers.getNextScratchIdx();
999   unsigned EncodedBytes = 0;
1000   const MachineOperand &CalleeMO = opers.getCallTarget();
1001 
1002   // Check for null target. If target is non-null (i.e. is non-zero or is
1003   // symbolic) then emit a call.
1004   if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
1005     MCOperand CalleeMCOp;
1006     switch (CalleeMO.getType()) {
1007     default:
1008       /// FIXME: Add a verifier check for bad callee types.
1009       llvm_unreachable("Unrecognized callee operand type.");
1010     case MachineOperand::MO_Immediate:
1011       if (CalleeMO.getImm())
1012         CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
1013       break;
1014     case MachineOperand::MO_ExternalSymbol:
1015     case MachineOperand::MO_GlobalAddress:
1016       CalleeMCOp =
1017         MCIL.LowerSymbolOperand(CalleeMO,
1018                                 MCIL.GetSymbolFromOperand(CalleeMO));
1019       break;
1020     }
1021 
1022     // Emit MOV to materialize the target address and the CALL to target.
1023     // This is encoded with 12-13 bytes, depending on which register is used.
1024     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
1025     if (X86II::isX86_64ExtendedReg(ScratchReg))
1026       EncodedBytes = 13;
1027     else
1028       EncodedBytes = 12;
1029 
1030     EmitAndCountInstruction(
1031         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1032     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1033   }
1034 
1035   // Emit padding.
1036   unsigned NumBytes = opers.getNumPatchBytes();
1037   assert(NumBytes >= EncodedBytes &&
1038          "Patchpoint can't request size less than the length of a call.");
1039 
1040   EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
1041            getSubtargetInfo());
1042 }
1043 
1044 void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
1045                                               X86MCInstLower &MCIL) {
1046   assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
1047 
1048   // We want to emit the following pattern, which follows the x86 calling
1049   // convention to prepare for the trampoline call to be patched in.
1050   //
1051   //   .p2align 1, ...
1052   // .Lxray_event_sled_N:
1053   //   jmp +N                        // jump across the instrumentation sled
1054   //   ...                           // set up arguments in register
1055   //   callq __xray_CustomEvent@plt  // force dependency to symbol
1056   //   ...
1057   //   <jump here>
1058   //
1059   // After patching, it would look something like:
1060   //
1061   //   nopw (2-byte nop)
1062   //   ...
1063   //   callq __xrayCustomEvent  // already lowered
1064   //   ...
1065   //
1066   // ---
1067   // First we emit the label and the jump.
1068   auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
1069   OutStreamer->AddComment("# XRay Custom Event Log");
1070   OutStreamer->EmitCodeAlignment(2);
1071   OutStreamer->EmitLabel(CurSled);
1072 
1073   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1074   // an operand (computed as an offset from the jmp instruction).
1075   // FIXME: Find another less hacky way do force the relative jump.
1076   OutStreamer->EmitBinaryData("\xeb\x0f");
1077 
1078   // The default C calling convention will place two arguments into %rcx and
1079   // %rdx -- so we only work with those.
1080   unsigned UsedRegs[] = {X86::RDI, X86::RSI};
1081   bool UsedMask[] = {false, false};
1082 
1083   // Then we put the operands in the %rdi and %rsi registers. We spill the
1084   // values in the register before we clobber them, and mark them as used in
1085   // UsedMask. In case the arguments are already in the correct register, we use
1086   // emit nops appropriately sized to keep the sled the same size in every
1087   // situation.
1088   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1089     if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1090       assert(Op->isReg() && "Only support arguments in registers");
1091       if (Op->getReg() != UsedRegs[I]) {
1092         UsedMask[I] = true;
1093         EmitAndCountInstruction(
1094             MCInstBuilder(X86::PUSH64r).addReg(UsedRegs[I]));
1095         EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
1096                                     .addReg(UsedRegs[I])
1097                                     .addReg(Op->getReg()));
1098       } else {
1099         EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1100       }
1101     }
1102 
1103   // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
1104   // name of the trampoline to be implemented by the XRay runtime.
1105   auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
1106   MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1107   if (isPositionIndependent())
1108     TOp.setTargetFlags(X86II::MO_PLT);
1109 
1110   // Emit the call instruction.
1111   EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1112                               .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1113 
1114   // Restore caller-saved and used registers.
1115   for (unsigned I = sizeof UsedMask; I-- > 0;)
1116     if (UsedMask[I])
1117       EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(UsedRegs[I]));
1118     else
1119       EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1120 
1121   OutStreamer->AddComment("xray custom event end.");
1122 
1123   // Record the sled version. Older versions of this sled were spelled
1124   // differently, so we let the runtime handle the different offsets we're
1125   // using.
1126   recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 1);
1127 }
1128 
1129 void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1130                                                   X86MCInstLower &MCIL) {
1131   // We want to emit the following pattern:
1132   //
1133   //   .p2align 1, ...
1134   // .Lxray_sled_N:
1135   //   jmp .tmpN
1136   //   # 9 bytes worth of noops
1137   //
1138   // We need the 9 bytes because at runtime, we'd be patching over the full 11
1139   // bytes with the following pattern:
1140   //
1141   //   mov %r10, <function id, 32-bit>   // 6 bytes
1142   //   call <relative offset, 32-bits>   // 5 bytes
1143   //
1144   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1145   OutStreamer->EmitCodeAlignment(2);
1146   OutStreamer->EmitLabel(CurSled);
1147 
1148   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1149   // an operand (computed as an offset from the jmp instruction).
1150   // FIXME: Find another less hacky way do force the relative jump.
1151   OutStreamer->EmitBytes("\xeb\x09");
1152   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1153   recordSled(CurSled, MI, SledKind::FUNCTION_ENTER);
1154 }
1155 
1156 void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1157                                        X86MCInstLower &MCIL) {
1158   // Since PATCHABLE_RET takes the opcode of the return statement as an
1159   // argument, we use that to emit the correct form of the RET that we want.
1160   // i.e. when we see this:
1161   //
1162   //   PATCHABLE_RET X86::RET ...
1163   //
1164   // We should emit the RET followed by sleds.
1165   //
1166   //   .p2align 1, ...
1167   // .Lxray_sled_N:
1168   //   ret  # or equivalent instruction
1169   //   # 10 bytes worth of noops
1170   //
1171   // This just makes sure that the alignment for the next instruction is 2.
1172   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1173   OutStreamer->EmitCodeAlignment(2);
1174   OutStreamer->EmitLabel(CurSled);
1175   unsigned OpCode = MI.getOperand(0).getImm();
1176   MCInst Ret;
1177   Ret.setOpcode(OpCode);
1178   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1179     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1180       Ret.addOperand(MaybeOperand.getValue());
1181   OutStreamer->EmitInstruction(Ret, getSubtargetInfo());
1182   EmitNops(*OutStreamer, 10, Subtarget->is64Bit(), getSubtargetInfo());
1183   recordSled(CurSled, MI, SledKind::FUNCTION_EXIT);
1184 }
1185 
1186 void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI, X86MCInstLower &MCIL) {
1187   // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1188   // instruction so we lower that particular instruction and its operands.
1189   // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1190   // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1191   // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1192   // tail call much like how we have it in PATCHABLE_RET.
1193   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1194   OutStreamer->EmitCodeAlignment(2);
1195   OutStreamer->EmitLabel(CurSled);
1196   auto Target = OutContext.createTempSymbol();
1197 
1198   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1199   // an operand (computed as an offset from the jmp instruction).
1200   // FIXME: Find another less hacky way do force the relative jump.
1201   OutStreamer->EmitBytes("\xeb\x09");
1202   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1203   OutStreamer->EmitLabel(Target);
1204   recordSled(CurSled, MI, SledKind::TAIL_CALL);
1205 
1206   unsigned OpCode = MI.getOperand(0).getImm();
1207   MCInst TC;
1208   TC.setOpcode(OpCode);
1209 
1210   // Before emitting the instruction, add a comment to indicate that this is
1211   // indeed a tail call.
1212   OutStreamer->AddComment("TAILCALL");
1213   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1214     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1215       TC.addOperand(MaybeOperand.getValue());
1216   OutStreamer->EmitInstruction(TC, getSubtargetInfo());
1217 }
1218 
1219 // Returns instruction preceding MBBI in MachineFunction.
1220 // If MBBI is the first instruction of the first basic block, returns null.
1221 static MachineBasicBlock::const_iterator
1222 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
1223   const MachineBasicBlock *MBB = MBBI->getParent();
1224   while (MBBI == MBB->begin()) {
1225     if (MBB == &MBB->getParent()->front())
1226       return MachineBasicBlock::const_iterator();
1227     MBB = MBB->getPrevNode();
1228     MBBI = MBB->end();
1229   }
1230   return --MBBI;
1231 }
1232 
1233 static const Constant *getConstantFromPool(const MachineInstr &MI,
1234                                            const MachineOperand &Op) {
1235   if (!Op.isCPI())
1236     return nullptr;
1237 
1238   ArrayRef<MachineConstantPoolEntry> Constants =
1239       MI.getParent()->getParent()->getConstantPool()->getConstants();
1240   const MachineConstantPoolEntry &ConstantEntry =
1241       Constants[Op.getIndex()];
1242 
1243   // Bail if this is a machine constant pool entry, we won't be able to dig out
1244   // anything useful.
1245   if (ConstantEntry.isMachineConstantPoolEntry())
1246     return nullptr;
1247 
1248   auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
1249   assert((!C || ConstantEntry.getType() == C->getType()) &&
1250          "Expected a constant of the same type!");
1251   return C;
1252 }
1253 
1254 static std::string getShuffleComment(const MachineInstr *MI,
1255                                      unsigned SrcOp1Idx,
1256                                      unsigned SrcOp2Idx,
1257                                      ArrayRef<int> Mask) {
1258   std::string Comment;
1259 
1260   // Compute the name for a register. This is really goofy because we have
1261   // multiple instruction printers that could (in theory) use different
1262   // names. Fortunately most people use the ATT style (outside of Windows)
1263   // and they actually agree on register naming here. Ultimately, this is
1264   // a comment, and so its OK if it isn't perfect.
1265   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1266     return X86ATTInstPrinter::getRegisterName(RegNum);
1267   };
1268 
1269   const MachineOperand &DstOp = MI->getOperand(0);
1270   const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
1271   const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
1272 
1273   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1274   StringRef Src1Name =
1275       SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
1276   StringRef Src2Name =
1277       SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
1278 
1279   // One source operand, fix the mask to print all elements in one span.
1280   SmallVector<int, 8> ShuffleMask(Mask.begin(), Mask.end());
1281   if (Src1Name == Src2Name)
1282     for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1283       if (ShuffleMask[i] >= e)
1284         ShuffleMask[i] -= e;
1285 
1286   raw_string_ostream CS(Comment);
1287   CS << DstName;
1288 
1289   // Handle AVX512 MASK/MASXZ write mask comments.
1290   // MASK: zmmX {%kY}
1291   // MASKZ: zmmX {%kY} {z}
1292   if (SrcOp1Idx > 1) {
1293     assert((SrcOp1Idx == 2 || SrcOp1Idx == 3) && "Unexpected writemask");
1294 
1295     const MachineOperand &WriteMaskOp = MI->getOperand(SrcOp1Idx - 1);
1296     if (WriteMaskOp.isReg()) {
1297       CS << " {%" << GetRegisterName(WriteMaskOp.getReg()) << "}";
1298 
1299       if (SrcOp1Idx == 2) {
1300         CS << " {z}";
1301       }
1302     }
1303   }
1304 
1305   CS << " = ";
1306 
1307   for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1308     if (i != 0)
1309       CS << ",";
1310     if (ShuffleMask[i] == SM_SentinelZero) {
1311       CS << "zero";
1312       continue;
1313     }
1314 
1315     // Otherwise, it must come from src1 or src2.  Print the span of elements
1316     // that comes from this src.
1317     bool isSrc1 = ShuffleMask[i] < (int)e;
1318     CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1319 
1320     bool IsFirst = true;
1321     while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1322            (ShuffleMask[i] < (int)e) == isSrc1) {
1323       if (!IsFirst)
1324         CS << ',';
1325       else
1326         IsFirst = false;
1327       if (ShuffleMask[i] == SM_SentinelUndef)
1328         CS << "u";
1329       else
1330         CS << ShuffleMask[i] % (int)e;
1331       ++i;
1332     }
1333     CS << ']';
1334     --i; // For loop increments element #.
1335   }
1336   CS.flush();
1337 
1338   return Comment;
1339 }
1340 
1341 static void printConstant(const Constant *COp, raw_ostream &CS) {
1342   if (isa<UndefValue>(COp)) {
1343     CS << "u";
1344   } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1345     if (CI->getBitWidth() <= 64) {
1346       CS << CI->getZExtValue();
1347     } else {
1348       // print multi-word constant as (w0,w1)
1349       const auto &Val = CI->getValue();
1350       CS << "(";
1351       for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1352         if (i > 0)
1353           CS << ",";
1354         CS << Val.getRawData()[i];
1355       }
1356       CS << ")";
1357     }
1358   } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1359     SmallString<32> Str;
1360     CF->getValueAPF().toString(Str);
1361     CS << Str;
1362   } else {
1363     CS << "?";
1364   }
1365 }
1366 
1367 void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
1368   assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1369   assert(getSubtarget().isOSWindows() && "SEH_ instruction Windows only");
1370   const X86RegisterInfo *RI =
1371       MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1372 
1373   // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
1374   if (EmitFPOData) {
1375     X86TargetStreamer *XTS =
1376         static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
1377     switch (MI->getOpcode()) {
1378     case X86::SEH_PushReg:
1379       XTS->emitFPOPushReg(MI->getOperand(0).getImm());
1380       break;
1381     case X86::SEH_StackAlloc:
1382       XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
1383       break;
1384     case X86::SEH_SetFrame:
1385       assert(MI->getOperand(1).getImm() == 0 &&
1386              ".cv_fpo_setframe takes no offset");
1387       XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
1388       break;
1389     case X86::SEH_EndPrologue:
1390       XTS->emitFPOEndPrologue();
1391       break;
1392     case X86::SEH_SaveReg:
1393     case X86::SEH_SaveXMM:
1394     case X86::SEH_PushFrame:
1395       llvm_unreachable("SEH_ directive incompatible with FPO");
1396       break;
1397     default:
1398       llvm_unreachable("expected SEH_ instruction");
1399     }
1400     return;
1401   }
1402 
1403   // Otherwise, use the .seh_ directives for all other Windows platforms.
1404   switch (MI->getOpcode()) {
1405   case X86::SEH_PushReg:
1406     OutStreamer->EmitWinCFIPushReg(
1407         RI->getSEHRegNum(MI->getOperand(0).getImm()));
1408     break;
1409 
1410   case X86::SEH_SaveReg:
1411     OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1412                                    MI->getOperand(1).getImm());
1413     break;
1414 
1415   case X86::SEH_SaveXMM:
1416     OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1417                                    MI->getOperand(1).getImm());
1418     break;
1419 
1420   case X86::SEH_StackAlloc:
1421     OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1422     break;
1423 
1424   case X86::SEH_SetFrame:
1425     OutStreamer->EmitWinCFISetFrame(
1426         RI->getSEHRegNum(MI->getOperand(0).getImm()),
1427         MI->getOperand(1).getImm());
1428     break;
1429 
1430   case X86::SEH_PushFrame:
1431     OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1432     break;
1433 
1434   case X86::SEH_EndPrologue:
1435     OutStreamer->EmitWinCFIEndProlog();
1436     break;
1437 
1438   default:
1439     llvm_unreachable("expected SEH_ instruction");
1440   }
1441 }
1442 
1443 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
1444   X86MCInstLower MCInstLowering(*MF, *this);
1445   const X86RegisterInfo *RI = MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1446 
1447   // Add a comment about EVEX-2-VEX compression for AVX-512 instrs that
1448   // are compressed from EVEX encoding to VEX encoding.
1449   if (TM.Options.MCOptions.ShowMCEncoding) {
1450     if (MI->getAsmPrinterFlags() & AC_EVEX_2_VEX)
1451       OutStreamer->AddComment("EVEX TO VEX Compression ", false);
1452   }
1453 
1454   switch (MI->getOpcode()) {
1455   case TargetOpcode::DBG_VALUE:
1456     llvm_unreachable("Should be handled target independently");
1457 
1458   // Emit nothing here but a comment if we can.
1459   case X86::Int_MemBarrier:
1460     OutStreamer->emitRawComment("MEMBARRIER");
1461     return;
1462 
1463 
1464   case X86::EH_RETURN:
1465   case X86::EH_RETURN64: {
1466     // Lower these as normal, but add some comments.
1467     unsigned Reg = MI->getOperand(0).getReg();
1468     OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1469                             X86ATTInstPrinter::getRegisterName(Reg));
1470     break;
1471   }
1472   case X86::CLEANUPRET: {
1473     // Lower these as normal, but add some comments.
1474     OutStreamer->AddComment("CLEANUPRET");
1475     break;
1476   }
1477 
1478   case X86::CATCHRET: {
1479     // Lower these as normal, but add some comments.
1480     OutStreamer->AddComment("CATCHRET");
1481     break;
1482   }
1483 
1484   case X86::TAILJMPr:
1485   case X86::TAILJMPm:
1486   case X86::TAILJMPd:
1487   case X86::TAILJMPd_CC:
1488   case X86::TAILJMPr64:
1489   case X86::TAILJMPm64:
1490   case X86::TAILJMPd64:
1491   case X86::TAILJMPd64_CC:
1492   case X86::TAILJMPr64_REX:
1493   case X86::TAILJMPm64_REX:
1494     // Lower these as normal, but add some comments.
1495     OutStreamer->AddComment("TAILCALL");
1496     break;
1497 
1498   case X86::TLS_addr32:
1499   case X86::TLS_addr64:
1500   case X86::TLS_base_addr32:
1501   case X86::TLS_base_addr64:
1502     return LowerTlsAddr(MCInstLowering, *MI);
1503 
1504   case X86::MOVPC32r: {
1505     // This is a pseudo op for a two instruction sequence with a label, which
1506     // looks like:
1507     //     call "L1$pb"
1508     // "L1$pb":
1509     //     popl %esi
1510 
1511     // Emit the call.
1512     MCSymbol *PICBase = MF->getPICBaseSymbol();
1513     // FIXME: We would like an efficient form for this, so we don't have to do a
1514     // lot of extra uniquing.
1515     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
1516       .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
1517 
1518     const X86FrameLowering* FrameLowering =
1519         MF->getSubtarget<X86Subtarget>().getFrameLowering();
1520     bool hasFP = FrameLowering->hasFP(*MF);
1521 
1522     // TODO: This is needed only if we require precise CFA.
1523     bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
1524                                !OutStreamer->getDwarfFrameInfos().back().End;
1525 
1526     int stackGrowth = -RI->getSlotSize();
1527 
1528     if (HasActiveDwarfFrame && !hasFP) {
1529       OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
1530     }
1531 
1532     // Emit the label.
1533     OutStreamer->EmitLabel(PICBase);
1534 
1535     // popl $reg
1536     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
1537                             .addReg(MI->getOperand(0).getReg()));
1538 
1539     if (HasActiveDwarfFrame && !hasFP) {
1540       OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
1541     }
1542     return;
1543   }
1544 
1545   case X86::ADD32ri: {
1546     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
1547     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
1548       break;
1549 
1550     // Okay, we have something like:
1551     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
1552 
1553     // For this, we want to print something like:
1554     //   MYGLOBAL + (. - PICBASE)
1555     // However, we can't generate a ".", so just emit a new label here and refer
1556     // to it.
1557     MCSymbol *DotSym = OutContext.createTempSymbol();
1558     OutStreamer->EmitLabel(DotSym);
1559 
1560     // Now that we have emitted the label, lower the complex operand expression.
1561     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
1562 
1563     const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1564     const MCExpr *PICBase =
1565       MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
1566     DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
1567 
1568     DotExpr = MCBinaryExpr::createAdd(MCSymbolRefExpr::create(OpSym,OutContext),
1569                                       DotExpr, OutContext);
1570 
1571     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
1572       .addReg(MI->getOperand(0).getReg())
1573       .addReg(MI->getOperand(1).getReg())
1574       .addExpr(DotExpr));
1575     return;
1576   }
1577   case TargetOpcode::STATEPOINT:
1578     return LowerSTATEPOINT(*MI, MCInstLowering);
1579 
1580   case TargetOpcode::FAULTING_OP:
1581     return LowerFAULTING_OP(*MI, MCInstLowering);
1582 
1583   case TargetOpcode::FENTRY_CALL:
1584     return LowerFENTRY_CALL(*MI, MCInstLowering);
1585 
1586   case TargetOpcode::PATCHABLE_OP:
1587     return LowerPATCHABLE_OP(*MI, MCInstLowering);
1588 
1589   case TargetOpcode::STACKMAP:
1590     return LowerSTACKMAP(*MI);
1591 
1592   case TargetOpcode::PATCHPOINT:
1593     return LowerPATCHPOINT(*MI, MCInstLowering);
1594 
1595   case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
1596     return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
1597 
1598   case TargetOpcode::PATCHABLE_RET:
1599     return LowerPATCHABLE_RET(*MI, MCInstLowering);
1600 
1601   case TargetOpcode::PATCHABLE_TAIL_CALL:
1602     return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
1603 
1604   case TargetOpcode::PATCHABLE_EVENT_CALL:
1605     return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
1606 
1607   case X86::MORESTACK_RET:
1608     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1609     return;
1610 
1611   case X86::MORESTACK_RET_RESTORE_R10:
1612     // Return, then restore R10.
1613     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1614     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
1615                             .addReg(X86::R10)
1616                             .addReg(X86::RAX));
1617     return;
1618 
1619   case X86::SEH_PushReg:
1620   case X86::SEH_SaveReg:
1621   case X86::SEH_SaveXMM:
1622   case X86::SEH_StackAlloc:
1623   case X86::SEH_SetFrame:
1624   case X86::SEH_PushFrame:
1625   case X86::SEH_EndPrologue:
1626     EmitSEHInstruction(MI);
1627     return;
1628 
1629   case X86::SEH_Epilogue: {
1630     assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1631     MachineBasicBlock::const_iterator MBBI(MI);
1632     // Check if preceded by a call and emit nop if so.
1633     for (MBBI = PrevCrossBBInst(MBBI);
1634          MBBI != MachineBasicBlock::const_iterator();
1635          MBBI = PrevCrossBBInst(MBBI)) {
1636       // Conservatively assume that pseudo instructions don't emit code and keep
1637       // looking for a call. We may emit an unnecessary nop in some cases.
1638       if (!MBBI->isPseudo()) {
1639         if (MBBI->isCall())
1640           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
1641         break;
1642       }
1643     }
1644     return;
1645   }
1646 
1647   // Lower PSHUFB and VPERMILP normally but add a comment if we can find
1648   // a constant shuffle mask. We won't be able to do this at the MC layer
1649   // because the mask isn't an immediate.
1650   case X86::PSHUFBrm:
1651   case X86::VPSHUFBrm:
1652   case X86::VPSHUFBYrm:
1653   case X86::VPSHUFBZ128rm:
1654   case X86::VPSHUFBZ128rmk:
1655   case X86::VPSHUFBZ128rmkz:
1656   case X86::VPSHUFBZ256rm:
1657   case X86::VPSHUFBZ256rmk:
1658   case X86::VPSHUFBZ256rmkz:
1659   case X86::VPSHUFBZrm:
1660   case X86::VPSHUFBZrmk:
1661   case X86::VPSHUFBZrmkz: {
1662     if (!OutStreamer->isVerboseAsm())
1663       break;
1664     unsigned SrcIdx, MaskIdx;
1665     switch (MI->getOpcode()) {
1666     default: llvm_unreachable("Invalid opcode");
1667     case X86::PSHUFBrm:
1668     case X86::VPSHUFBrm:
1669     case X86::VPSHUFBYrm:
1670     case X86::VPSHUFBZ128rm:
1671     case X86::VPSHUFBZ256rm:
1672     case X86::VPSHUFBZrm:
1673       SrcIdx = 1; MaskIdx = 5; break;
1674     case X86::VPSHUFBZ128rmkz:
1675     case X86::VPSHUFBZ256rmkz:
1676     case X86::VPSHUFBZrmkz:
1677       SrcIdx = 2; MaskIdx = 6; break;
1678     case X86::VPSHUFBZ128rmk:
1679     case X86::VPSHUFBZ256rmk:
1680     case X86::VPSHUFBZrmk:
1681       SrcIdx = 3; MaskIdx = 7; break;
1682     }
1683 
1684     assert(MI->getNumOperands() >= 6 &&
1685            "We should always have at least 6 operands!");
1686 
1687     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1688     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1689       SmallVector<int, 64> Mask;
1690       DecodePSHUFBMask(C, Mask);
1691       if (!Mask.empty())
1692         OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask),
1693                                 !EnablePrintSchedInfo);
1694     }
1695     break;
1696   }
1697 
1698   case X86::VPERMILPSrm:
1699   case X86::VPERMILPSYrm:
1700   case X86::VPERMILPSZ128rm:
1701   case X86::VPERMILPSZ128rmk:
1702   case X86::VPERMILPSZ128rmkz:
1703   case X86::VPERMILPSZ256rm:
1704   case X86::VPERMILPSZ256rmk:
1705   case X86::VPERMILPSZ256rmkz:
1706   case X86::VPERMILPSZrm:
1707   case X86::VPERMILPSZrmk:
1708   case X86::VPERMILPSZrmkz:
1709   case X86::VPERMILPDrm:
1710   case X86::VPERMILPDYrm:
1711   case X86::VPERMILPDZ128rm:
1712   case X86::VPERMILPDZ128rmk:
1713   case X86::VPERMILPDZ128rmkz:
1714   case X86::VPERMILPDZ256rm:
1715   case X86::VPERMILPDZ256rmk:
1716   case X86::VPERMILPDZ256rmkz:
1717   case X86::VPERMILPDZrm:
1718   case X86::VPERMILPDZrmk:
1719   case X86::VPERMILPDZrmkz: {
1720     if (!OutStreamer->isVerboseAsm())
1721       break;
1722     unsigned SrcIdx, MaskIdx;
1723     unsigned ElSize;
1724     switch (MI->getOpcode()) {
1725     default: llvm_unreachable("Invalid opcode");
1726     case X86::VPERMILPSrm:
1727     case X86::VPERMILPSYrm:
1728     case X86::VPERMILPSZ128rm:
1729     case X86::VPERMILPSZ256rm:
1730     case X86::VPERMILPSZrm:
1731       SrcIdx = 1; MaskIdx = 5; ElSize = 32; break;
1732     case X86::VPERMILPSZ128rmkz:
1733     case X86::VPERMILPSZ256rmkz:
1734     case X86::VPERMILPSZrmkz:
1735       SrcIdx = 2; MaskIdx = 6; ElSize = 32; break;
1736     case X86::VPERMILPSZ128rmk:
1737     case X86::VPERMILPSZ256rmk:
1738     case X86::VPERMILPSZrmk:
1739       SrcIdx = 3; MaskIdx = 7; ElSize = 32; break;
1740     case X86::VPERMILPDrm:
1741     case X86::VPERMILPDYrm:
1742     case X86::VPERMILPDZ128rm:
1743     case X86::VPERMILPDZ256rm:
1744     case X86::VPERMILPDZrm:
1745       SrcIdx = 1; MaskIdx = 5; ElSize = 64; break;
1746     case X86::VPERMILPDZ128rmkz:
1747     case X86::VPERMILPDZ256rmkz:
1748     case X86::VPERMILPDZrmkz:
1749       SrcIdx = 2; MaskIdx = 6; ElSize = 64; break;
1750     case X86::VPERMILPDZ128rmk:
1751     case X86::VPERMILPDZ256rmk:
1752     case X86::VPERMILPDZrmk:
1753       SrcIdx = 3; MaskIdx = 7; ElSize = 64; break;
1754     }
1755 
1756     assert(MI->getNumOperands() >= 6 &&
1757            "We should always have at least 6 operands!");
1758 
1759     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1760     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1761       SmallVector<int, 16> Mask;
1762       DecodeVPERMILPMask(C, ElSize, Mask);
1763       if (!Mask.empty())
1764         OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask),
1765                                 !EnablePrintSchedInfo);
1766     }
1767     break;
1768   }
1769 
1770   case X86::VPERMIL2PDrm:
1771   case X86::VPERMIL2PSrm:
1772   case X86::VPERMIL2PDYrm:
1773   case X86::VPERMIL2PSYrm: {
1774     if (!OutStreamer->isVerboseAsm())
1775       break;
1776     assert(MI->getNumOperands() >= 8 &&
1777            "We should always have at least 8 operands!");
1778 
1779     const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
1780     if (!CtrlOp.isImm())
1781       break;
1782 
1783     unsigned ElSize;
1784     switch (MI->getOpcode()) {
1785     default: llvm_unreachable("Invalid opcode");
1786     case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
1787     case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
1788     }
1789 
1790     const MachineOperand &MaskOp = MI->getOperand(6);
1791     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1792       SmallVector<int, 16> Mask;
1793       DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Mask);
1794       if (!Mask.empty())
1795         OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask),
1796                                 !EnablePrintSchedInfo);
1797     }
1798     break;
1799   }
1800 
1801   case X86::VPPERMrrm: {
1802     if (!OutStreamer->isVerboseAsm())
1803       break;
1804     assert(MI->getNumOperands() >= 7 &&
1805            "We should always have at least 7 operands!");
1806 
1807     const MachineOperand &MaskOp = MI->getOperand(6);
1808     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1809       SmallVector<int, 16> Mask;
1810       DecodeVPPERMMask(C, Mask);
1811       if (!Mask.empty())
1812         OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask),
1813                                 !EnablePrintSchedInfo);
1814     }
1815     break;
1816   }
1817 
1818 #define MOV_CASE(Prefix, Suffix)        \
1819   case X86::Prefix##MOVAPD##Suffix##rm: \
1820   case X86::Prefix##MOVAPS##Suffix##rm: \
1821   case X86::Prefix##MOVUPD##Suffix##rm: \
1822   case X86::Prefix##MOVUPS##Suffix##rm: \
1823   case X86::Prefix##MOVDQA##Suffix##rm: \
1824   case X86::Prefix##MOVDQU##Suffix##rm:
1825 
1826 #define MOV_AVX512_CASE(Suffix)         \
1827   case X86::VMOVDQA64##Suffix##rm:      \
1828   case X86::VMOVDQA32##Suffix##rm:      \
1829   case X86::VMOVDQU64##Suffix##rm:      \
1830   case X86::VMOVDQU32##Suffix##rm:      \
1831   case X86::VMOVDQU16##Suffix##rm:      \
1832   case X86::VMOVDQU8##Suffix##rm:       \
1833   case X86::VMOVAPS##Suffix##rm:        \
1834   case X86::VMOVAPD##Suffix##rm:        \
1835   case X86::VMOVUPS##Suffix##rm:        \
1836   case X86::VMOVUPD##Suffix##rm:
1837 
1838 #define CASE_ALL_MOV_RM()               \
1839   MOV_CASE(, )   /* SSE */              \
1840   MOV_CASE(V, )  /* AVX-128 */          \
1841   MOV_CASE(V, Y) /* AVX-256 */          \
1842   MOV_AVX512_CASE(Z)                    \
1843   MOV_AVX512_CASE(Z256)                 \
1844   MOV_AVX512_CASE(Z128)
1845 
1846   // For loads from a constant pool to a vector register, print the constant
1847   // loaded.
1848   CASE_ALL_MOV_RM()
1849   case X86::VBROADCASTF128:
1850   case X86::VBROADCASTI128:
1851   case X86::VBROADCASTF32X4Z256rm:
1852   case X86::VBROADCASTF32X4rm:
1853   case X86::VBROADCASTF32X8rm:
1854   case X86::VBROADCASTF64X2Z128rm:
1855   case X86::VBROADCASTF64X2rm:
1856   case X86::VBROADCASTF64X4rm:
1857   case X86::VBROADCASTI32X4Z256rm:
1858   case X86::VBROADCASTI32X4rm:
1859   case X86::VBROADCASTI32X8rm:
1860   case X86::VBROADCASTI64X2Z128rm:
1861   case X86::VBROADCASTI64X2rm:
1862   case X86::VBROADCASTI64X4rm:
1863     if (!OutStreamer->isVerboseAsm())
1864       break;
1865     if (MI->getNumOperands() <= 4)
1866       break;
1867     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
1868       int NumLanes = 1;
1869       // Override NumLanes for the broadcast instructions.
1870       switch (MI->getOpcode()) {
1871       case X86::VBROADCASTF128:         NumLanes = 2;  break;
1872       case X86::VBROADCASTI128:         NumLanes = 2;  break;
1873       case X86::VBROADCASTF32X4Z256rm:  NumLanes = 2;  break;
1874       case X86::VBROADCASTF32X4rm:      NumLanes = 4;  break;
1875       case X86::VBROADCASTF32X8rm:      NumLanes = 2;  break;
1876       case X86::VBROADCASTF64X2Z128rm:  NumLanes = 2;  break;
1877       case X86::VBROADCASTF64X2rm:      NumLanes = 4;  break;
1878       case X86::VBROADCASTF64X4rm:      NumLanes = 2;  break;
1879       case X86::VBROADCASTI32X4Z256rm:  NumLanes = 2;  break;
1880       case X86::VBROADCASTI32X4rm:      NumLanes = 4;  break;
1881       case X86::VBROADCASTI32X8rm:      NumLanes = 2;  break;
1882       case X86::VBROADCASTI64X2Z128rm:  NumLanes = 2;  break;
1883       case X86::VBROADCASTI64X2rm:      NumLanes = 4;  break;
1884       case X86::VBROADCASTI64X4rm:      NumLanes = 2;  break;
1885       }
1886 
1887       std::string Comment;
1888       raw_string_ostream CS(Comment);
1889       const MachineOperand &DstOp = MI->getOperand(0);
1890       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
1891       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
1892         CS << "[";
1893         for (int l = 0; l != NumLanes; ++l) {
1894           for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
1895             if (i != 0 || l != 0)
1896               CS << ",";
1897             if (CDS->getElementType()->isIntegerTy())
1898               CS << CDS->getElementAsInteger(i);
1899             else if (CDS->getElementType()->isFloatTy())
1900               CS << CDS->getElementAsFloat(i);
1901             else if (CDS->getElementType()->isDoubleTy())
1902               CS << CDS->getElementAsDouble(i);
1903             else
1904               CS << "?";
1905           }
1906         }
1907         CS << "]";
1908         OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
1909       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
1910         CS << "<";
1911         for (int l = 0; l != NumLanes; ++l) {
1912           for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
1913             if (i != 0 || l != 0)
1914               CS << ",";
1915             printConstant(CV->getOperand(i), CS);
1916           }
1917         }
1918         CS << ">";
1919         OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
1920       }
1921     }
1922     break;
1923   case X86::VBROADCASTSSrm:
1924   case X86::VBROADCASTSSYrm:
1925   case X86::VBROADCASTSSZ128m:
1926   case X86::VBROADCASTSSZ256m:
1927   case X86::VBROADCASTSSZm:
1928   case X86::VBROADCASTSDYrm:
1929   case X86::VBROADCASTSDZ256m:
1930   case X86::VBROADCASTSDZm:
1931   case X86::VPBROADCASTBrm:
1932   case X86::VPBROADCASTBYrm:
1933   case X86::VPBROADCASTBZ128m:
1934   case X86::VPBROADCASTBZ256m:
1935   case X86::VPBROADCASTBZm:
1936   case X86::VPBROADCASTDrm:
1937   case X86::VPBROADCASTDYrm:
1938   case X86::VPBROADCASTDZ128m:
1939   case X86::VPBROADCASTDZ256m:
1940   case X86::VPBROADCASTDZm:
1941   case X86::VPBROADCASTQrm:
1942   case X86::VPBROADCASTQYrm:
1943   case X86::VPBROADCASTQZ128m:
1944   case X86::VPBROADCASTQZ256m:
1945   case X86::VPBROADCASTQZm:
1946   case X86::VPBROADCASTWrm:
1947   case X86::VPBROADCASTWYrm:
1948   case X86::VPBROADCASTWZ128m:
1949   case X86::VPBROADCASTWZ256m:
1950   case X86::VPBROADCASTWZm:
1951     if (!OutStreamer->isVerboseAsm())
1952       break;
1953     if (MI->getNumOperands() <= 4)
1954       break;
1955     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
1956       int NumElts;
1957       switch (MI->getOpcode()) {
1958       default: llvm_unreachable("Invalid opcode");
1959       case X86::VBROADCASTSSrm:    NumElts = 4;  break;
1960       case X86::VBROADCASTSSYrm:   NumElts = 8;  break;
1961       case X86::VBROADCASTSSZ128m: NumElts = 4;  break;
1962       case X86::VBROADCASTSSZ256m: NumElts = 8;  break;
1963       case X86::VBROADCASTSSZm:    NumElts = 16; break;
1964       case X86::VBROADCASTSDYrm:   NumElts = 4;  break;
1965       case X86::VBROADCASTSDZ256m: NumElts = 4;  break;
1966       case X86::VBROADCASTSDZm:    NumElts = 8;  break;
1967       case X86::VPBROADCASTBrm:    NumElts = 16; break;
1968       case X86::VPBROADCASTBYrm:   NumElts = 32; break;
1969       case X86::VPBROADCASTBZ128m: NumElts = 16; break;
1970       case X86::VPBROADCASTBZ256m: NumElts = 32; break;
1971       case X86::VPBROADCASTBZm:    NumElts = 64; break;
1972       case X86::VPBROADCASTDrm:    NumElts = 4;  break;
1973       case X86::VPBROADCASTDYrm:   NumElts = 8;  break;
1974       case X86::VPBROADCASTDZ128m: NumElts = 4;  break;
1975       case X86::VPBROADCASTDZ256m: NumElts = 8;  break;
1976       case X86::VPBROADCASTDZm:    NumElts = 16; break;
1977       case X86::VPBROADCASTQrm:    NumElts = 2;  break;
1978       case X86::VPBROADCASTQYrm:   NumElts = 4;  break;
1979       case X86::VPBROADCASTQZ128m: NumElts = 2;  break;
1980       case X86::VPBROADCASTQZ256m: NumElts = 4;  break;
1981       case X86::VPBROADCASTQZm:    NumElts = 8;  break;
1982       case X86::VPBROADCASTWrm:    NumElts = 8;  break;
1983       case X86::VPBROADCASTWYrm:   NumElts = 16; break;
1984       case X86::VPBROADCASTWZ128m: NumElts = 8;  break;
1985       case X86::VPBROADCASTWZ256m: NumElts = 16; break;
1986       case X86::VPBROADCASTWZm:    NumElts = 32; break;
1987       }
1988 
1989       std::string Comment;
1990       raw_string_ostream CS(Comment);
1991       const MachineOperand &DstOp = MI->getOperand(0);
1992       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
1993       CS << "[";
1994       for (int i = 0; i != NumElts; ++i) {
1995         if (i != 0)
1996           CS << ",";
1997         printConstant(C, CS);
1998       }
1999       CS << "]";
2000       OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
2001     }
2002   }
2003 
2004   MCInst TmpInst;
2005   MCInstLowering.Lower(MI, TmpInst);
2006 
2007   // Stackmap shadows cannot include branch targets, so we can count the bytes
2008   // in a call towards the shadow, but must ensure that the no thread returns
2009   // in to the stackmap shadow.  The only way to achieve this is if the call
2010   // is at the end of the shadow.
2011   if (MI->isCall()) {
2012     // Count then size of the call towards the shadow
2013     SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
2014     // Then flush the shadow so that we fill with nops before the call, not
2015     // after it.
2016     SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
2017     // Then emit the call
2018     OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
2019     return;
2020   }
2021 
2022   EmitAndCountInstruction(TmpInst);
2023 }
2024