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