1 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains code to lower X86 MachineInstrs to their corresponding
10 // MCInst records.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/X86ATTInstPrinter.h"
15 #include "MCTargetDesc/X86BaseInfo.h"
16 #include "MCTargetDesc/X86InstComments.h"
17 #include "MCTargetDesc/X86TargetStreamer.h"
18 #include "Utils/X86ShuffleDecode.h"
19 #include "X86AsmPrinter.h"
20 #include "X86RegisterInfo.h"
21 #include "X86ShuffleDecodeConstantPool.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/StackMaps.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCCodeEmitter.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCFixup.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCInstBuilder.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCSectionELF.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCSymbolELF.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 
47 using namespace llvm;
48 
49 namespace {
50 
51 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
52 class X86MCInstLower {
53   MCContext &Ctx;
54   const MachineFunction &MF;
55   const TargetMachine &TM;
56   const MCAsmInfo &MAI;
57   X86AsmPrinter &AsmPrinter;
58 
59 public:
60   X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
61 
62   Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
63                                           const MachineOperand &MO) const;
64   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
65 
66   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
67   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
68 
69 private:
70   MachineModuleInfoMachO &getMachOMMI() const;
71 };
72 
73 } // end anonymous namespace
74 
75 // Emit a minimal sequence of nops spanning NumBytes bytes.
76 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
77                      const MCSubtargetInfo &STI);
78 
79 void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
80                                                  const MCSubtargetInfo &STI,
81                                                  MCCodeEmitter *CodeEmitter) {
82   if (InShadow) {
83     SmallString<256> Code;
84     SmallVector<MCFixup, 4> Fixups;
85     raw_svector_ostream VecOS(Code);
86     CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
87     CurrentShadowSize += Code.size();
88     if (CurrentShadowSize >= RequiredShadowSize)
89       InShadow = false; // The shadow is big enough. Stop counting.
90   }
91 }
92 
93 void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
94     MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
95   if (InShadow && CurrentShadowSize < RequiredShadowSize) {
96     InShadow = false;
97     EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
98              MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
99   }
100 }
101 
102 void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
103   OutStreamer->EmitInstruction(Inst, getSubtargetInfo());
104   SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
105 }
106 
107 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
108                                X86AsmPrinter &asmprinter)
109     : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
110       AsmPrinter(asmprinter) {}
111 
112 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
113   return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
114 }
115 
116 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
117 /// operand to an MCSymbol.
118 MCSymbol *X86MCInstLower::GetSymbolFromOperand(const MachineOperand &MO) const {
119   const DataLayout &DL = MF.getDataLayout();
120   assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) &&
121          "Isn't a symbol reference");
122 
123   MCSymbol *Sym = nullptr;
124   SmallString<128> Name;
125   StringRef Suffix;
126 
127   switch (MO.getTargetFlags()) {
128   case X86II::MO_DLLIMPORT:
129     // Handle dllimport linkage.
130     Name += "__imp_";
131     break;
132   case X86II::MO_COFFSTUB:
133     Name += ".refptr.";
134     break;
135   case X86II::MO_DARWIN_NONLAZY:
136   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
137     Suffix = "$non_lazy_ptr";
138     break;
139   }
140 
141   if (!Suffix.empty())
142     Name += DL.getPrivateGlobalPrefix();
143 
144   if (MO.isGlobal()) {
145     const GlobalValue *GV = MO.getGlobal();
146     AsmPrinter.getNameWithPrefix(Name, GV);
147   } else if (MO.isSymbol()) {
148     Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
149   } else if (MO.isMBB()) {
150     assert(Suffix.empty());
151     Sym = MO.getMBB()->getSymbol();
152   }
153 
154   Name += Suffix;
155   if (!Sym)
156     Sym = Ctx.getOrCreateSymbol(Name);
157 
158   // If the target flags on the operand changes the name of the symbol, do that
159   // before we return the symbol.
160   switch (MO.getTargetFlags()) {
161   default:
162     break;
163   case X86II::MO_COFFSTUB: {
164     MachineModuleInfoCOFF &MMICOFF =
165         MF.getMMI().getObjFileInfo<MachineModuleInfoCOFF>();
166     MachineModuleInfoImpl::StubValueTy &StubSym = MMICOFF.getGVStubEntry(Sym);
167     if (!StubSym.getPointer()) {
168       assert(MO.isGlobal() && "Extern symbol not handled yet");
169       StubSym = MachineModuleInfoImpl::StubValueTy(
170           AsmPrinter.getSymbol(MO.getGlobal()), true);
171     }
172     break;
173   }
174   case X86II::MO_DARWIN_NONLAZY:
175   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
176     MachineModuleInfoImpl::StubValueTy &StubSym =
177         getMachOMMI().getGVStubEntry(Sym);
178     if (!StubSym.getPointer()) {
179       assert(MO.isGlobal() && "Extern symbol not handled yet");
180       StubSym = MachineModuleInfoImpl::StubValueTy(
181           AsmPrinter.getSymbol(MO.getGlobal()),
182           !MO.getGlobal()->hasInternalLinkage());
183     }
184     break;
185   }
186   }
187 
188   return Sym;
189 }
190 
191 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
192                                              MCSymbol *Sym) const {
193   // FIXME: We would like an efficient form for this, so we don't have to do a
194   // lot of extra uniquing.
195   const MCExpr *Expr = nullptr;
196   MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
197 
198   switch (MO.getTargetFlags()) {
199   default:
200     llvm_unreachable("Unknown target flag on GV operand");
201   case X86II::MO_NO_FLAG: // No flag.
202   // These affect the name of the symbol, not any suffix.
203   case X86II::MO_DARWIN_NONLAZY:
204   case X86II::MO_DLLIMPORT:
205   case X86II::MO_COFFSTUB:
206     break;
207 
208   case X86II::MO_TLVP:
209     RefKind = MCSymbolRefExpr::VK_TLVP;
210     break;
211   case X86II::MO_TLVP_PIC_BASE:
212     Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
213     // Subtract the pic base.
214     Expr = MCBinaryExpr::createSub(
215         Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
216     break;
217   case X86II::MO_SECREL:
218     RefKind = MCSymbolRefExpr::VK_SECREL;
219     break;
220   case X86II::MO_TLSGD:
221     RefKind = MCSymbolRefExpr::VK_TLSGD;
222     break;
223   case X86II::MO_TLSLD:
224     RefKind = MCSymbolRefExpr::VK_TLSLD;
225     break;
226   case X86II::MO_TLSLDM:
227     RefKind = MCSymbolRefExpr::VK_TLSLDM;
228     break;
229   case X86II::MO_GOTTPOFF:
230     RefKind = MCSymbolRefExpr::VK_GOTTPOFF;
231     break;
232   case X86II::MO_INDNTPOFF:
233     RefKind = MCSymbolRefExpr::VK_INDNTPOFF;
234     break;
235   case X86II::MO_TPOFF:
236     RefKind = MCSymbolRefExpr::VK_TPOFF;
237     break;
238   case X86II::MO_DTPOFF:
239     RefKind = MCSymbolRefExpr::VK_DTPOFF;
240     break;
241   case X86II::MO_NTPOFF:
242     RefKind = MCSymbolRefExpr::VK_NTPOFF;
243     break;
244   case X86II::MO_GOTNTPOFF:
245     RefKind = MCSymbolRefExpr::VK_GOTNTPOFF;
246     break;
247   case X86II::MO_GOTPCREL:
248     RefKind = MCSymbolRefExpr::VK_GOTPCREL;
249     break;
250   case X86II::MO_GOT:
251     RefKind = MCSymbolRefExpr::VK_GOT;
252     break;
253   case X86II::MO_GOTOFF:
254     RefKind = MCSymbolRefExpr::VK_GOTOFF;
255     break;
256   case X86II::MO_PLT:
257     RefKind = MCSymbolRefExpr::VK_PLT;
258     break;
259   case X86II::MO_ABS8:
260     RefKind = MCSymbolRefExpr::VK_X86_ABS8;
261     break;
262   case X86II::MO_PIC_BASE_OFFSET:
263   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
264     Expr = MCSymbolRefExpr::create(Sym, Ctx);
265     // Subtract the pic base.
266     Expr = MCBinaryExpr::createSub(
267         Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
268     if (MO.isJTI()) {
269       assert(MAI.doesSetDirectiveSuppressReloc());
270       // If .set directive is supported, use it to reduce the number of
271       // relocations the assembler will generate for differences between
272       // local labels. This is only safe when the symbols are in the same
273       // section so we are restricting it to jumptable references.
274       MCSymbol *Label = Ctx.createTempSymbol();
275       AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
276       Expr = MCSymbolRefExpr::create(Label, Ctx);
277     }
278     break;
279   }
280 
281   if (!Expr)
282     Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
283 
284   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
285     Expr = MCBinaryExpr::createAdd(
286         Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
287   return MCOperand::createExpr(Expr);
288 }
289 
290 /// Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
291 /// a short fixed-register form.
292 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
293   unsigned ImmOp = Inst.getNumOperands() - 1;
294   assert(Inst.getOperand(0).isReg() &&
295          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
296          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
297            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
298           Inst.getNumOperands() == 2) &&
299          "Unexpected instruction!");
300 
301   // Check whether the destination register can be fixed.
302   unsigned Reg = Inst.getOperand(0).getReg();
303   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
304     return;
305 
306   // If so, rewrite the instruction.
307   MCOperand Saved = Inst.getOperand(ImmOp);
308   Inst = MCInst();
309   Inst.setOpcode(Opcode);
310   Inst.addOperand(Saved);
311 }
312 
313 /// If a movsx instruction has a shorter encoding for the used register
314 /// simplify the instruction to use it instead.
315 static void SimplifyMOVSX(MCInst &Inst) {
316   unsigned NewOpcode = 0;
317   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
318   switch (Inst.getOpcode()) {
319   default:
320     llvm_unreachable("Unexpected instruction!");
321   case X86::MOVSX16rr8: // movsbw %al, %ax   --> cbtw
322     if (Op0 == X86::AX && Op1 == X86::AL)
323       NewOpcode = X86::CBW;
324     break;
325   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
326     if (Op0 == X86::EAX && Op1 == X86::AX)
327       NewOpcode = X86::CWDE;
328     break;
329   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
330     if (Op0 == X86::RAX && Op1 == X86::EAX)
331       NewOpcode = X86::CDQE;
332     break;
333   }
334 
335   if (NewOpcode != 0) {
336     Inst = MCInst();
337     Inst.setOpcode(NewOpcode);
338   }
339 }
340 
341 /// Simplify things like MOV32rm to MOV32o32a.
342 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
343                                   unsigned Opcode) {
344   // Don't make these simplifications in 64-bit mode; other assemblers don't
345   // perform them because they make the code larger.
346   if (Printer.getSubtarget().is64Bit())
347     return;
348 
349   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
350   unsigned AddrBase = IsStore;
351   unsigned RegOp = IsStore ? 0 : 5;
352   unsigned AddrOp = AddrBase + 3;
353   assert(
354       Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
355       Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
356       Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
357       Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
358       Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
359       (Inst.getOperand(AddrOp).isExpr() || Inst.getOperand(AddrOp).isImm()) &&
360       "Unexpected instruction!");
361 
362   // Check whether the destination register can be fixed.
363   unsigned Reg = Inst.getOperand(RegOp).getReg();
364   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
365     return;
366 
367   // Check whether this is an absolute address.
368   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
369   // to do this here.
370   bool Absolute = true;
371   if (Inst.getOperand(AddrOp).isExpr()) {
372     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
373     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
374       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
375         Absolute = false;
376   }
377 
378   if (Absolute &&
379       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
380        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
381        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
382     return;
383 
384   // If so, rewrite the instruction.
385   MCOperand Saved = Inst.getOperand(AddrOp);
386   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
387   Inst = MCInst();
388   Inst.setOpcode(Opcode);
389   Inst.addOperand(Saved);
390   Inst.addOperand(Seg);
391 }
392 
393 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
394   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
395 }
396 
397 Optional<MCOperand>
398 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
399                                     const MachineOperand &MO) const {
400   switch (MO.getType()) {
401   default:
402     MI->print(errs());
403     llvm_unreachable("unknown operand type");
404   case MachineOperand::MO_Register:
405     // Ignore all implicit register operands.
406     if (MO.isImplicit())
407       return None;
408     return MCOperand::createReg(MO.getReg());
409   case MachineOperand::MO_Immediate:
410     return MCOperand::createImm(MO.getImm());
411   case MachineOperand::MO_MachineBasicBlock:
412   case MachineOperand::MO_GlobalAddress:
413   case MachineOperand::MO_ExternalSymbol:
414     return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
415   case MachineOperand::MO_MCSymbol:
416     return LowerSymbolOperand(MO, MO.getMCSymbol());
417   case MachineOperand::MO_JumpTableIndex:
418     return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
419   case MachineOperand::MO_ConstantPoolIndex:
420     return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
421   case MachineOperand::MO_BlockAddress:
422     return LowerSymbolOperand(
423         MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
424   case MachineOperand::MO_RegisterMask:
425     // Ignore call clobbers.
426     return None;
427   }
428 }
429 
430 // Replace TAILJMP opcodes with their equivalent opcodes that have encoding
431 // information.
432 static unsigned convertTailJumpOpcode(unsigned Opcode) {
433   switch (Opcode) {
434   case X86::TAILJMPr:
435     Opcode = X86::JMP32r;
436     break;
437   case X86::TAILJMPm:
438     Opcode = X86::JMP32m;
439     break;
440   case X86::TAILJMPr64:
441     Opcode = X86::JMP64r;
442     break;
443   case X86::TAILJMPm64:
444     Opcode = X86::JMP64m;
445     break;
446   case X86::TAILJMPr64_REX:
447     Opcode = X86::JMP64r_REX;
448     break;
449   case X86::TAILJMPm64_REX:
450     Opcode = X86::JMP64m_REX;
451     break;
452   case X86::TAILJMPd:
453   case X86::TAILJMPd64:
454     Opcode = X86::JMP_1;
455     break;
456   case X86::TAILJMPd_CC:
457   case X86::TAILJMPd64_CC:
458     Opcode = X86::JCC_1;
459     break;
460   }
461 
462   return Opcode;
463 }
464 
465 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
466   OutMI.setOpcode(MI->getOpcode());
467 
468   for (const MachineOperand &MO : MI->operands())
469     if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
470       OutMI.addOperand(MaybeMCOp.getValue());
471 
472   // Handle a few special cases to eliminate operand modifiers.
473   switch (OutMI.getOpcode()) {
474   case X86::LEA64_32r:
475   case X86::LEA64r:
476   case X86::LEA16r:
477   case X86::LEA32r:
478     // LEA should have a segment register, but it must be empty.
479     assert(OutMI.getNumOperands() == 1 + X86::AddrNumOperands &&
480            "Unexpected # of LEA operands");
481     assert(OutMI.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
482            "LEA has segment specified!");
483     break;
484 
485   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
486   // if one of the registers is extended, but other isn't.
487   case X86::VMOVZPQILo2PQIrr:
488   case X86::VMOVAPDrr:
489   case X86::VMOVAPDYrr:
490   case X86::VMOVAPSrr:
491   case X86::VMOVAPSYrr:
492   case X86::VMOVDQArr:
493   case X86::VMOVDQAYrr:
494   case X86::VMOVDQUrr:
495   case X86::VMOVDQUYrr:
496   case X86::VMOVUPDrr:
497   case X86::VMOVUPDYrr:
498   case X86::VMOVUPSrr:
499   case X86::VMOVUPSYrr: {
500     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
501         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
502       unsigned NewOpc;
503       switch (OutMI.getOpcode()) {
504       default: llvm_unreachable("Invalid opcode");
505       case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr;   break;
506       case X86::VMOVAPDrr:        NewOpc = X86::VMOVAPDrr_REV;  break;
507       case X86::VMOVAPDYrr:       NewOpc = X86::VMOVAPDYrr_REV; break;
508       case X86::VMOVAPSrr:        NewOpc = X86::VMOVAPSrr_REV;  break;
509       case X86::VMOVAPSYrr:       NewOpc = X86::VMOVAPSYrr_REV; break;
510       case X86::VMOVDQArr:        NewOpc = X86::VMOVDQArr_REV;  break;
511       case X86::VMOVDQAYrr:       NewOpc = X86::VMOVDQAYrr_REV; break;
512       case X86::VMOVDQUrr:        NewOpc = X86::VMOVDQUrr_REV;  break;
513       case X86::VMOVDQUYrr:       NewOpc = X86::VMOVDQUYrr_REV; break;
514       case X86::VMOVUPDrr:        NewOpc = X86::VMOVUPDrr_REV;  break;
515       case X86::VMOVUPDYrr:       NewOpc = X86::VMOVUPDYrr_REV; break;
516       case X86::VMOVUPSrr:        NewOpc = X86::VMOVUPSrr_REV;  break;
517       case X86::VMOVUPSYrr:       NewOpc = X86::VMOVUPSYrr_REV; break;
518       }
519       OutMI.setOpcode(NewOpc);
520     }
521     break;
522   }
523   case X86::VMOVSDrr:
524   case X86::VMOVSSrr: {
525     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
526         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
527       unsigned NewOpc;
528       switch (OutMI.getOpcode()) {
529       default: llvm_unreachable("Invalid opcode");
530       case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
531       case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
532       }
533       OutMI.setOpcode(NewOpc);
534     }
535     break;
536   }
537 
538   case X86::VPCMPBZ128rmi:  case X86::VPCMPBZ128rmik:
539   case X86::VPCMPBZ128rri:  case X86::VPCMPBZ128rrik:
540   case X86::VPCMPBZ256rmi:  case X86::VPCMPBZ256rmik:
541   case X86::VPCMPBZ256rri:  case X86::VPCMPBZ256rrik:
542   case X86::VPCMPBZrmi:     case X86::VPCMPBZrmik:
543   case X86::VPCMPBZrri:     case X86::VPCMPBZrrik:
544   case X86::VPCMPDZ128rmi:  case X86::VPCMPDZ128rmik:
545   case X86::VPCMPDZ128rmib: case X86::VPCMPDZ128rmibk:
546   case X86::VPCMPDZ128rri:  case X86::VPCMPDZ128rrik:
547   case X86::VPCMPDZ256rmi:  case X86::VPCMPDZ256rmik:
548   case X86::VPCMPDZ256rmib: case X86::VPCMPDZ256rmibk:
549   case X86::VPCMPDZ256rri:  case X86::VPCMPDZ256rrik:
550   case X86::VPCMPDZrmi:     case X86::VPCMPDZrmik:
551   case X86::VPCMPDZrmib:    case X86::VPCMPDZrmibk:
552   case X86::VPCMPDZrri:     case X86::VPCMPDZrrik:
553   case X86::VPCMPQZ128rmi:  case X86::VPCMPQZ128rmik:
554   case X86::VPCMPQZ128rmib: case X86::VPCMPQZ128rmibk:
555   case X86::VPCMPQZ128rri:  case X86::VPCMPQZ128rrik:
556   case X86::VPCMPQZ256rmi:  case X86::VPCMPQZ256rmik:
557   case X86::VPCMPQZ256rmib: case X86::VPCMPQZ256rmibk:
558   case X86::VPCMPQZ256rri:  case X86::VPCMPQZ256rrik:
559   case X86::VPCMPQZrmi:     case X86::VPCMPQZrmik:
560   case X86::VPCMPQZrmib:    case X86::VPCMPQZrmibk:
561   case X86::VPCMPQZrri:     case X86::VPCMPQZrrik:
562   case X86::VPCMPWZ128rmi:  case X86::VPCMPWZ128rmik:
563   case X86::VPCMPWZ128rri:  case X86::VPCMPWZ128rrik:
564   case X86::VPCMPWZ256rmi:  case X86::VPCMPWZ256rmik:
565   case X86::VPCMPWZ256rri:  case X86::VPCMPWZ256rrik:
566   case X86::VPCMPWZrmi:     case X86::VPCMPWZrmik:
567   case X86::VPCMPWZrri:     case X86::VPCMPWZrrik: {
568     // Turn immediate 0 into the VPCMPEQ instruction.
569     if (OutMI.getOperand(OutMI.getNumOperands() - 1).getImm() == 0) {
570       unsigned NewOpc;
571       switch (OutMI.getOpcode()) {
572       case X86::VPCMPBZ128rmi:   NewOpc = X86::VPCMPEQBZ128rm;   break;
573       case X86::VPCMPBZ128rmik:  NewOpc = X86::VPCMPEQBZ128rmk;  break;
574       case X86::VPCMPBZ128rri:   NewOpc = X86::VPCMPEQBZ128rr;   break;
575       case X86::VPCMPBZ128rrik:  NewOpc = X86::VPCMPEQBZ128rrk;  break;
576       case X86::VPCMPBZ256rmi:   NewOpc = X86::VPCMPEQBZ256rm;   break;
577       case X86::VPCMPBZ256rmik:  NewOpc = X86::VPCMPEQBZ256rmk;  break;
578       case X86::VPCMPBZ256rri:   NewOpc = X86::VPCMPEQBZ256rr;   break;
579       case X86::VPCMPBZ256rrik:  NewOpc = X86::VPCMPEQBZ256rrk;  break;
580       case X86::VPCMPBZrmi:      NewOpc = X86::VPCMPEQBZrm;      break;
581       case X86::VPCMPBZrmik:     NewOpc = X86::VPCMPEQBZrmk;     break;
582       case X86::VPCMPBZrri:      NewOpc = X86::VPCMPEQBZrr;      break;
583       case X86::VPCMPBZrrik:     NewOpc = X86::VPCMPEQBZrrk;     break;
584       case X86::VPCMPDZ128rmi:   NewOpc = X86::VPCMPEQDZ128rm;   break;
585       case X86::VPCMPDZ128rmib:  NewOpc = X86::VPCMPEQDZ128rmb;  break;
586       case X86::VPCMPDZ128rmibk: NewOpc = X86::VPCMPEQDZ128rmbk; break;
587       case X86::VPCMPDZ128rmik:  NewOpc = X86::VPCMPEQDZ128rmk;  break;
588       case X86::VPCMPDZ128rri:   NewOpc = X86::VPCMPEQDZ128rr;   break;
589       case X86::VPCMPDZ128rrik:  NewOpc = X86::VPCMPEQDZ128rrk;  break;
590       case X86::VPCMPDZ256rmi:   NewOpc = X86::VPCMPEQDZ256rm;   break;
591       case X86::VPCMPDZ256rmib:  NewOpc = X86::VPCMPEQDZ256rmb;  break;
592       case X86::VPCMPDZ256rmibk: NewOpc = X86::VPCMPEQDZ256rmbk; break;
593       case X86::VPCMPDZ256rmik:  NewOpc = X86::VPCMPEQDZ256rmk;  break;
594       case X86::VPCMPDZ256rri:   NewOpc = X86::VPCMPEQDZ256rr;   break;
595       case X86::VPCMPDZ256rrik:  NewOpc = X86::VPCMPEQDZ256rrk;  break;
596       case X86::VPCMPDZrmi:      NewOpc = X86::VPCMPEQDZrm;      break;
597       case X86::VPCMPDZrmib:     NewOpc = X86::VPCMPEQDZrmb;     break;
598       case X86::VPCMPDZrmibk:    NewOpc = X86::VPCMPEQDZrmbk;    break;
599       case X86::VPCMPDZrmik:     NewOpc = X86::VPCMPEQDZrmk;     break;
600       case X86::VPCMPDZrri:      NewOpc = X86::VPCMPEQDZrr;      break;
601       case X86::VPCMPDZrrik:     NewOpc = X86::VPCMPEQDZrrk;     break;
602       case X86::VPCMPQZ128rmi:   NewOpc = X86::VPCMPEQQZ128rm;   break;
603       case X86::VPCMPQZ128rmib:  NewOpc = X86::VPCMPEQQZ128rmb;  break;
604       case X86::VPCMPQZ128rmibk: NewOpc = X86::VPCMPEQQZ128rmbk; break;
605       case X86::VPCMPQZ128rmik:  NewOpc = X86::VPCMPEQQZ128rmk;  break;
606       case X86::VPCMPQZ128rri:   NewOpc = X86::VPCMPEQQZ128rr;   break;
607       case X86::VPCMPQZ128rrik:  NewOpc = X86::VPCMPEQQZ128rrk;  break;
608       case X86::VPCMPQZ256rmi:   NewOpc = X86::VPCMPEQQZ256rm;   break;
609       case X86::VPCMPQZ256rmib:  NewOpc = X86::VPCMPEQQZ256rmb;  break;
610       case X86::VPCMPQZ256rmibk: NewOpc = X86::VPCMPEQQZ256rmbk; break;
611       case X86::VPCMPQZ256rmik:  NewOpc = X86::VPCMPEQQZ256rmk;  break;
612       case X86::VPCMPQZ256rri:   NewOpc = X86::VPCMPEQQZ256rr;   break;
613       case X86::VPCMPQZ256rrik:  NewOpc = X86::VPCMPEQQZ256rrk;  break;
614       case X86::VPCMPQZrmi:      NewOpc = X86::VPCMPEQQZrm;      break;
615       case X86::VPCMPQZrmib:     NewOpc = X86::VPCMPEQQZrmb;     break;
616       case X86::VPCMPQZrmibk:    NewOpc = X86::VPCMPEQQZrmbk;    break;
617       case X86::VPCMPQZrmik:     NewOpc = X86::VPCMPEQQZrmk;     break;
618       case X86::VPCMPQZrri:      NewOpc = X86::VPCMPEQQZrr;      break;
619       case X86::VPCMPQZrrik:     NewOpc = X86::VPCMPEQQZrrk;     break;
620       case X86::VPCMPWZ128rmi:   NewOpc = X86::VPCMPEQWZ128rm;   break;
621       case X86::VPCMPWZ128rmik:  NewOpc = X86::VPCMPEQWZ128rmk;  break;
622       case X86::VPCMPWZ128rri:   NewOpc = X86::VPCMPEQWZ128rr;   break;
623       case X86::VPCMPWZ128rrik:  NewOpc = X86::VPCMPEQWZ128rrk;  break;
624       case X86::VPCMPWZ256rmi:   NewOpc = X86::VPCMPEQWZ256rm;   break;
625       case X86::VPCMPWZ256rmik:  NewOpc = X86::VPCMPEQWZ256rmk;  break;
626       case X86::VPCMPWZ256rri:   NewOpc = X86::VPCMPEQWZ256rr;   break;
627       case X86::VPCMPWZ256rrik:  NewOpc = X86::VPCMPEQWZ256rrk;  break;
628       case X86::VPCMPWZrmi:      NewOpc = X86::VPCMPEQWZrm;      break;
629       case X86::VPCMPWZrmik:     NewOpc = X86::VPCMPEQWZrmk;     break;
630       case X86::VPCMPWZrri:      NewOpc = X86::VPCMPEQWZrr;      break;
631       case X86::VPCMPWZrrik:     NewOpc = X86::VPCMPEQWZrrk;     break;
632       }
633 
634       OutMI.setOpcode(NewOpc);
635       OutMI.erase(&OutMI.getOperand(OutMI.getNumOperands() - 1));
636       break;
637     }
638 
639     // Turn immediate 6 into the VPCMPGT instruction.
640     if (OutMI.getOperand(OutMI.getNumOperands() - 1).getImm() == 6) {
641       unsigned NewOpc;
642       switch (OutMI.getOpcode()) {
643       case X86::VPCMPBZ128rmi:   NewOpc = X86::VPCMPGTBZ128rm;   break;
644       case X86::VPCMPBZ128rmik:  NewOpc = X86::VPCMPGTBZ128rmk;  break;
645       case X86::VPCMPBZ128rri:   NewOpc = X86::VPCMPGTBZ128rr;   break;
646       case X86::VPCMPBZ128rrik:  NewOpc = X86::VPCMPGTBZ128rrk;  break;
647       case X86::VPCMPBZ256rmi:   NewOpc = X86::VPCMPGTBZ256rm;   break;
648       case X86::VPCMPBZ256rmik:  NewOpc = X86::VPCMPGTBZ256rmk;  break;
649       case X86::VPCMPBZ256rri:   NewOpc = X86::VPCMPGTBZ256rr;   break;
650       case X86::VPCMPBZ256rrik:  NewOpc = X86::VPCMPGTBZ256rrk;  break;
651       case X86::VPCMPBZrmi:      NewOpc = X86::VPCMPGTBZrm;      break;
652       case X86::VPCMPBZrmik:     NewOpc = X86::VPCMPGTBZrmk;     break;
653       case X86::VPCMPBZrri:      NewOpc = X86::VPCMPGTBZrr;      break;
654       case X86::VPCMPBZrrik:     NewOpc = X86::VPCMPGTBZrrk;     break;
655       case X86::VPCMPDZ128rmi:   NewOpc = X86::VPCMPGTDZ128rm;   break;
656       case X86::VPCMPDZ128rmib:  NewOpc = X86::VPCMPGTDZ128rmb;  break;
657       case X86::VPCMPDZ128rmibk: NewOpc = X86::VPCMPGTDZ128rmbk; break;
658       case X86::VPCMPDZ128rmik:  NewOpc = X86::VPCMPGTDZ128rmk;  break;
659       case X86::VPCMPDZ128rri:   NewOpc = X86::VPCMPGTDZ128rr;   break;
660       case X86::VPCMPDZ128rrik:  NewOpc = X86::VPCMPGTDZ128rrk;  break;
661       case X86::VPCMPDZ256rmi:   NewOpc = X86::VPCMPGTDZ256rm;   break;
662       case X86::VPCMPDZ256rmib:  NewOpc = X86::VPCMPGTDZ256rmb;  break;
663       case X86::VPCMPDZ256rmibk: NewOpc = X86::VPCMPGTDZ256rmbk; break;
664       case X86::VPCMPDZ256rmik:  NewOpc = X86::VPCMPGTDZ256rmk;  break;
665       case X86::VPCMPDZ256rri:   NewOpc = X86::VPCMPGTDZ256rr;   break;
666       case X86::VPCMPDZ256rrik:  NewOpc = X86::VPCMPGTDZ256rrk;  break;
667       case X86::VPCMPDZrmi:      NewOpc = X86::VPCMPGTDZrm;      break;
668       case X86::VPCMPDZrmib:     NewOpc = X86::VPCMPGTDZrmb;     break;
669       case X86::VPCMPDZrmibk:    NewOpc = X86::VPCMPGTDZrmbk;    break;
670       case X86::VPCMPDZrmik:     NewOpc = X86::VPCMPGTDZrmk;     break;
671       case X86::VPCMPDZrri:      NewOpc = X86::VPCMPGTDZrr;      break;
672       case X86::VPCMPDZrrik:     NewOpc = X86::VPCMPGTDZrrk;     break;
673       case X86::VPCMPQZ128rmi:   NewOpc = X86::VPCMPGTQZ128rm;   break;
674       case X86::VPCMPQZ128rmib:  NewOpc = X86::VPCMPGTQZ128rmb;  break;
675       case X86::VPCMPQZ128rmibk: NewOpc = X86::VPCMPGTQZ128rmbk; break;
676       case X86::VPCMPQZ128rmik:  NewOpc = X86::VPCMPGTQZ128rmk;  break;
677       case X86::VPCMPQZ128rri:   NewOpc = X86::VPCMPGTQZ128rr;   break;
678       case X86::VPCMPQZ128rrik:  NewOpc = X86::VPCMPGTQZ128rrk;  break;
679       case X86::VPCMPQZ256rmi:   NewOpc = X86::VPCMPGTQZ256rm;   break;
680       case X86::VPCMPQZ256rmib:  NewOpc = X86::VPCMPGTQZ256rmb;  break;
681       case X86::VPCMPQZ256rmibk: NewOpc = X86::VPCMPGTQZ256rmbk; break;
682       case X86::VPCMPQZ256rmik:  NewOpc = X86::VPCMPGTQZ256rmk;  break;
683       case X86::VPCMPQZ256rri:   NewOpc = X86::VPCMPGTQZ256rr;   break;
684       case X86::VPCMPQZ256rrik:  NewOpc = X86::VPCMPGTQZ256rrk;  break;
685       case X86::VPCMPQZrmi:      NewOpc = X86::VPCMPGTQZrm;      break;
686       case X86::VPCMPQZrmib:     NewOpc = X86::VPCMPGTQZrmb;     break;
687       case X86::VPCMPQZrmibk:    NewOpc = X86::VPCMPGTQZrmbk;    break;
688       case X86::VPCMPQZrmik:     NewOpc = X86::VPCMPGTQZrmk;     break;
689       case X86::VPCMPQZrri:      NewOpc = X86::VPCMPGTQZrr;      break;
690       case X86::VPCMPQZrrik:     NewOpc = X86::VPCMPGTQZrrk;     break;
691       case X86::VPCMPWZ128rmi:   NewOpc = X86::VPCMPGTWZ128rm;   break;
692       case X86::VPCMPWZ128rmik:  NewOpc = X86::VPCMPGTWZ128rmk;  break;
693       case X86::VPCMPWZ128rri:   NewOpc = X86::VPCMPGTWZ128rr;   break;
694       case X86::VPCMPWZ128rrik:  NewOpc = X86::VPCMPGTWZ128rrk;  break;
695       case X86::VPCMPWZ256rmi:   NewOpc = X86::VPCMPGTWZ256rm;   break;
696       case X86::VPCMPWZ256rmik:  NewOpc = X86::VPCMPGTWZ256rmk;  break;
697       case X86::VPCMPWZ256rri:   NewOpc = X86::VPCMPGTWZ256rr;   break;
698       case X86::VPCMPWZ256rrik:  NewOpc = X86::VPCMPGTWZ256rrk;  break;
699       case X86::VPCMPWZrmi:      NewOpc = X86::VPCMPGTWZrm;      break;
700       case X86::VPCMPWZrmik:     NewOpc = X86::VPCMPGTWZrmk;     break;
701       case X86::VPCMPWZrri:      NewOpc = X86::VPCMPGTWZrr;      break;
702       case X86::VPCMPWZrrik:     NewOpc = X86::VPCMPGTWZrrk;     break;
703       }
704 
705       OutMI.setOpcode(NewOpc);
706       OutMI.erase(&OutMI.getOperand(OutMI.getNumOperands() - 1));
707       break;
708     }
709 
710     break;
711   }
712 
713   // CALL64r, CALL64pcrel32 - These instructions used to have
714   // register inputs modeled as normal uses instead of implicit uses.  As such,
715   // they we used to truncate off all but the first operand (the callee). This
716   // issue seems to have been fixed at some point. This assert verifies that.
717   case X86::CALL64r:
718   case X86::CALL64pcrel32:
719     assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
720     break;
721 
722   case X86::EH_RETURN:
723   case X86::EH_RETURN64: {
724     OutMI = MCInst();
725     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
726     break;
727   }
728 
729   case X86::CLEANUPRET: {
730     // Replace CLEANUPRET with the appropriate RET.
731     OutMI = MCInst();
732     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
733     break;
734   }
735 
736   case X86::CATCHRET: {
737     // Replace CATCHRET with the appropriate RET.
738     const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
739     unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
740     OutMI = MCInst();
741     OutMI.setOpcode(getRetOpcode(Subtarget));
742     OutMI.addOperand(MCOperand::createReg(ReturnReg));
743     break;
744   }
745 
746   // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump
747   // instruction.
748   case X86::TAILJMPr:
749   case X86::TAILJMPr64:
750   case X86::TAILJMPr64_REX:
751   case X86::TAILJMPd:
752   case X86::TAILJMPd64:
753     assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
754     OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
755     break;
756 
757   case X86::TAILJMPd_CC:
758   case X86::TAILJMPd64_CC:
759     assert(OutMI.getNumOperands() == 2 && "Unexpected number of operands!");
760     OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
761     break;
762 
763   case X86::TAILJMPm:
764   case X86::TAILJMPm64:
765   case X86::TAILJMPm64_REX:
766     assert(OutMI.getNumOperands() == X86::AddrNumOperands &&
767            "Unexpected number of operands!");
768     OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
769     break;
770 
771   case X86::DEC16r:
772   case X86::DEC32r:
773   case X86::INC16r:
774   case X86::INC32r:
775     // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
776     if (!AsmPrinter.getSubtarget().is64Bit()) {
777       unsigned Opcode;
778       switch (OutMI.getOpcode()) {
779       default: llvm_unreachable("Invalid opcode");
780       case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
781       case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
782       case X86::INC16r: Opcode = X86::INC16r_alt; break;
783       case X86::INC32r: Opcode = X86::INC32r_alt; break;
784       }
785       OutMI.setOpcode(Opcode);
786     }
787     break;
788 
789   // We don't currently select the correct instruction form for instructions
790   // which have a short %eax, etc. form. Handle this by custom lowering, for
791   // now.
792   //
793   // Note, we are currently not handling the following instructions:
794   // MOV64ao8, MOV64o8a
795   // XCHG16ar, XCHG32ar, XCHG64ar
796   case X86::MOV8mr_NOREX:
797   case X86::MOV8mr:
798   case X86::MOV8rm_NOREX:
799   case X86::MOV8rm:
800   case X86::MOV16mr:
801   case X86::MOV16rm:
802   case X86::MOV32mr:
803   case X86::MOV32rm: {
804     unsigned NewOpc;
805     switch (OutMI.getOpcode()) {
806     default: llvm_unreachable("Invalid opcode");
807     case X86::MOV8mr_NOREX:
808     case X86::MOV8mr:  NewOpc = X86::MOV8o32a; break;
809     case X86::MOV8rm_NOREX:
810     case X86::MOV8rm:  NewOpc = X86::MOV8ao32; break;
811     case X86::MOV16mr: NewOpc = X86::MOV16o32a; break;
812     case X86::MOV16rm: NewOpc = X86::MOV16ao32; break;
813     case X86::MOV32mr: NewOpc = X86::MOV32o32a; break;
814     case X86::MOV32rm: NewOpc = X86::MOV32ao32; break;
815     }
816     SimplifyShortMoveForm(AsmPrinter, OutMI, NewOpc);
817     break;
818   }
819 
820   case X86::ADC8ri: case X86::ADC16ri: case X86::ADC32ri: case X86::ADC64ri32:
821   case X86::ADD8ri: case X86::ADD16ri: case X86::ADD32ri: case X86::ADD64ri32:
822   case X86::AND8ri: case X86::AND16ri: case X86::AND32ri: case X86::AND64ri32:
823   case X86::CMP8ri: case X86::CMP16ri: case X86::CMP32ri: case X86::CMP64ri32:
824   case X86::OR8ri:  case X86::OR16ri:  case X86::OR32ri:  case X86::OR64ri32:
825   case X86::SBB8ri: case X86::SBB16ri: case X86::SBB32ri: case X86::SBB64ri32:
826   case X86::SUB8ri: case X86::SUB16ri: case X86::SUB32ri: case X86::SUB64ri32:
827   case X86::TEST8ri:case X86::TEST16ri:case X86::TEST32ri:case X86::TEST64ri32:
828   case X86::XOR8ri: case X86::XOR16ri: case X86::XOR32ri: case X86::XOR64ri32: {
829     unsigned NewOpc;
830     switch (OutMI.getOpcode()) {
831     default: llvm_unreachable("Invalid opcode");
832     case X86::ADC8ri:     NewOpc = X86::ADC8i8;    break;
833     case X86::ADC16ri:    NewOpc = X86::ADC16i16;  break;
834     case X86::ADC32ri:    NewOpc = X86::ADC32i32;  break;
835     case X86::ADC64ri32:  NewOpc = X86::ADC64i32;  break;
836     case X86::ADD8ri:     NewOpc = X86::ADD8i8;    break;
837     case X86::ADD16ri:    NewOpc = X86::ADD16i16;  break;
838     case X86::ADD32ri:    NewOpc = X86::ADD32i32;  break;
839     case X86::ADD64ri32:  NewOpc = X86::ADD64i32;  break;
840     case X86::AND8ri:     NewOpc = X86::AND8i8;    break;
841     case X86::AND16ri:    NewOpc = X86::AND16i16;  break;
842     case X86::AND32ri:    NewOpc = X86::AND32i32;  break;
843     case X86::AND64ri32:  NewOpc = X86::AND64i32;  break;
844     case X86::CMP8ri:     NewOpc = X86::CMP8i8;    break;
845     case X86::CMP16ri:    NewOpc = X86::CMP16i16;  break;
846     case X86::CMP32ri:    NewOpc = X86::CMP32i32;  break;
847     case X86::CMP64ri32:  NewOpc = X86::CMP64i32;  break;
848     case X86::OR8ri:      NewOpc = X86::OR8i8;     break;
849     case X86::OR16ri:     NewOpc = X86::OR16i16;   break;
850     case X86::OR32ri:     NewOpc = X86::OR32i32;   break;
851     case X86::OR64ri32:   NewOpc = X86::OR64i32;   break;
852     case X86::SBB8ri:     NewOpc = X86::SBB8i8;    break;
853     case X86::SBB16ri:    NewOpc = X86::SBB16i16;  break;
854     case X86::SBB32ri:    NewOpc = X86::SBB32i32;  break;
855     case X86::SBB64ri32:  NewOpc = X86::SBB64i32;  break;
856     case X86::SUB8ri:     NewOpc = X86::SUB8i8;    break;
857     case X86::SUB16ri:    NewOpc = X86::SUB16i16;  break;
858     case X86::SUB32ri:    NewOpc = X86::SUB32i32;  break;
859     case X86::SUB64ri32:  NewOpc = X86::SUB64i32;  break;
860     case X86::TEST8ri:    NewOpc = X86::TEST8i8;   break;
861     case X86::TEST16ri:   NewOpc = X86::TEST16i16; break;
862     case X86::TEST32ri:   NewOpc = X86::TEST32i32; break;
863     case X86::TEST64ri32: NewOpc = X86::TEST64i32; break;
864     case X86::XOR8ri:     NewOpc = X86::XOR8i8;    break;
865     case X86::XOR16ri:    NewOpc = X86::XOR16i16;  break;
866     case X86::XOR32ri:    NewOpc = X86::XOR32i32;  break;
867     case X86::XOR64ri32:  NewOpc = X86::XOR64i32;  break;
868     }
869     SimplifyShortImmForm(OutMI, NewOpc);
870     break;
871   }
872 
873   // Try to shrink some forms of movsx.
874   case X86::MOVSX16rr8:
875   case X86::MOVSX32rr16:
876   case X86::MOVSX64rr32:
877     SimplifyMOVSX(OutMI);
878     break;
879   }
880 }
881 
882 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
883                                  const MachineInstr &MI) {
884   bool Is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
885                   MI.getOpcode() == X86::TLS_base_addr64;
886   MCContext &Ctx = OutStreamer->getContext();
887 
888   MCSymbolRefExpr::VariantKind SRVK;
889   switch (MI.getOpcode()) {
890   case X86::TLS_addr32:
891   case X86::TLS_addr64:
892     SRVK = MCSymbolRefExpr::VK_TLSGD;
893     break;
894   case X86::TLS_base_addr32:
895     SRVK = MCSymbolRefExpr::VK_TLSLDM;
896     break;
897   case X86::TLS_base_addr64:
898     SRVK = MCSymbolRefExpr::VK_TLSLD;
899     break;
900   default:
901     llvm_unreachable("unexpected opcode");
902   }
903 
904   const MCSymbolRefExpr *Sym = MCSymbolRefExpr::create(
905       MCInstLowering.GetSymbolFromOperand(MI.getOperand(3)), SRVK, Ctx);
906 
907   // As of binutils 2.32, ld has a bogus TLS relaxation error when the GD/LD
908   // code sequence using R_X86_64_GOTPCREL (instead of R_X86_64_GOTPCRELX) is
909   // attempted to be relaxed to IE/LE (binutils PR24784). Work around the bug by
910   // only using GOT when GOTPCRELX is enabled.
911   // TODO Delete the workaround when GOTPCRELX becomes commonplace.
912   bool UseGot = MMI->getModule()->getRtLibUseGOT() &&
913                 Ctx.getAsmInfo()->canRelaxRelocations();
914 
915   if (Is64Bits) {
916     bool NeedsPadding = SRVK == MCSymbolRefExpr::VK_TLSGD;
917     if (NeedsPadding)
918       EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
919     EmitAndCountInstruction(MCInstBuilder(X86::LEA64r)
920                                 .addReg(X86::RDI)
921                                 .addReg(X86::RIP)
922                                 .addImm(1)
923                                 .addReg(0)
924                                 .addExpr(Sym)
925                                 .addReg(0));
926     const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("__tls_get_addr");
927     if (NeedsPadding) {
928       if (!UseGot)
929         EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
930       EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
931       EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
932     }
933     if (UseGot) {
934       const MCExpr *Expr = MCSymbolRefExpr::create(
935           TlsGetAddr, MCSymbolRefExpr::VK_GOTPCREL, Ctx);
936       EmitAndCountInstruction(MCInstBuilder(X86::CALL64m)
937                                   .addReg(X86::RIP)
938                                   .addImm(1)
939                                   .addReg(0)
940                                   .addExpr(Expr)
941                                   .addReg(0));
942     } else {
943       EmitAndCountInstruction(
944           MCInstBuilder(X86::CALL64pcrel32)
945               .addExpr(MCSymbolRefExpr::create(TlsGetAddr,
946                                                MCSymbolRefExpr::VK_PLT, Ctx)));
947     }
948   } else {
949     if (SRVK == MCSymbolRefExpr::VK_TLSGD && !UseGot) {
950       EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
951                                   .addReg(X86::EAX)
952                                   .addReg(0)
953                                   .addImm(1)
954                                   .addReg(X86::EBX)
955                                   .addExpr(Sym)
956                                   .addReg(0));
957     } else {
958       EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
959                                   .addReg(X86::EAX)
960                                   .addReg(X86::EBX)
961                                   .addImm(1)
962                                   .addReg(0)
963                                   .addExpr(Sym)
964                                   .addReg(0));
965     }
966 
967     const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("___tls_get_addr");
968     if (UseGot) {
969       const MCExpr *Expr =
970           MCSymbolRefExpr::create(TlsGetAddr, MCSymbolRefExpr::VK_GOT, Ctx);
971       EmitAndCountInstruction(MCInstBuilder(X86::CALL32m)
972                                   .addReg(X86::EBX)
973                                   .addImm(1)
974                                   .addReg(0)
975                                   .addExpr(Expr)
976                                   .addReg(0));
977     } else {
978       EmitAndCountInstruction(
979           MCInstBuilder(X86::CALLpcrel32)
980               .addExpr(MCSymbolRefExpr::create(TlsGetAddr,
981                                                MCSymbolRefExpr::VK_PLT, Ctx)));
982     }
983   }
984 }
985 
986 /// Emit the largest nop instruction smaller than or equal to \p NumBytes
987 /// bytes.  Return the size of nop emitted.
988 static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
989                         const MCSubtargetInfo &STI) {
990   // This works only for 64bit. For 32bit we have to do additional checking if
991   // the CPU supports multi-byte nops.
992   assert(Is64Bit && "EmitNops only supports X86-64");
993 
994   unsigned NopSize;
995   unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
996   IndexReg = Displacement = SegmentReg = 0;
997   BaseReg = X86::RAX;
998   ScaleVal = 1;
999   switch (NumBytes) {
1000   case 0:
1001     llvm_unreachable("Zero nops?");
1002     break;
1003   case 1:
1004     NopSize = 1;
1005     Opc = X86::NOOP;
1006     break;
1007   case 2:
1008     NopSize = 2;
1009     Opc = X86::XCHG16ar;
1010     break;
1011   case 3:
1012     NopSize = 3;
1013     Opc = X86::NOOPL;
1014     break;
1015   case 4:
1016     NopSize = 4;
1017     Opc = X86::NOOPL;
1018     Displacement = 8;
1019     break;
1020   case 5:
1021     NopSize = 5;
1022     Opc = X86::NOOPL;
1023     Displacement = 8;
1024     IndexReg = X86::RAX;
1025     break;
1026   case 6:
1027     NopSize = 6;
1028     Opc = X86::NOOPW;
1029     Displacement = 8;
1030     IndexReg = X86::RAX;
1031     break;
1032   case 7:
1033     NopSize = 7;
1034     Opc = X86::NOOPL;
1035     Displacement = 512;
1036     break;
1037   case 8:
1038     NopSize = 8;
1039     Opc = X86::NOOPL;
1040     Displacement = 512;
1041     IndexReg = X86::RAX;
1042     break;
1043   case 9:
1044     NopSize = 9;
1045     Opc = X86::NOOPW;
1046     Displacement = 512;
1047     IndexReg = X86::RAX;
1048     break;
1049   default:
1050     NopSize = 10;
1051     Opc = X86::NOOPW;
1052     Displacement = 512;
1053     IndexReg = X86::RAX;
1054     SegmentReg = X86::CS;
1055     break;
1056   }
1057 
1058   unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
1059   NopSize += NumPrefixes;
1060   for (unsigned i = 0; i != NumPrefixes; ++i)
1061     OS.EmitBytes("\x66");
1062 
1063   switch (Opc) {
1064   default: llvm_unreachable("Unexpected opcode");
1065   case X86::NOOP:
1066     OS.EmitInstruction(MCInstBuilder(Opc), STI);
1067     break;
1068   case X86::XCHG16ar:
1069     OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX).addReg(X86::AX), STI);
1070     break;
1071   case X86::NOOPL:
1072   case X86::NOOPW:
1073     OS.EmitInstruction(MCInstBuilder(Opc)
1074                            .addReg(BaseReg)
1075                            .addImm(ScaleVal)
1076                            .addReg(IndexReg)
1077                            .addImm(Displacement)
1078                            .addReg(SegmentReg),
1079                        STI);
1080     break;
1081   }
1082   assert(NopSize <= NumBytes && "We overemitted?");
1083   return NopSize;
1084 }
1085 
1086 /// Emit the optimal amount of multi-byte nops on X86.
1087 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
1088                      const MCSubtargetInfo &STI) {
1089   unsigned NopsToEmit = NumBytes;
1090   (void)NopsToEmit;
1091   while (NumBytes) {
1092     NumBytes -= EmitNop(OS, NumBytes, Is64Bit, STI);
1093     assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
1094   }
1095 }
1096 
1097 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
1098                                     X86MCInstLower &MCIL) {
1099   assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
1100 
1101   StatepointOpers SOpers(&MI);
1102   if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
1103     EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
1104              getSubtargetInfo());
1105   } else {
1106     // Lower call target and choose correct opcode
1107     const MachineOperand &CallTarget = SOpers.getCallTarget();
1108     MCOperand CallTargetMCOp;
1109     unsigned CallOpcode;
1110     switch (CallTarget.getType()) {
1111     case MachineOperand::MO_GlobalAddress:
1112     case MachineOperand::MO_ExternalSymbol:
1113       CallTargetMCOp = MCIL.LowerSymbolOperand(
1114           CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
1115       CallOpcode = X86::CALL64pcrel32;
1116       // Currently, we only support relative addressing with statepoints.
1117       // Otherwise, we'll need a scratch register to hold the target
1118       // address.  You'll fail asserts during load & relocation if this
1119       // symbol is to far away. (TODO: support non-relative addressing)
1120       break;
1121     case MachineOperand::MO_Immediate:
1122       CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
1123       CallOpcode = X86::CALL64pcrel32;
1124       // Currently, we only support relative addressing with statepoints.
1125       // Otherwise, we'll need a scratch register to hold the target
1126       // immediate.  You'll fail asserts during load & relocation if this
1127       // address is to far away. (TODO: support non-relative addressing)
1128       break;
1129     case MachineOperand::MO_Register:
1130       // FIXME: Add retpoline support and remove this.
1131       if (Subtarget->useRetpolineIndirectCalls())
1132         report_fatal_error("Lowering register statepoints with retpoline not "
1133                            "yet implemented.");
1134       CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
1135       CallOpcode = X86::CALL64r;
1136       break;
1137     default:
1138       llvm_unreachable("Unsupported operand type in statepoint call target");
1139       break;
1140     }
1141 
1142     // Emit call
1143     MCInst CallInst;
1144     CallInst.setOpcode(CallOpcode);
1145     CallInst.addOperand(CallTargetMCOp);
1146     OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
1147   }
1148 
1149   // Record our statepoint node in the same section used by STACKMAP
1150   // and PATCHPOINT
1151   SM.recordStatepoint(MI);
1152 }
1153 
1154 void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
1155                                      X86MCInstLower &MCIL) {
1156   // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
1157   //                  <opcode>, <operands>
1158 
1159   Register DefRegister = FaultingMI.getOperand(0).getReg();
1160   FaultMaps::FaultKind FK =
1161       static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
1162   MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
1163   unsigned Opcode = FaultingMI.getOperand(3).getImm();
1164   unsigned OperandsBeginIdx = 4;
1165 
1166   assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
1167   FM.recordFaultingOp(FK, HandlerLabel);
1168 
1169   MCInst MI;
1170   MI.setOpcode(Opcode);
1171 
1172   if (DefRegister != X86::NoRegister)
1173     MI.addOperand(MCOperand::createReg(DefRegister));
1174 
1175   for (auto I = FaultingMI.operands_begin() + OperandsBeginIdx,
1176             E = FaultingMI.operands_end();
1177        I != E; ++I)
1178     if (auto MaybeOperand = MCIL.LowerMachineOperand(&FaultingMI, *I))
1179       MI.addOperand(MaybeOperand.getValue());
1180 
1181   OutStreamer->AddComment("on-fault: " + HandlerLabel->getName());
1182   OutStreamer->EmitInstruction(MI, getSubtargetInfo());
1183 }
1184 
1185 void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
1186                                      X86MCInstLower &MCIL) {
1187   bool Is64Bits = Subtarget->is64Bit();
1188   MCContext &Ctx = OutStreamer->getContext();
1189   MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
1190   const MCSymbolRefExpr *Op =
1191       MCSymbolRefExpr::create(fentry, MCSymbolRefExpr::VK_None, Ctx);
1192 
1193   EmitAndCountInstruction(
1194       MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
1195           .addExpr(Op));
1196 }
1197 
1198 void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
1199                                       X86MCInstLower &MCIL) {
1200   // PATCHABLE_OP minsize, opcode, operands
1201 
1202   unsigned MinSize = MI.getOperand(0).getImm();
1203   unsigned Opcode = MI.getOperand(1).getImm();
1204 
1205   MCInst MCI;
1206   MCI.setOpcode(Opcode);
1207   for (auto &MO : make_range(MI.operands_begin() + 2, MI.operands_end()))
1208     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1209       MCI.addOperand(MaybeOperand.getValue());
1210 
1211   SmallString<256> Code;
1212   SmallVector<MCFixup, 4> Fixups;
1213   raw_svector_ostream VecOS(Code);
1214   CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
1215 
1216   if (Code.size() < MinSize) {
1217     if (MinSize == 2 && Opcode == X86::PUSH64r) {
1218       // This is an optimization that lets us get away without emitting a nop in
1219       // many cases.
1220       //
1221       // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %r9) takes two
1222       // bytes too, so the check on MinSize is important.
1223       MCI.setOpcode(X86::PUSH64rmr);
1224     } else {
1225       unsigned NopSize = EmitNop(*OutStreamer, MinSize, Subtarget->is64Bit(),
1226                                  getSubtargetInfo());
1227       assert(NopSize == MinSize && "Could not implement MinSize!");
1228       (void)NopSize;
1229     }
1230   }
1231 
1232   OutStreamer->EmitInstruction(MCI, getSubtargetInfo());
1233 }
1234 
1235 // Lower a stackmap of the form:
1236 // <id>, <shadowBytes>, ...
1237 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
1238   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1239   SM.recordStackMap(MI);
1240   unsigned NumShadowBytes = MI.getOperand(1).getImm();
1241   SMShadowTracker.reset(NumShadowBytes);
1242 }
1243 
1244 // Lower a patchpoint of the form:
1245 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
1246 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
1247                                     X86MCInstLower &MCIL) {
1248   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
1249 
1250   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1251 
1252   SM.recordPatchPoint(MI);
1253 
1254   PatchPointOpers opers(&MI);
1255   unsigned ScratchIdx = opers.getNextScratchIdx();
1256   unsigned EncodedBytes = 0;
1257   const MachineOperand &CalleeMO = opers.getCallTarget();
1258 
1259   // Check for null target. If target is non-null (i.e. is non-zero or is
1260   // symbolic) then emit a call.
1261   if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
1262     MCOperand CalleeMCOp;
1263     switch (CalleeMO.getType()) {
1264     default:
1265       /// FIXME: Add a verifier check for bad callee types.
1266       llvm_unreachable("Unrecognized callee operand type.");
1267     case MachineOperand::MO_Immediate:
1268       if (CalleeMO.getImm())
1269         CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
1270       break;
1271     case MachineOperand::MO_ExternalSymbol:
1272     case MachineOperand::MO_GlobalAddress:
1273       CalleeMCOp = MCIL.LowerSymbolOperand(CalleeMO,
1274                                            MCIL.GetSymbolFromOperand(CalleeMO));
1275       break;
1276     }
1277 
1278     // Emit MOV to materialize the target address and the CALL to target.
1279     // This is encoded with 12-13 bytes, depending on which register is used.
1280     Register ScratchReg = MI.getOperand(ScratchIdx).getReg();
1281     if (X86II::isX86_64ExtendedReg(ScratchReg))
1282       EncodedBytes = 13;
1283     else
1284       EncodedBytes = 12;
1285 
1286     EmitAndCountInstruction(
1287         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1288     // FIXME: Add retpoline support and remove this.
1289     if (Subtarget->useRetpolineIndirectCalls())
1290       report_fatal_error(
1291           "Lowering patchpoint with retpoline not yet implemented.");
1292     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1293   }
1294 
1295   // Emit padding.
1296   unsigned NumBytes = opers.getNumPatchBytes();
1297   assert(NumBytes >= EncodedBytes &&
1298          "Patchpoint can't request size less than the length of a call.");
1299 
1300   EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
1301            getSubtargetInfo());
1302 }
1303 
1304 void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
1305                                               X86MCInstLower &MCIL) {
1306   assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
1307 
1308   // We want to emit the following pattern, which follows the x86 calling
1309   // convention to prepare for the trampoline call to be patched in.
1310   //
1311   //   .p2align 1, ...
1312   // .Lxray_event_sled_N:
1313   //   jmp +N                        // jump across the instrumentation sled
1314   //   ...                           // set up arguments in register
1315   //   callq __xray_CustomEvent@plt  // force dependency to symbol
1316   //   ...
1317   //   <jump here>
1318   //
1319   // After patching, it would look something like:
1320   //
1321   //   nopw (2-byte nop)
1322   //   ...
1323   //   callq __xrayCustomEvent  // already lowered
1324   //   ...
1325   //
1326   // ---
1327   // First we emit the label and the jump.
1328   auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
1329   OutStreamer->AddComment("# XRay Custom Event Log");
1330   OutStreamer->EmitCodeAlignment(2);
1331   OutStreamer->EmitLabel(CurSled);
1332 
1333   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1334   // an operand (computed as an offset from the jmp instruction).
1335   // FIXME: Find another less hacky way do force the relative jump.
1336   OutStreamer->EmitBinaryData("\xeb\x0f");
1337 
1338   // The default C calling convention will place two arguments into %rcx and
1339   // %rdx -- so we only work with those.
1340   const Register DestRegs[] = {X86::RDI, X86::RSI};
1341   bool UsedMask[] = {false, false};
1342   // Filled out in loop.
1343   Register SrcRegs[] = {0, 0};
1344 
1345   // Then we put the operands in the %rdi and %rsi registers. We spill the
1346   // values in the register before we clobber them, and mark them as used in
1347   // UsedMask. In case the arguments are already in the correct register, we use
1348   // emit nops appropriately sized to keep the sled the same size in every
1349   // situation.
1350   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1351     if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1352       assert(Op->isReg() && "Only support arguments in registers");
1353       SrcRegs[I] = getX86SubSuperRegister(Op->getReg(), 64);
1354       if (SrcRegs[I] != DestRegs[I]) {
1355         UsedMask[I] = true;
1356         EmitAndCountInstruction(
1357             MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1358       } else {
1359         EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1360       }
1361     }
1362 
1363   // Now that the register values are stashed, mov arguments into place.
1364   // FIXME: This doesn't work if one of the later SrcRegs is equal to an
1365   // earlier DestReg. We will have already overwritten over the register before
1366   // we can copy from it.
1367   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1368     if (SrcRegs[I] != DestRegs[I])
1369       EmitAndCountInstruction(
1370           MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1371 
1372   // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
1373   // name of the trampoline to be implemented by the XRay runtime.
1374   auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
1375   MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1376   if (isPositionIndependent())
1377     TOp.setTargetFlags(X86II::MO_PLT);
1378 
1379   // Emit the call instruction.
1380   EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1381                               .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1382 
1383   // Restore caller-saved and used registers.
1384   for (unsigned I = sizeof UsedMask; I-- > 0;)
1385     if (UsedMask[I])
1386       EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1387     else
1388       EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1389 
1390   OutStreamer->AddComment("xray custom event end.");
1391 
1392   // Record the sled version. Older versions of this sled were spelled
1393   // differently, so we let the runtime handle the different offsets we're
1394   // using.
1395   recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 1);
1396 }
1397 
1398 void X86AsmPrinter::LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr &MI,
1399                                                     X86MCInstLower &MCIL) {
1400   assert(Subtarget->is64Bit() && "XRay typed events only supports X86-64");
1401 
1402   // We want to emit the following pattern, which follows the x86 calling
1403   // convention to prepare for the trampoline call to be patched in.
1404   //
1405   //   .p2align 1, ...
1406   // .Lxray_event_sled_N:
1407   //   jmp +N                        // jump across the instrumentation sled
1408   //   ...                           // set up arguments in register
1409   //   callq __xray_TypedEvent@plt  // force dependency to symbol
1410   //   ...
1411   //   <jump here>
1412   //
1413   // After patching, it would look something like:
1414   //
1415   //   nopw (2-byte nop)
1416   //   ...
1417   //   callq __xrayTypedEvent  // already lowered
1418   //   ...
1419   //
1420   // ---
1421   // First we emit the label and the jump.
1422   auto CurSled = OutContext.createTempSymbol("xray_typed_event_sled_", true);
1423   OutStreamer->AddComment("# XRay Typed Event Log");
1424   OutStreamer->EmitCodeAlignment(2);
1425   OutStreamer->EmitLabel(CurSled);
1426 
1427   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1428   // an operand (computed as an offset from the jmp instruction).
1429   // FIXME: Find another less hacky way do force the relative jump.
1430   OutStreamer->EmitBinaryData("\xeb\x14");
1431 
1432   // An x86-64 convention may place three arguments into %rcx, %rdx, and R8,
1433   // so we'll work with those. Or we may be called via SystemV, in which case
1434   // we don't have to do any translation.
1435   const Register DestRegs[] = {X86::RDI, X86::RSI, X86::RDX};
1436   bool UsedMask[] = {false, false, false};
1437 
1438   // Will fill out src regs in the loop.
1439   Register SrcRegs[] = {0, 0, 0};
1440 
1441   // Then we put the operands in the SystemV registers. We spill the values in
1442   // the registers before we clobber them, and mark them as used in UsedMask.
1443   // In case the arguments are already in the correct register, we emit nops
1444   // appropriately sized to keep the sled the same size in every situation.
1445   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1446     if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1447       // TODO: Is register only support adequate?
1448       assert(Op->isReg() && "Only supports arguments in registers");
1449       SrcRegs[I] = getX86SubSuperRegister(Op->getReg(), 64);
1450       if (SrcRegs[I] != DestRegs[I]) {
1451         UsedMask[I] = true;
1452         EmitAndCountInstruction(
1453             MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1454       } else {
1455         EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1456       }
1457     }
1458 
1459   // In the above loop we only stash all of the destination registers or emit
1460   // nops if the arguments are already in the right place. Doing the actually
1461   // moving is postponed until after all the registers are stashed so nothing
1462   // is clobbers. We've already added nops to account for the size of mov and
1463   // push if the register is in the right place, so we only have to worry about
1464   // emitting movs.
1465   // FIXME: This doesn't work if one of the later SrcRegs is equal to an
1466   // earlier DestReg. We will have already overwritten over the register before
1467   // we can copy from it.
1468   for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1469     if (UsedMask[I])
1470       EmitAndCountInstruction(
1471           MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1472 
1473   // We emit a hard dependency on the __xray_TypedEvent symbol, which is the
1474   // name of the trampoline to be implemented by the XRay runtime.
1475   auto TSym = OutContext.getOrCreateSymbol("__xray_TypedEvent");
1476   MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1477   if (isPositionIndependent())
1478     TOp.setTargetFlags(X86II::MO_PLT);
1479 
1480   // Emit the call instruction.
1481   EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1482                               .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1483 
1484   // Restore caller-saved and used registers.
1485   for (unsigned I = sizeof UsedMask; I-- > 0;)
1486     if (UsedMask[I])
1487       EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1488     else
1489       EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1490 
1491   OutStreamer->AddComment("xray typed event end.");
1492 
1493   // Record the sled version.
1494   recordSled(CurSled, MI, SledKind::TYPED_EVENT, 0);
1495 }
1496 
1497 void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1498                                                   X86MCInstLower &MCIL) {
1499   // We want to emit the following pattern:
1500   //
1501   //   .p2align 1, ...
1502   // .Lxray_sled_N:
1503   //   jmp .tmpN
1504   //   # 9 bytes worth of noops
1505   //
1506   // We need the 9 bytes because at runtime, we'd be patching over the full 11
1507   // bytes with the following pattern:
1508   //
1509   //   mov %r10, <function id, 32-bit>   // 6 bytes
1510   //   call <relative offset, 32-bits>   // 5 bytes
1511   //
1512   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1513   OutStreamer->EmitCodeAlignment(2);
1514   OutStreamer->EmitLabel(CurSled);
1515 
1516   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1517   // an operand (computed as an offset from the jmp instruction).
1518   // FIXME: Find another less hacky way do force the relative jump.
1519   OutStreamer->EmitBytes("\xeb\x09");
1520   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1521   recordSled(CurSled, MI, SledKind::FUNCTION_ENTER);
1522 }
1523 
1524 void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1525                                        X86MCInstLower &MCIL) {
1526   // Since PATCHABLE_RET takes the opcode of the return statement as an
1527   // argument, we use that to emit the correct form of the RET that we want.
1528   // i.e. when we see this:
1529   //
1530   //   PATCHABLE_RET X86::RET ...
1531   //
1532   // We should emit the RET followed by sleds.
1533   //
1534   //   .p2align 1, ...
1535   // .Lxray_sled_N:
1536   //   ret  # or equivalent instruction
1537   //   # 10 bytes worth of noops
1538   //
1539   // This just makes sure that the alignment for the next instruction is 2.
1540   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1541   OutStreamer->EmitCodeAlignment(2);
1542   OutStreamer->EmitLabel(CurSled);
1543   unsigned OpCode = MI.getOperand(0).getImm();
1544   MCInst Ret;
1545   Ret.setOpcode(OpCode);
1546   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1547     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1548       Ret.addOperand(MaybeOperand.getValue());
1549   OutStreamer->EmitInstruction(Ret, getSubtargetInfo());
1550   EmitNops(*OutStreamer, 10, Subtarget->is64Bit(), getSubtargetInfo());
1551   recordSled(CurSled, MI, SledKind::FUNCTION_EXIT);
1552 }
1553 
1554 void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI,
1555                                              X86MCInstLower &MCIL) {
1556   // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1557   // instruction so we lower that particular instruction and its operands.
1558   // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1559   // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1560   // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1561   // tail call much like how we have it in PATCHABLE_RET.
1562   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1563   OutStreamer->EmitCodeAlignment(2);
1564   OutStreamer->EmitLabel(CurSled);
1565   auto Target = OutContext.createTempSymbol();
1566 
1567   // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1568   // an operand (computed as an offset from the jmp instruction).
1569   // FIXME: Find another less hacky way do force the relative jump.
1570   OutStreamer->EmitBytes("\xeb\x09");
1571   EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1572   OutStreamer->EmitLabel(Target);
1573   recordSled(CurSled, MI, SledKind::TAIL_CALL);
1574 
1575   unsigned OpCode = MI.getOperand(0).getImm();
1576   OpCode = convertTailJumpOpcode(OpCode);
1577   MCInst TC;
1578   TC.setOpcode(OpCode);
1579 
1580   // Before emitting the instruction, add a comment to indicate that this is
1581   // indeed a tail call.
1582   OutStreamer->AddComment("TAILCALL");
1583   for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1584     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1585       TC.addOperand(MaybeOperand.getValue());
1586   OutStreamer->EmitInstruction(TC, getSubtargetInfo());
1587 }
1588 
1589 // Returns instruction preceding MBBI in MachineFunction.
1590 // If MBBI is the first instruction of the first basic block, returns null.
1591 static MachineBasicBlock::const_iterator
1592 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
1593   const MachineBasicBlock *MBB = MBBI->getParent();
1594   while (MBBI == MBB->begin()) {
1595     if (MBB == &MBB->getParent()->front())
1596       return MachineBasicBlock::const_iterator();
1597     MBB = MBB->getPrevNode();
1598     MBBI = MBB->end();
1599   }
1600   --MBBI;
1601   return MBBI;
1602 }
1603 
1604 static const Constant *getConstantFromPool(const MachineInstr &MI,
1605                                            const MachineOperand &Op) {
1606   if (!Op.isCPI() || Op.getOffset() != 0)
1607     return nullptr;
1608 
1609   ArrayRef<MachineConstantPoolEntry> Constants =
1610       MI.getParent()->getParent()->getConstantPool()->getConstants();
1611   const MachineConstantPoolEntry &ConstantEntry = Constants[Op.getIndex()];
1612 
1613   // Bail if this is a machine constant pool entry, we won't be able to dig out
1614   // anything useful.
1615   if (ConstantEntry.isMachineConstantPoolEntry())
1616     return nullptr;
1617 
1618   const Constant *C = ConstantEntry.Val.ConstVal;
1619   assert((!C || ConstantEntry.getType() == C->getType()) &&
1620          "Expected a constant of the same type!");
1621   return C;
1622 }
1623 
1624 static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx,
1625                                      unsigned SrcOp2Idx, ArrayRef<int> Mask) {
1626   std::string Comment;
1627 
1628   // Compute the name for a register. This is really goofy because we have
1629   // multiple instruction printers that could (in theory) use different
1630   // names. Fortunately most people use the ATT style (outside of Windows)
1631   // and they actually agree on register naming here. Ultimately, this is
1632   // a comment, and so its OK if it isn't perfect.
1633   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1634     return X86ATTInstPrinter::getRegisterName(RegNum);
1635   };
1636 
1637   const MachineOperand &DstOp = MI->getOperand(0);
1638   const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
1639   const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
1640 
1641   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1642   StringRef Src1Name =
1643       SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
1644   StringRef Src2Name =
1645       SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
1646 
1647   // One source operand, fix the mask to print all elements in one span.
1648   SmallVector<int, 8> ShuffleMask(Mask.begin(), Mask.end());
1649   if (Src1Name == Src2Name)
1650     for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1651       if (ShuffleMask[i] >= e)
1652         ShuffleMask[i] -= e;
1653 
1654   raw_string_ostream CS(Comment);
1655   CS << DstName;
1656 
1657   // Handle AVX512 MASK/MASXZ write mask comments.
1658   // MASK: zmmX {%kY}
1659   // MASKZ: zmmX {%kY} {z}
1660   if (SrcOp1Idx > 1) {
1661     assert((SrcOp1Idx == 2 || SrcOp1Idx == 3) && "Unexpected writemask");
1662 
1663     const MachineOperand &WriteMaskOp = MI->getOperand(SrcOp1Idx - 1);
1664     if (WriteMaskOp.isReg()) {
1665       CS << " {%" << GetRegisterName(WriteMaskOp.getReg()) << "}";
1666 
1667       if (SrcOp1Idx == 2) {
1668         CS << " {z}";
1669       }
1670     }
1671   }
1672 
1673   CS << " = ";
1674 
1675   for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1676     if (i != 0)
1677       CS << ",";
1678     if (ShuffleMask[i] == SM_SentinelZero) {
1679       CS << "zero";
1680       continue;
1681     }
1682 
1683     // Otherwise, it must come from src1 or src2.  Print the span of elements
1684     // that comes from this src.
1685     bool isSrc1 = ShuffleMask[i] < (int)e;
1686     CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1687 
1688     bool IsFirst = true;
1689     while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1690            (ShuffleMask[i] < (int)e) == isSrc1) {
1691       if (!IsFirst)
1692         CS << ',';
1693       else
1694         IsFirst = false;
1695       if (ShuffleMask[i] == SM_SentinelUndef)
1696         CS << "u";
1697       else
1698         CS << ShuffleMask[i] % (int)e;
1699       ++i;
1700     }
1701     CS << ']';
1702     --i; // For loop increments element #.
1703   }
1704   CS.flush();
1705 
1706   return Comment;
1707 }
1708 
1709 static void printConstant(const APInt &Val, raw_ostream &CS) {
1710   if (Val.getBitWidth() <= 64) {
1711     CS << Val.getZExtValue();
1712   } else {
1713     // print multi-word constant as (w0,w1)
1714     CS << "(";
1715     for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1716       if (i > 0)
1717         CS << ",";
1718       CS << Val.getRawData()[i];
1719     }
1720     CS << ")";
1721   }
1722 }
1723 
1724 static void printConstant(const APFloat &Flt, raw_ostream &CS) {
1725   SmallString<32> Str;
1726   // Force scientific notation to distinquish from integers.
1727   Flt.toString(Str, 0, 0);
1728   CS << Str;
1729 }
1730 
1731 static void printConstant(const Constant *COp, raw_ostream &CS) {
1732   if (isa<UndefValue>(COp)) {
1733     CS << "u";
1734   } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1735     printConstant(CI->getValue(), CS);
1736   } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1737     printConstant(CF->getValueAPF(), CS);
1738   } else {
1739     CS << "?";
1740   }
1741 }
1742 
1743 void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
1744   assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1745   assert(getSubtarget().isOSWindows() && "SEH_ instruction Windows only");
1746 
1747   // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
1748   if (EmitFPOData) {
1749     X86TargetStreamer *XTS =
1750         static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
1751     switch (MI->getOpcode()) {
1752     case X86::SEH_PushReg:
1753       XTS->emitFPOPushReg(MI->getOperand(0).getImm());
1754       break;
1755     case X86::SEH_StackAlloc:
1756       XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
1757       break;
1758     case X86::SEH_StackAlign:
1759       XTS->emitFPOStackAlign(MI->getOperand(0).getImm());
1760       break;
1761     case X86::SEH_SetFrame:
1762       assert(MI->getOperand(1).getImm() == 0 &&
1763              ".cv_fpo_setframe takes no offset");
1764       XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
1765       break;
1766     case X86::SEH_EndPrologue:
1767       XTS->emitFPOEndPrologue();
1768       break;
1769     case X86::SEH_SaveReg:
1770     case X86::SEH_SaveXMM:
1771     case X86::SEH_PushFrame:
1772       llvm_unreachable("SEH_ directive incompatible with FPO");
1773       break;
1774     default:
1775       llvm_unreachable("expected SEH_ instruction");
1776     }
1777     return;
1778   }
1779 
1780   // Otherwise, use the .seh_ directives for all other Windows platforms.
1781   switch (MI->getOpcode()) {
1782   case X86::SEH_PushReg:
1783     OutStreamer->EmitWinCFIPushReg(MI->getOperand(0).getImm());
1784     break;
1785 
1786   case X86::SEH_SaveReg:
1787     OutStreamer->EmitWinCFISaveReg(MI->getOperand(0).getImm(),
1788                                    MI->getOperand(1).getImm());
1789     break;
1790 
1791   case X86::SEH_SaveXMM:
1792     OutStreamer->EmitWinCFISaveXMM(MI->getOperand(0).getImm(),
1793                                    MI->getOperand(1).getImm());
1794     break;
1795 
1796   case X86::SEH_StackAlloc:
1797     OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1798     break;
1799 
1800   case X86::SEH_SetFrame:
1801     OutStreamer->EmitWinCFISetFrame(MI->getOperand(0).getImm(),
1802                                     MI->getOperand(1).getImm());
1803     break;
1804 
1805   case X86::SEH_PushFrame:
1806     OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1807     break;
1808 
1809   case X86::SEH_EndPrologue:
1810     OutStreamer->EmitWinCFIEndProlog();
1811     break;
1812 
1813   default:
1814     llvm_unreachable("expected SEH_ instruction");
1815   }
1816 }
1817 
1818 static unsigned getRegisterWidth(const MCOperandInfo &Info) {
1819   if (Info.RegClass == X86::VR128RegClassID ||
1820       Info.RegClass == X86::VR128XRegClassID)
1821     return 128;
1822   if (Info.RegClass == X86::VR256RegClassID ||
1823       Info.RegClass == X86::VR256XRegClassID)
1824     return 256;
1825   if (Info.RegClass == X86::VR512RegClassID)
1826     return 512;
1827   llvm_unreachable("Unknown register class!");
1828 }
1829 
1830 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
1831   X86MCInstLower MCInstLowering(*MF, *this);
1832   const X86RegisterInfo *RI =
1833       MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1834 
1835   // Add a comment about EVEX-2-VEX compression for AVX-512 instrs that
1836   // are compressed from EVEX encoding to VEX encoding.
1837   if (TM.Options.MCOptions.ShowMCEncoding) {
1838     if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_VEX)
1839       OutStreamer->AddComment("EVEX TO VEX Compression ", false);
1840   }
1841 
1842   switch (MI->getOpcode()) {
1843   case TargetOpcode::DBG_VALUE:
1844     llvm_unreachable("Should be handled target independently");
1845 
1846   // Emit nothing here but a comment if we can.
1847   case X86::Int_MemBarrier:
1848     OutStreamer->emitRawComment("MEMBARRIER");
1849     return;
1850 
1851   case X86::EH_RETURN:
1852   case X86::EH_RETURN64: {
1853     // Lower these as normal, but add some comments.
1854     Register Reg = MI->getOperand(0).getReg();
1855     OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1856                             X86ATTInstPrinter::getRegisterName(Reg));
1857     break;
1858   }
1859   case X86::CLEANUPRET: {
1860     // Lower these as normal, but add some comments.
1861     OutStreamer->AddComment("CLEANUPRET");
1862     break;
1863   }
1864 
1865   case X86::CATCHRET: {
1866     // Lower these as normal, but add some comments.
1867     OutStreamer->AddComment("CATCHRET");
1868     break;
1869   }
1870 
1871   case X86::TAILJMPr:
1872   case X86::TAILJMPm:
1873   case X86::TAILJMPd:
1874   case X86::TAILJMPd_CC:
1875   case X86::TAILJMPr64:
1876   case X86::TAILJMPm64:
1877   case X86::TAILJMPd64:
1878   case X86::TAILJMPd64_CC:
1879   case X86::TAILJMPr64_REX:
1880   case X86::TAILJMPm64_REX:
1881     // Lower these as normal, but add some comments.
1882     OutStreamer->AddComment("TAILCALL");
1883     break;
1884 
1885   case X86::TLS_addr32:
1886   case X86::TLS_addr64:
1887   case X86::TLS_base_addr32:
1888   case X86::TLS_base_addr64:
1889     return LowerTlsAddr(MCInstLowering, *MI);
1890 
1891   // Loading/storing mask pairs requires two kmov operations. The second one of these
1892   // needs a 2 byte displacement relative to the specified address (with 32 bit spill
1893   // size). The pairs of 1bit masks up to 16 bit masks all use the same spill size,
1894   // they all are stored using MASKPAIR16STORE, loaded using MASKPAIR16LOAD.
1895   //
1896   // The displacement value might wrap around in theory, thus the asserts in both
1897   // cases.
1898   case X86::MASKPAIR16LOAD: {
1899     int64_t Disp = MI->getOperand(1 + X86::AddrDisp).getImm();
1900     assert(Disp >= 0 && Disp <= INT32_MAX - 2 && "Unexpected displacement");
1901     Register Reg = MI->getOperand(0).getReg();
1902     Register Reg0 = RI->getSubReg(Reg, X86::sub_mask_0);
1903     Register Reg1 = RI->getSubReg(Reg, X86::sub_mask_1);
1904 
1905     // Load the first mask register
1906     MCInstBuilder MIB = MCInstBuilder(X86::KMOVWkm);
1907     MIB.addReg(Reg0);
1908     for (int i = 0; i < X86::AddrNumOperands; ++i) {
1909       auto Op = MCInstLowering.LowerMachineOperand(MI, MI->getOperand(1 + i));
1910       MIB.addOperand(Op.getValue());
1911     }
1912     EmitAndCountInstruction(MIB);
1913 
1914     // Load the second mask register of the pair
1915     MIB = MCInstBuilder(X86::KMOVWkm);
1916     MIB.addReg(Reg1);
1917     for (int i = 0; i < X86::AddrNumOperands; ++i) {
1918       if (i == X86::AddrDisp) {
1919         MIB.addImm(Disp + 2);
1920       } else {
1921         auto Op = MCInstLowering.LowerMachineOperand(MI, MI->getOperand(1 + i));
1922         MIB.addOperand(Op.getValue());
1923       }
1924     }
1925     EmitAndCountInstruction(MIB);
1926     return;
1927   }
1928 
1929   case X86::MASKPAIR16STORE: {
1930     int64_t Disp = MI->getOperand(X86::AddrDisp).getImm();
1931     assert(Disp >= 0 && Disp <= INT32_MAX - 2 && "Unexpected displacement");
1932     Register Reg = MI->getOperand(X86::AddrNumOperands).getReg();
1933     Register Reg0 = RI->getSubReg(Reg, X86::sub_mask_0);
1934     Register Reg1 = RI->getSubReg(Reg, X86::sub_mask_1);
1935 
1936     // Store the first mask register
1937     MCInstBuilder MIB = MCInstBuilder(X86::KMOVWmk);
1938     for (int i = 0; i < X86::AddrNumOperands; ++i)
1939       MIB.addOperand(MCInstLowering.LowerMachineOperand(MI, MI->getOperand(i)).getValue());
1940     MIB.addReg(Reg0);
1941     EmitAndCountInstruction(MIB);
1942 
1943     // Store the second mask register of the pair
1944     MIB = MCInstBuilder(X86::KMOVWmk);
1945     for (int i = 0; i < X86::AddrNumOperands; ++i) {
1946       if (i == X86::AddrDisp) {
1947         MIB.addImm(Disp + 2);
1948       } else {
1949         auto Op = MCInstLowering.LowerMachineOperand(MI, MI->getOperand(0 + i));
1950         MIB.addOperand(Op.getValue());
1951       }
1952     }
1953     MIB.addReg(Reg1);
1954     EmitAndCountInstruction(MIB);
1955     return;
1956   }
1957 
1958   case X86::MOVPC32r: {
1959     // This is a pseudo op for a two instruction sequence with a label, which
1960     // looks like:
1961     //     call "L1$pb"
1962     // "L1$pb":
1963     //     popl %esi
1964 
1965     // Emit the call.
1966     MCSymbol *PICBase = MF->getPICBaseSymbol();
1967     // FIXME: We would like an efficient form for this, so we don't have to do a
1968     // lot of extra uniquing.
1969     EmitAndCountInstruction(
1970         MCInstBuilder(X86::CALLpcrel32)
1971             .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
1972 
1973     const X86FrameLowering *FrameLowering =
1974         MF->getSubtarget<X86Subtarget>().getFrameLowering();
1975     bool hasFP = FrameLowering->hasFP(*MF);
1976 
1977     // TODO: This is needed only if we require precise CFA.
1978     bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
1979                                !OutStreamer->getDwarfFrameInfos().back().End;
1980 
1981     int stackGrowth = -RI->getSlotSize();
1982 
1983     if (HasActiveDwarfFrame && !hasFP) {
1984       OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
1985     }
1986 
1987     // Emit the label.
1988     OutStreamer->EmitLabel(PICBase);
1989 
1990     // popl $reg
1991     EmitAndCountInstruction(
1992         MCInstBuilder(X86::POP32r).addReg(MI->getOperand(0).getReg()));
1993 
1994     if (HasActiveDwarfFrame && !hasFP) {
1995       OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
1996     }
1997     return;
1998   }
1999 
2000   case X86::ADD32ri: {
2001     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
2002     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
2003       break;
2004 
2005     // Okay, we have something like:
2006     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
2007 
2008     // For this, we want to print something like:
2009     //   MYGLOBAL + (. - PICBASE)
2010     // However, we can't generate a ".", so just emit a new label here and refer
2011     // to it.
2012     MCSymbol *DotSym = OutContext.createTempSymbol();
2013     OutStreamer->EmitLabel(DotSym);
2014 
2015     // Now that we have emitted the label, lower the complex operand expression.
2016     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
2017 
2018     const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
2019     const MCExpr *PICBase =
2020         MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
2021     DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
2022 
2023     DotExpr = MCBinaryExpr::createAdd(
2024         MCSymbolRefExpr::create(OpSym, OutContext), DotExpr, OutContext);
2025 
2026     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
2027                                 .addReg(MI->getOperand(0).getReg())
2028                                 .addReg(MI->getOperand(1).getReg())
2029                                 .addExpr(DotExpr));
2030     return;
2031   }
2032   case TargetOpcode::STATEPOINT:
2033     return LowerSTATEPOINT(*MI, MCInstLowering);
2034 
2035   case TargetOpcode::FAULTING_OP:
2036     return LowerFAULTING_OP(*MI, MCInstLowering);
2037 
2038   case TargetOpcode::FENTRY_CALL:
2039     return LowerFENTRY_CALL(*MI, MCInstLowering);
2040 
2041   case TargetOpcode::PATCHABLE_OP:
2042     return LowerPATCHABLE_OP(*MI, MCInstLowering);
2043 
2044   case TargetOpcode::STACKMAP:
2045     return LowerSTACKMAP(*MI);
2046 
2047   case TargetOpcode::PATCHPOINT:
2048     return LowerPATCHPOINT(*MI, MCInstLowering);
2049 
2050   case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
2051     return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
2052 
2053   case TargetOpcode::PATCHABLE_RET:
2054     return LowerPATCHABLE_RET(*MI, MCInstLowering);
2055 
2056   case TargetOpcode::PATCHABLE_TAIL_CALL:
2057     return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
2058 
2059   case TargetOpcode::PATCHABLE_EVENT_CALL:
2060     return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
2061 
2062   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
2063     return LowerPATCHABLE_TYPED_EVENT_CALL(*MI, MCInstLowering);
2064 
2065   case X86::MORESTACK_RET:
2066     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
2067     return;
2068 
2069   case X86::MORESTACK_RET_RESTORE_R10:
2070     // Return, then restore R10.
2071     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
2072     EmitAndCountInstruction(
2073         MCInstBuilder(X86::MOV64rr).addReg(X86::R10).addReg(X86::RAX));
2074     return;
2075 
2076   case X86::SEH_PushReg:
2077   case X86::SEH_SaveReg:
2078   case X86::SEH_SaveXMM:
2079   case X86::SEH_StackAlloc:
2080   case X86::SEH_StackAlign:
2081   case X86::SEH_SetFrame:
2082   case X86::SEH_PushFrame:
2083   case X86::SEH_EndPrologue:
2084     EmitSEHInstruction(MI);
2085     return;
2086 
2087   case X86::SEH_Epilogue: {
2088     assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
2089     MachineBasicBlock::const_iterator MBBI(MI);
2090     // Check if preceded by a call and emit nop if so.
2091     for (MBBI = PrevCrossBBInst(MBBI);
2092          MBBI != MachineBasicBlock::const_iterator();
2093          MBBI = PrevCrossBBInst(MBBI)) {
2094       // Conservatively assume that pseudo instructions don't emit code and keep
2095       // looking for a call. We may emit an unnecessary nop in some cases.
2096       if (!MBBI->isPseudo()) {
2097         if (MBBI->isCall())
2098           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
2099         break;
2100       }
2101     }
2102     return;
2103   }
2104 
2105   // Lower PSHUFB and VPERMILP normally but add a comment if we can find
2106   // a constant shuffle mask. We won't be able to do this at the MC layer
2107   // because the mask isn't an immediate.
2108   case X86::PSHUFBrm:
2109   case X86::VPSHUFBrm:
2110   case X86::VPSHUFBYrm:
2111   case X86::VPSHUFBZ128rm:
2112   case X86::VPSHUFBZ128rmk:
2113   case X86::VPSHUFBZ128rmkz:
2114   case X86::VPSHUFBZ256rm:
2115   case X86::VPSHUFBZ256rmk:
2116   case X86::VPSHUFBZ256rmkz:
2117   case X86::VPSHUFBZrm:
2118   case X86::VPSHUFBZrmk:
2119   case X86::VPSHUFBZrmkz: {
2120     if (!OutStreamer->isVerboseAsm())
2121       break;
2122     unsigned SrcIdx, MaskIdx;
2123     switch (MI->getOpcode()) {
2124     default: llvm_unreachable("Invalid opcode");
2125     case X86::PSHUFBrm:
2126     case X86::VPSHUFBrm:
2127     case X86::VPSHUFBYrm:
2128     case X86::VPSHUFBZ128rm:
2129     case X86::VPSHUFBZ256rm:
2130     case X86::VPSHUFBZrm:
2131       SrcIdx = 1; MaskIdx = 5; break;
2132     case X86::VPSHUFBZ128rmkz:
2133     case X86::VPSHUFBZ256rmkz:
2134     case X86::VPSHUFBZrmkz:
2135       SrcIdx = 2; MaskIdx = 6; break;
2136     case X86::VPSHUFBZ128rmk:
2137     case X86::VPSHUFBZ256rmk:
2138     case X86::VPSHUFBZrmk:
2139       SrcIdx = 3; MaskIdx = 7; break;
2140     }
2141 
2142     assert(MI->getNumOperands() >= 6 &&
2143            "We should always have at least 6 operands!");
2144 
2145     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
2146     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2147       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2148       SmallVector<int, 64> Mask;
2149       DecodePSHUFBMask(C, Width, Mask);
2150       if (!Mask.empty())
2151         OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
2152     }
2153     break;
2154   }
2155 
2156   case X86::VPERMILPSrm:
2157   case X86::VPERMILPSYrm:
2158   case X86::VPERMILPSZ128rm:
2159   case X86::VPERMILPSZ128rmk:
2160   case X86::VPERMILPSZ128rmkz:
2161   case X86::VPERMILPSZ256rm:
2162   case X86::VPERMILPSZ256rmk:
2163   case X86::VPERMILPSZ256rmkz:
2164   case X86::VPERMILPSZrm:
2165   case X86::VPERMILPSZrmk:
2166   case X86::VPERMILPSZrmkz:
2167   case X86::VPERMILPDrm:
2168   case X86::VPERMILPDYrm:
2169   case X86::VPERMILPDZ128rm:
2170   case X86::VPERMILPDZ128rmk:
2171   case X86::VPERMILPDZ128rmkz:
2172   case X86::VPERMILPDZ256rm:
2173   case X86::VPERMILPDZ256rmk:
2174   case X86::VPERMILPDZ256rmkz:
2175   case X86::VPERMILPDZrm:
2176   case X86::VPERMILPDZrmk:
2177   case X86::VPERMILPDZrmkz: {
2178     if (!OutStreamer->isVerboseAsm())
2179       break;
2180     unsigned SrcIdx, MaskIdx;
2181     unsigned ElSize;
2182     switch (MI->getOpcode()) {
2183     default: llvm_unreachable("Invalid opcode");
2184     case X86::VPERMILPSrm:
2185     case X86::VPERMILPSYrm:
2186     case X86::VPERMILPSZ128rm:
2187     case X86::VPERMILPSZ256rm:
2188     case X86::VPERMILPSZrm:
2189       SrcIdx = 1; MaskIdx = 5; ElSize = 32; break;
2190     case X86::VPERMILPSZ128rmkz:
2191     case X86::VPERMILPSZ256rmkz:
2192     case X86::VPERMILPSZrmkz:
2193       SrcIdx = 2; MaskIdx = 6; ElSize = 32; break;
2194     case X86::VPERMILPSZ128rmk:
2195     case X86::VPERMILPSZ256rmk:
2196     case X86::VPERMILPSZrmk:
2197       SrcIdx = 3; MaskIdx = 7; ElSize = 32; break;
2198     case X86::VPERMILPDrm:
2199     case X86::VPERMILPDYrm:
2200     case X86::VPERMILPDZ128rm:
2201     case X86::VPERMILPDZ256rm:
2202     case X86::VPERMILPDZrm:
2203       SrcIdx = 1; MaskIdx = 5; ElSize = 64; break;
2204     case X86::VPERMILPDZ128rmkz:
2205     case X86::VPERMILPDZ256rmkz:
2206     case X86::VPERMILPDZrmkz:
2207       SrcIdx = 2; MaskIdx = 6; ElSize = 64; break;
2208     case X86::VPERMILPDZ128rmk:
2209     case X86::VPERMILPDZ256rmk:
2210     case X86::VPERMILPDZrmk:
2211       SrcIdx = 3; MaskIdx = 7; ElSize = 64; break;
2212     }
2213 
2214     assert(MI->getNumOperands() >= 6 &&
2215            "We should always have at least 6 operands!");
2216 
2217     const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
2218     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2219       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2220       SmallVector<int, 16> Mask;
2221       DecodeVPERMILPMask(C, ElSize, Width, Mask);
2222       if (!Mask.empty())
2223         OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
2224     }
2225     break;
2226   }
2227 
2228   case X86::VPERMIL2PDrm:
2229   case X86::VPERMIL2PSrm:
2230   case X86::VPERMIL2PDYrm:
2231   case X86::VPERMIL2PSYrm: {
2232     if (!OutStreamer->isVerboseAsm())
2233       break;
2234     assert(MI->getNumOperands() >= 8 &&
2235            "We should always have at least 8 operands!");
2236 
2237     const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
2238     if (!CtrlOp.isImm())
2239       break;
2240 
2241     unsigned ElSize;
2242     switch (MI->getOpcode()) {
2243     default: llvm_unreachable("Invalid opcode");
2244     case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
2245     case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
2246     }
2247 
2248     const MachineOperand &MaskOp = MI->getOperand(6);
2249     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2250       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2251       SmallVector<int, 16> Mask;
2252       DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Width, Mask);
2253       if (!Mask.empty())
2254         OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask));
2255     }
2256     break;
2257   }
2258 
2259   case X86::VPPERMrrm: {
2260     if (!OutStreamer->isVerboseAsm())
2261       break;
2262     assert(MI->getNumOperands() >= 7 &&
2263            "We should always have at least 7 operands!");
2264 
2265     const MachineOperand &MaskOp = MI->getOperand(6);
2266     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2267       unsigned Width = getRegisterWidth(MI->getDesc().OpInfo[0]);
2268       SmallVector<int, 16> Mask;
2269       DecodeVPPERMMask(C, Width, Mask);
2270       if (!Mask.empty())
2271         OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask));
2272     }
2273     break;
2274   }
2275 
2276   case X86::MMX_MOVQ64rm: {
2277     if (!OutStreamer->isVerboseAsm())
2278       break;
2279     if (MI->getNumOperands() <= 4)
2280       break;
2281     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2282       std::string Comment;
2283       raw_string_ostream CS(Comment);
2284       const MachineOperand &DstOp = MI->getOperand(0);
2285       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2286       if (auto *CF = dyn_cast<ConstantFP>(C)) {
2287         CS << "0x" << CF->getValueAPF().bitcastToAPInt().toString(16, false);
2288         OutStreamer->AddComment(CS.str());
2289       }
2290     }
2291     break;
2292   }
2293 
2294 #define MOV_CASE(Prefix, Suffix)                                               \
2295   case X86::Prefix##MOVAPD##Suffix##rm:                                        \
2296   case X86::Prefix##MOVAPS##Suffix##rm:                                        \
2297   case X86::Prefix##MOVUPD##Suffix##rm:                                        \
2298   case X86::Prefix##MOVUPS##Suffix##rm:                                        \
2299   case X86::Prefix##MOVDQA##Suffix##rm:                                        \
2300   case X86::Prefix##MOVDQU##Suffix##rm:
2301 
2302 #define MOV_AVX512_CASE(Suffix)                                                \
2303   case X86::VMOVDQA64##Suffix##rm:                                             \
2304   case X86::VMOVDQA32##Suffix##rm:                                             \
2305   case X86::VMOVDQU64##Suffix##rm:                                             \
2306   case X86::VMOVDQU32##Suffix##rm:                                             \
2307   case X86::VMOVDQU16##Suffix##rm:                                             \
2308   case X86::VMOVDQU8##Suffix##rm:                                              \
2309   case X86::VMOVAPS##Suffix##rm:                                               \
2310   case X86::VMOVAPD##Suffix##rm:                                               \
2311   case X86::VMOVUPS##Suffix##rm:                                               \
2312   case X86::VMOVUPD##Suffix##rm:
2313 
2314 #define CASE_ALL_MOV_RM()                                                      \
2315   MOV_CASE(, )   /* SSE */                                                     \
2316   MOV_CASE(V, )  /* AVX-128 */                                                 \
2317   MOV_CASE(V, Y) /* AVX-256 */                                                 \
2318   MOV_AVX512_CASE(Z)                                                           \
2319   MOV_AVX512_CASE(Z256)                                                        \
2320   MOV_AVX512_CASE(Z128)
2321 
2322     // For loads from a constant pool to a vector register, print the constant
2323     // loaded.
2324     CASE_ALL_MOV_RM()
2325   case X86::VBROADCASTF128:
2326   case X86::VBROADCASTI128:
2327   case X86::VBROADCASTF32X4Z256rm:
2328   case X86::VBROADCASTF32X4rm:
2329   case X86::VBROADCASTF32X8rm:
2330   case X86::VBROADCASTF64X2Z128rm:
2331   case X86::VBROADCASTF64X2rm:
2332   case X86::VBROADCASTF64X4rm:
2333   case X86::VBROADCASTI32X4Z256rm:
2334   case X86::VBROADCASTI32X4rm:
2335   case X86::VBROADCASTI32X8rm:
2336   case X86::VBROADCASTI64X2Z128rm:
2337   case X86::VBROADCASTI64X2rm:
2338   case X86::VBROADCASTI64X4rm:
2339     if (!OutStreamer->isVerboseAsm())
2340       break;
2341     if (MI->getNumOperands() <= 4)
2342       break;
2343     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2344       int NumLanes = 1;
2345       // Override NumLanes for the broadcast instructions.
2346       switch (MI->getOpcode()) {
2347       case X86::VBROADCASTF128:        NumLanes = 2; break;
2348       case X86::VBROADCASTI128:        NumLanes = 2; break;
2349       case X86::VBROADCASTF32X4Z256rm: NumLanes = 2; break;
2350       case X86::VBROADCASTF32X4rm:     NumLanes = 4; break;
2351       case X86::VBROADCASTF32X8rm:     NumLanes = 2; break;
2352       case X86::VBROADCASTF64X2Z128rm: NumLanes = 2; break;
2353       case X86::VBROADCASTF64X2rm:     NumLanes = 4; break;
2354       case X86::VBROADCASTF64X4rm:     NumLanes = 2; break;
2355       case X86::VBROADCASTI32X4Z256rm: NumLanes = 2; break;
2356       case X86::VBROADCASTI32X4rm:     NumLanes = 4; break;
2357       case X86::VBROADCASTI32X8rm:     NumLanes = 2; break;
2358       case X86::VBROADCASTI64X2Z128rm: NumLanes = 2; break;
2359       case X86::VBROADCASTI64X2rm:     NumLanes = 4; break;
2360       case X86::VBROADCASTI64X4rm:     NumLanes = 2; break;
2361       }
2362 
2363       std::string Comment;
2364       raw_string_ostream CS(Comment);
2365       const MachineOperand &DstOp = MI->getOperand(0);
2366       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2367       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
2368         CS << "[";
2369         for (int l = 0; l != NumLanes; ++l) {
2370           for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements;
2371                ++i) {
2372             if (i != 0 || l != 0)
2373               CS << ",";
2374             if (CDS->getElementType()->isIntegerTy())
2375               printConstant(CDS->getElementAsAPInt(i), CS);
2376             else if (CDS->getElementType()->isHalfTy() ||
2377                      CDS->getElementType()->isFloatTy() ||
2378                      CDS->getElementType()->isDoubleTy())
2379               printConstant(CDS->getElementAsAPFloat(i), CS);
2380             else
2381               CS << "?";
2382           }
2383         }
2384         CS << "]";
2385         OutStreamer->AddComment(CS.str());
2386       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
2387         CS << "<";
2388         for (int l = 0; l != NumLanes; ++l) {
2389           for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands;
2390                ++i) {
2391             if (i != 0 || l != 0)
2392               CS << ",";
2393             printConstant(CV->getOperand(i), CS);
2394           }
2395         }
2396         CS << ">";
2397         OutStreamer->AddComment(CS.str());
2398       }
2399     }
2400     break;
2401   case X86::MOVDDUPrm:
2402   case X86::VMOVDDUPrm:
2403   case X86::VMOVDDUPZ128rm:
2404   case X86::VBROADCASTSSrm:
2405   case X86::VBROADCASTSSYrm:
2406   case X86::VBROADCASTSSZ128m:
2407   case X86::VBROADCASTSSZ256m:
2408   case X86::VBROADCASTSSZm:
2409   case X86::VBROADCASTSDYrm:
2410   case X86::VBROADCASTSDZ256m:
2411   case X86::VBROADCASTSDZm:
2412   case X86::VPBROADCASTBrm:
2413   case X86::VPBROADCASTBYrm:
2414   case X86::VPBROADCASTBZ128m:
2415   case X86::VPBROADCASTBZ256m:
2416   case X86::VPBROADCASTBZm:
2417   case X86::VPBROADCASTDrm:
2418   case X86::VPBROADCASTDYrm:
2419   case X86::VPBROADCASTDZ128m:
2420   case X86::VPBROADCASTDZ256m:
2421   case X86::VPBROADCASTDZm:
2422   case X86::VPBROADCASTQrm:
2423   case X86::VPBROADCASTQYrm:
2424   case X86::VPBROADCASTQZ128m:
2425   case X86::VPBROADCASTQZ256m:
2426   case X86::VPBROADCASTQZm:
2427   case X86::VPBROADCASTWrm:
2428   case X86::VPBROADCASTWYrm:
2429   case X86::VPBROADCASTWZ128m:
2430   case X86::VPBROADCASTWZ256m:
2431   case X86::VPBROADCASTWZm:
2432     if (!OutStreamer->isVerboseAsm())
2433       break;
2434     if (MI->getNumOperands() <= 4)
2435       break;
2436     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2437       int NumElts;
2438       switch (MI->getOpcode()) {
2439       default: llvm_unreachable("Invalid opcode");
2440       case X86::MOVDDUPrm:         NumElts = 2;  break;
2441       case X86::VMOVDDUPrm:        NumElts = 2;  break;
2442       case X86::VMOVDDUPZ128rm:    NumElts = 2;  break;
2443       case X86::VBROADCASTSSrm:    NumElts = 4;  break;
2444       case X86::VBROADCASTSSYrm:   NumElts = 8;  break;
2445       case X86::VBROADCASTSSZ128m: NumElts = 4;  break;
2446       case X86::VBROADCASTSSZ256m: NumElts = 8;  break;
2447       case X86::VBROADCASTSSZm:    NumElts = 16; break;
2448       case X86::VBROADCASTSDYrm:   NumElts = 4;  break;
2449       case X86::VBROADCASTSDZ256m: NumElts = 4;  break;
2450       case X86::VBROADCASTSDZm:    NumElts = 8;  break;
2451       case X86::VPBROADCASTBrm:    NumElts = 16; break;
2452       case X86::VPBROADCASTBYrm:   NumElts = 32; break;
2453       case X86::VPBROADCASTBZ128m: NumElts = 16; break;
2454       case X86::VPBROADCASTBZ256m: NumElts = 32; break;
2455       case X86::VPBROADCASTBZm:    NumElts = 64; break;
2456       case X86::VPBROADCASTDrm:    NumElts = 4;  break;
2457       case X86::VPBROADCASTDYrm:   NumElts = 8;  break;
2458       case X86::VPBROADCASTDZ128m: NumElts = 4;  break;
2459       case X86::VPBROADCASTDZ256m: NumElts = 8;  break;
2460       case X86::VPBROADCASTDZm:    NumElts = 16; break;
2461       case X86::VPBROADCASTQrm:    NumElts = 2;  break;
2462       case X86::VPBROADCASTQYrm:   NumElts = 4;  break;
2463       case X86::VPBROADCASTQZ128m: NumElts = 2;  break;
2464       case X86::VPBROADCASTQZ256m: NumElts = 4;  break;
2465       case X86::VPBROADCASTQZm:    NumElts = 8;  break;
2466       case X86::VPBROADCASTWrm:    NumElts = 8;  break;
2467       case X86::VPBROADCASTWYrm:   NumElts = 16; break;
2468       case X86::VPBROADCASTWZ128m: NumElts = 8;  break;
2469       case X86::VPBROADCASTWZ256m: NumElts = 16; break;
2470       case X86::VPBROADCASTWZm:    NumElts = 32; break;
2471       }
2472 
2473       std::string Comment;
2474       raw_string_ostream CS(Comment);
2475       const MachineOperand &DstOp = MI->getOperand(0);
2476       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2477       CS << "[";
2478       for (int i = 0; i != NumElts; ++i) {
2479         if (i != 0)
2480           CS << ",";
2481         printConstant(C, CS);
2482       }
2483       CS << "]";
2484       OutStreamer->AddComment(CS.str());
2485     }
2486   }
2487 
2488   MCInst TmpInst;
2489   MCInstLowering.Lower(MI, TmpInst);
2490 
2491   // Stackmap shadows cannot include branch targets, so we can count the bytes
2492   // in a call towards the shadow, but must ensure that the no thread returns
2493   // in to the stackmap shadow.  The only way to achieve this is if the call
2494   // is at the end of the shadow.
2495   if (MI->isCall()) {
2496     // Count then size of the call towards the shadow
2497     SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
2498     // Then flush the shadow so that we fill with nops before the call, not
2499     // after it.
2500     SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
2501     // Then emit the call
2502     OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
2503     return;
2504   }
2505 
2506   EmitAndCountInstruction(TmpInst);
2507 }
2508