xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86InstrInfo.cpp (revision 069ac18495ad8fde2748bc94b0f80a50250bb01d)
1 //===-- X86InstrInfo.cpp - X86 Instruction Information --------------------===//
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 the X86 implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86InstrInfo.h"
14 #include "X86.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrFoldTables.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Sequence.h"
22 #include "llvm/CodeGen/LiveIntervals.h"
23 #include "llvm/CodeGen/LivePhysRegs.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineCombinerPattern.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/StackMaps.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCInst.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include <optional>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "x86-instr-info"
52 
53 #define GET_INSTRINFO_CTOR_DTOR
54 #include "X86GenInstrInfo.inc"
55 
56 static cl::opt<bool>
57     NoFusing("disable-spill-fusing",
58              cl::desc("Disable fusing of spill code into instructions"),
59              cl::Hidden);
60 static cl::opt<bool>
61 PrintFailedFusing("print-failed-fuse-candidates",
62                   cl::desc("Print instructions that the allocator wants to"
63                            " fuse, but the X86 backend currently can't"),
64                   cl::Hidden);
65 static cl::opt<bool>
66 ReMatPICStubLoad("remat-pic-stub-load",
67                  cl::desc("Re-materialize load from stub in PIC mode"),
68                  cl::init(false), cl::Hidden);
69 static cl::opt<unsigned>
70 PartialRegUpdateClearance("partial-reg-update-clearance",
71                           cl::desc("Clearance between two register writes "
72                                    "for inserting XOR to avoid partial "
73                                    "register update"),
74                           cl::init(64), cl::Hidden);
75 static cl::opt<unsigned>
76 UndefRegClearance("undef-reg-clearance",
77                   cl::desc("How many idle instructions we would like before "
78                            "certain undef register reads"),
79                   cl::init(128), cl::Hidden);
80 
81 
82 // Pin the vtable to this file.
83 void X86InstrInfo::anchor() {}
84 
85 X86InstrInfo::X86InstrInfo(X86Subtarget &STI)
86     : X86GenInstrInfo((STI.isTarget64BitLP64() ? X86::ADJCALLSTACKDOWN64
87                                                : X86::ADJCALLSTACKDOWN32),
88                       (STI.isTarget64BitLP64() ? X86::ADJCALLSTACKUP64
89                                                : X86::ADJCALLSTACKUP32),
90                       X86::CATCHRET,
91                       (STI.is64Bit() ? X86::RET64 : X86::RET32)),
92       Subtarget(STI), RI(STI.getTargetTriple()) {
93 }
94 
95 bool
96 X86InstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
97                                     Register &SrcReg, Register &DstReg,
98                                     unsigned &SubIdx) const {
99   switch (MI.getOpcode()) {
100   default: break;
101   case X86::MOVSX16rr8:
102   case X86::MOVZX16rr8:
103   case X86::MOVSX32rr8:
104   case X86::MOVZX32rr8:
105   case X86::MOVSX64rr8:
106     if (!Subtarget.is64Bit())
107       // It's not always legal to reference the low 8-bit of the larger
108       // register in 32-bit mode.
109       return false;
110     [[fallthrough]];
111   case X86::MOVSX32rr16:
112   case X86::MOVZX32rr16:
113   case X86::MOVSX64rr16:
114   case X86::MOVSX64rr32: {
115     if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
116       // Be conservative.
117       return false;
118     SrcReg = MI.getOperand(1).getReg();
119     DstReg = MI.getOperand(0).getReg();
120     switch (MI.getOpcode()) {
121     default: llvm_unreachable("Unreachable!");
122     case X86::MOVSX16rr8:
123     case X86::MOVZX16rr8:
124     case X86::MOVSX32rr8:
125     case X86::MOVZX32rr8:
126     case X86::MOVSX64rr8:
127       SubIdx = X86::sub_8bit;
128       break;
129     case X86::MOVSX32rr16:
130     case X86::MOVZX32rr16:
131     case X86::MOVSX64rr16:
132       SubIdx = X86::sub_16bit;
133       break;
134     case X86::MOVSX64rr32:
135       SubIdx = X86::sub_32bit;
136       break;
137     }
138     return true;
139   }
140   }
141   return false;
142 }
143 
144 bool X86InstrInfo::isDataInvariant(MachineInstr &MI) {
145   if (MI.mayLoad() || MI.mayStore())
146     return false;
147 
148   // Some target-independent operations that trivially lower to data-invariant
149   // instructions.
150   if (MI.isCopyLike() || MI.isInsertSubreg())
151     return true;
152 
153   unsigned Opcode = MI.getOpcode();
154   using namespace X86;
155   // On x86 it is believed that imul is constant time w.r.t. the loaded data.
156   // However, they set flags and are perhaps the most surprisingly constant
157   // time operations so we call them out here separately.
158   if (isIMUL(Opcode))
159     return true;
160   // Bit scanning and counting instructions that are somewhat surprisingly
161   // constant time as they scan across bits and do other fairly complex
162   // operations like popcnt, but are believed to be constant time on x86.
163   // However, these set flags.
164   if (isBSF(Opcode) || isBSR(Opcode) || isLZCNT(Opcode) || isPOPCNT(Opcode) ||
165       isTZCNT(Opcode))
166     return true;
167   // Bit manipulation instructions are effectively combinations of basic
168   // arithmetic ops, and should still execute in constant time. These also
169   // set flags.
170   if (isBLCFILL(Opcode) || isBLCI(Opcode) || isBLCIC(Opcode) ||
171       isBLCMSK(Opcode) || isBLCS(Opcode) || isBLSFILL(Opcode) ||
172       isBLSI(Opcode) || isBLSIC(Opcode) || isBLSMSK(Opcode) || isBLSR(Opcode) ||
173       isTZMSK(Opcode))
174     return true;
175   // Bit extracting and clearing instructions should execute in constant time,
176   // and set flags.
177   if (isBEXTR(Opcode) || isBZHI(Opcode))
178     return true;
179   // Shift and rotate.
180   if (isROL(Opcode) || isROR(Opcode) || isSAR(Opcode) || isSHL(Opcode) ||
181       isSHR(Opcode) || isSHLD(Opcode) || isSHRD(Opcode))
182     return true;
183   // Basic arithmetic is constant time on the input but does set flags.
184   if (isADC(Opcode) || isADD(Opcode) || isAND(Opcode) || isOR(Opcode) ||
185       isSBB(Opcode) || isSUB(Opcode) || isXOR(Opcode))
186     return true;
187   // Arithmetic with just 32-bit and 64-bit variants and no immediates.
188   if (isADCX(Opcode) || isADOX(Opcode) || isANDN(Opcode))
189     return true;
190   // Unary arithmetic operations.
191   if (isDEC(Opcode) || isINC(Opcode) || isNEG(Opcode))
192     return true;
193   // Unlike other arithmetic, NOT doesn't set EFLAGS.
194   if (isNOT(Opcode))
195     return true;
196   // Various move instructions used to zero or sign extend things. Note that we
197   // intentionally don't support the _NOREX variants as we can't handle that
198   // register constraint anyways.
199   if (isMOVSX(Opcode) || isMOVZX(Opcode) || isMOVSXD(Opcode) || isMOV(Opcode))
200     return true;
201   // Arithmetic instructions that are both constant time and don't set flags.
202   if (isRORX(Opcode) || isSARX(Opcode) || isSHLX(Opcode) || isSHRX(Opcode))
203     return true;
204   // LEA doesn't actually access memory, and its arithmetic is constant time.
205   if (isLEA(Opcode))
206     return true;
207   // By default, assume that the instruction is not data invariant.
208   return false;
209 }
210 
211 bool X86InstrInfo::isDataInvariantLoad(MachineInstr &MI) {
212   switch (MI.getOpcode()) {
213   default:
214     // By default, assume that the load will immediately leak.
215     return false;
216 
217   // On x86 it is believed that imul is constant time w.r.t. the loaded data.
218   // However, they set flags and are perhaps the most surprisingly constant
219   // time operations so we call them out here separately.
220   case X86::IMUL16rm:
221   case X86::IMUL16rmi:
222   case X86::IMUL32rm:
223   case X86::IMUL32rmi:
224   case X86::IMUL64rm:
225   case X86::IMUL64rmi32:
226 
227   // Bit scanning and counting instructions that are somewhat surprisingly
228   // constant time as they scan across bits and do other fairly complex
229   // operations like popcnt, but are believed to be constant time on x86.
230   // However, these set flags.
231   case X86::BSF16rm:
232   case X86::BSF32rm:
233   case X86::BSF64rm:
234   case X86::BSR16rm:
235   case X86::BSR32rm:
236   case X86::BSR64rm:
237   case X86::LZCNT16rm:
238   case X86::LZCNT32rm:
239   case X86::LZCNT64rm:
240   case X86::POPCNT16rm:
241   case X86::POPCNT32rm:
242   case X86::POPCNT64rm:
243   case X86::TZCNT16rm:
244   case X86::TZCNT32rm:
245   case X86::TZCNT64rm:
246 
247   // Bit manipulation instructions are effectively combinations of basic
248   // arithmetic ops, and should still execute in constant time. These also
249   // set flags.
250   case X86::BLCFILL32rm:
251   case X86::BLCFILL64rm:
252   case X86::BLCI32rm:
253   case X86::BLCI64rm:
254   case X86::BLCIC32rm:
255   case X86::BLCIC64rm:
256   case X86::BLCMSK32rm:
257   case X86::BLCMSK64rm:
258   case X86::BLCS32rm:
259   case X86::BLCS64rm:
260   case X86::BLSFILL32rm:
261   case X86::BLSFILL64rm:
262   case X86::BLSI32rm:
263   case X86::BLSI64rm:
264   case X86::BLSIC32rm:
265   case X86::BLSIC64rm:
266   case X86::BLSMSK32rm:
267   case X86::BLSMSK64rm:
268   case X86::BLSR32rm:
269   case X86::BLSR64rm:
270   case X86::TZMSK32rm:
271   case X86::TZMSK64rm:
272 
273   // Bit extracting and clearing instructions should execute in constant time,
274   // and set flags.
275   case X86::BEXTR32rm:
276   case X86::BEXTR64rm:
277   case X86::BEXTRI32mi:
278   case X86::BEXTRI64mi:
279   case X86::BZHI32rm:
280   case X86::BZHI64rm:
281 
282   // Basic arithmetic is constant time on the input but does set flags.
283   case X86::ADC8rm:
284   case X86::ADC16rm:
285   case X86::ADC32rm:
286   case X86::ADC64rm:
287   case X86::ADCX32rm:
288   case X86::ADCX64rm:
289   case X86::ADD8rm:
290   case X86::ADD16rm:
291   case X86::ADD32rm:
292   case X86::ADD64rm:
293   case X86::ADOX32rm:
294   case X86::ADOX64rm:
295   case X86::AND8rm:
296   case X86::AND16rm:
297   case X86::AND32rm:
298   case X86::AND64rm:
299   case X86::ANDN32rm:
300   case X86::ANDN64rm:
301   case X86::OR8rm:
302   case X86::OR16rm:
303   case X86::OR32rm:
304   case X86::OR64rm:
305   case X86::SBB8rm:
306   case X86::SBB16rm:
307   case X86::SBB32rm:
308   case X86::SBB64rm:
309   case X86::SUB8rm:
310   case X86::SUB16rm:
311   case X86::SUB32rm:
312   case X86::SUB64rm:
313   case X86::XOR8rm:
314   case X86::XOR16rm:
315   case X86::XOR32rm:
316   case X86::XOR64rm:
317 
318   // Integer multiply w/o affecting flags is still believed to be constant
319   // time on x86. Called out separately as this is among the most surprising
320   // instructions to exhibit that behavior.
321   case X86::MULX32rm:
322   case X86::MULX64rm:
323 
324   // Arithmetic instructions that are both constant time and don't set flags.
325   case X86::RORX32mi:
326   case X86::RORX64mi:
327   case X86::SARX32rm:
328   case X86::SARX64rm:
329   case X86::SHLX32rm:
330   case X86::SHLX64rm:
331   case X86::SHRX32rm:
332   case X86::SHRX64rm:
333 
334   // Conversions are believed to be constant time and don't set flags.
335   case X86::CVTTSD2SI64rm:
336   case X86::VCVTTSD2SI64rm:
337   case X86::VCVTTSD2SI64Zrm:
338   case X86::CVTTSD2SIrm:
339   case X86::VCVTTSD2SIrm:
340   case X86::VCVTTSD2SIZrm:
341   case X86::CVTTSS2SI64rm:
342   case X86::VCVTTSS2SI64rm:
343   case X86::VCVTTSS2SI64Zrm:
344   case X86::CVTTSS2SIrm:
345   case X86::VCVTTSS2SIrm:
346   case X86::VCVTTSS2SIZrm:
347   case X86::CVTSI2SDrm:
348   case X86::VCVTSI2SDrm:
349   case X86::VCVTSI2SDZrm:
350   case X86::CVTSI2SSrm:
351   case X86::VCVTSI2SSrm:
352   case X86::VCVTSI2SSZrm:
353   case X86::CVTSI642SDrm:
354   case X86::VCVTSI642SDrm:
355   case X86::VCVTSI642SDZrm:
356   case X86::CVTSI642SSrm:
357   case X86::VCVTSI642SSrm:
358   case X86::VCVTSI642SSZrm:
359   case X86::CVTSS2SDrm:
360   case X86::VCVTSS2SDrm:
361   case X86::VCVTSS2SDZrm:
362   case X86::CVTSD2SSrm:
363   case X86::VCVTSD2SSrm:
364   case X86::VCVTSD2SSZrm:
365   // AVX512 added unsigned integer conversions.
366   case X86::VCVTTSD2USI64Zrm:
367   case X86::VCVTTSD2USIZrm:
368   case X86::VCVTTSS2USI64Zrm:
369   case X86::VCVTTSS2USIZrm:
370   case X86::VCVTUSI2SDZrm:
371   case X86::VCVTUSI642SDZrm:
372   case X86::VCVTUSI2SSZrm:
373   case X86::VCVTUSI642SSZrm:
374 
375   // Loads to register don't set flags.
376   case X86::MOV8rm:
377   case X86::MOV8rm_NOREX:
378   case X86::MOV16rm:
379   case X86::MOV32rm:
380   case X86::MOV64rm:
381   case X86::MOVSX16rm8:
382   case X86::MOVSX32rm16:
383   case X86::MOVSX32rm8:
384   case X86::MOVSX32rm8_NOREX:
385   case X86::MOVSX64rm16:
386   case X86::MOVSX64rm32:
387   case X86::MOVSX64rm8:
388   case X86::MOVZX16rm8:
389   case X86::MOVZX32rm16:
390   case X86::MOVZX32rm8:
391   case X86::MOVZX32rm8_NOREX:
392   case X86::MOVZX64rm16:
393   case X86::MOVZX64rm8:
394     return true;
395   }
396 }
397 
398 int X86InstrInfo::getSPAdjust(const MachineInstr &MI) const {
399   const MachineFunction *MF = MI.getParent()->getParent();
400   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
401 
402   if (isFrameInstr(MI)) {
403     int SPAdj = alignTo(getFrameSize(MI), TFI->getStackAlign());
404     SPAdj -= getFrameAdjustment(MI);
405     if (!isFrameSetup(MI))
406       SPAdj = -SPAdj;
407     return SPAdj;
408   }
409 
410   // To know whether a call adjusts the stack, we need information
411   // that is bound to the following ADJCALLSTACKUP pseudo.
412   // Look for the next ADJCALLSTACKUP that follows the call.
413   if (MI.isCall()) {
414     const MachineBasicBlock *MBB = MI.getParent();
415     auto I = ++MachineBasicBlock::const_iterator(MI);
416     for (auto E = MBB->end(); I != E; ++I) {
417       if (I->getOpcode() == getCallFrameDestroyOpcode() ||
418           I->isCall())
419         break;
420     }
421 
422     // If we could not find a frame destroy opcode, then it has already
423     // been simplified, so we don't care.
424     if (I->getOpcode() != getCallFrameDestroyOpcode())
425       return 0;
426 
427     return -(I->getOperand(1).getImm());
428   }
429 
430   // Currently handle only PUSHes we can reasonably expect to see
431   // in call sequences
432   switch (MI.getOpcode()) {
433   default:
434     return 0;
435   case X86::PUSH32r:
436   case X86::PUSH32rmm:
437   case X86::PUSH32rmr:
438   case X86::PUSH32i:
439     return 4;
440   case X86::PUSH64r:
441   case X86::PUSH64rmm:
442   case X86::PUSH64rmr:
443   case X86::PUSH64i32:
444     return 8;
445   }
446 }
447 
448 /// Return true and the FrameIndex if the specified
449 /// operand and follow operands form a reference to the stack frame.
450 bool X86InstrInfo::isFrameOperand(const MachineInstr &MI, unsigned int Op,
451                                   int &FrameIndex) const {
452   if (MI.getOperand(Op + X86::AddrBaseReg).isFI() &&
453       MI.getOperand(Op + X86::AddrScaleAmt).isImm() &&
454       MI.getOperand(Op + X86::AddrIndexReg).isReg() &&
455       MI.getOperand(Op + X86::AddrDisp).isImm() &&
456       MI.getOperand(Op + X86::AddrScaleAmt).getImm() == 1 &&
457       MI.getOperand(Op + X86::AddrIndexReg).getReg() == 0 &&
458       MI.getOperand(Op + X86::AddrDisp).getImm() == 0) {
459     FrameIndex = MI.getOperand(Op + X86::AddrBaseReg).getIndex();
460     return true;
461   }
462   return false;
463 }
464 
465 static bool isFrameLoadOpcode(int Opcode, unsigned &MemBytes) {
466   switch (Opcode) {
467   default:
468     return false;
469   case X86::MOV8rm:
470   case X86::KMOVBkm:
471     MemBytes = 1;
472     return true;
473   case X86::MOV16rm:
474   case X86::KMOVWkm:
475   case X86::VMOVSHZrm:
476   case X86::VMOVSHZrm_alt:
477     MemBytes = 2;
478     return true;
479   case X86::MOV32rm:
480   case X86::MOVSSrm:
481   case X86::MOVSSrm_alt:
482   case X86::VMOVSSrm:
483   case X86::VMOVSSrm_alt:
484   case X86::VMOVSSZrm:
485   case X86::VMOVSSZrm_alt:
486   case X86::KMOVDkm:
487     MemBytes = 4;
488     return true;
489   case X86::MOV64rm:
490   case X86::LD_Fp64m:
491   case X86::MOVSDrm:
492   case X86::MOVSDrm_alt:
493   case X86::VMOVSDrm:
494   case X86::VMOVSDrm_alt:
495   case X86::VMOVSDZrm:
496   case X86::VMOVSDZrm_alt:
497   case X86::MMX_MOVD64rm:
498   case X86::MMX_MOVQ64rm:
499   case X86::KMOVQkm:
500     MemBytes = 8;
501     return true;
502   case X86::MOVAPSrm:
503   case X86::MOVUPSrm:
504   case X86::MOVAPDrm:
505   case X86::MOVUPDrm:
506   case X86::MOVDQArm:
507   case X86::MOVDQUrm:
508   case X86::VMOVAPSrm:
509   case X86::VMOVUPSrm:
510   case X86::VMOVAPDrm:
511   case X86::VMOVUPDrm:
512   case X86::VMOVDQArm:
513   case X86::VMOVDQUrm:
514   case X86::VMOVAPSZ128rm:
515   case X86::VMOVUPSZ128rm:
516   case X86::VMOVAPSZ128rm_NOVLX:
517   case X86::VMOVUPSZ128rm_NOVLX:
518   case X86::VMOVAPDZ128rm:
519   case X86::VMOVUPDZ128rm:
520   case X86::VMOVDQU8Z128rm:
521   case X86::VMOVDQU16Z128rm:
522   case X86::VMOVDQA32Z128rm:
523   case X86::VMOVDQU32Z128rm:
524   case X86::VMOVDQA64Z128rm:
525   case X86::VMOVDQU64Z128rm:
526     MemBytes = 16;
527     return true;
528   case X86::VMOVAPSYrm:
529   case X86::VMOVUPSYrm:
530   case X86::VMOVAPDYrm:
531   case X86::VMOVUPDYrm:
532   case X86::VMOVDQAYrm:
533   case X86::VMOVDQUYrm:
534   case X86::VMOVAPSZ256rm:
535   case X86::VMOVUPSZ256rm:
536   case X86::VMOVAPSZ256rm_NOVLX:
537   case X86::VMOVUPSZ256rm_NOVLX:
538   case X86::VMOVAPDZ256rm:
539   case X86::VMOVUPDZ256rm:
540   case X86::VMOVDQU8Z256rm:
541   case X86::VMOVDQU16Z256rm:
542   case X86::VMOVDQA32Z256rm:
543   case X86::VMOVDQU32Z256rm:
544   case X86::VMOVDQA64Z256rm:
545   case X86::VMOVDQU64Z256rm:
546     MemBytes = 32;
547     return true;
548   case X86::VMOVAPSZrm:
549   case X86::VMOVUPSZrm:
550   case X86::VMOVAPDZrm:
551   case X86::VMOVUPDZrm:
552   case X86::VMOVDQU8Zrm:
553   case X86::VMOVDQU16Zrm:
554   case X86::VMOVDQA32Zrm:
555   case X86::VMOVDQU32Zrm:
556   case X86::VMOVDQA64Zrm:
557   case X86::VMOVDQU64Zrm:
558     MemBytes = 64;
559     return true;
560   }
561 }
562 
563 static bool isFrameStoreOpcode(int Opcode, unsigned &MemBytes) {
564   switch (Opcode) {
565   default:
566     return false;
567   case X86::MOV8mr:
568   case X86::KMOVBmk:
569     MemBytes = 1;
570     return true;
571   case X86::MOV16mr:
572   case X86::KMOVWmk:
573   case X86::VMOVSHZmr:
574     MemBytes = 2;
575     return true;
576   case X86::MOV32mr:
577   case X86::MOVSSmr:
578   case X86::VMOVSSmr:
579   case X86::VMOVSSZmr:
580   case X86::KMOVDmk:
581     MemBytes = 4;
582     return true;
583   case X86::MOV64mr:
584   case X86::ST_FpP64m:
585   case X86::MOVSDmr:
586   case X86::VMOVSDmr:
587   case X86::VMOVSDZmr:
588   case X86::MMX_MOVD64mr:
589   case X86::MMX_MOVQ64mr:
590   case X86::MMX_MOVNTQmr:
591   case X86::KMOVQmk:
592     MemBytes = 8;
593     return true;
594   case X86::MOVAPSmr:
595   case X86::MOVUPSmr:
596   case X86::MOVAPDmr:
597   case X86::MOVUPDmr:
598   case X86::MOVDQAmr:
599   case X86::MOVDQUmr:
600   case X86::VMOVAPSmr:
601   case X86::VMOVUPSmr:
602   case X86::VMOVAPDmr:
603   case X86::VMOVUPDmr:
604   case X86::VMOVDQAmr:
605   case X86::VMOVDQUmr:
606   case X86::VMOVUPSZ128mr:
607   case X86::VMOVAPSZ128mr:
608   case X86::VMOVUPSZ128mr_NOVLX:
609   case X86::VMOVAPSZ128mr_NOVLX:
610   case X86::VMOVUPDZ128mr:
611   case X86::VMOVAPDZ128mr:
612   case X86::VMOVDQA32Z128mr:
613   case X86::VMOVDQU32Z128mr:
614   case X86::VMOVDQA64Z128mr:
615   case X86::VMOVDQU64Z128mr:
616   case X86::VMOVDQU8Z128mr:
617   case X86::VMOVDQU16Z128mr:
618     MemBytes = 16;
619     return true;
620   case X86::VMOVUPSYmr:
621   case X86::VMOVAPSYmr:
622   case X86::VMOVUPDYmr:
623   case X86::VMOVAPDYmr:
624   case X86::VMOVDQUYmr:
625   case X86::VMOVDQAYmr:
626   case X86::VMOVUPSZ256mr:
627   case X86::VMOVAPSZ256mr:
628   case X86::VMOVUPSZ256mr_NOVLX:
629   case X86::VMOVAPSZ256mr_NOVLX:
630   case X86::VMOVUPDZ256mr:
631   case X86::VMOVAPDZ256mr:
632   case X86::VMOVDQU8Z256mr:
633   case X86::VMOVDQU16Z256mr:
634   case X86::VMOVDQA32Z256mr:
635   case X86::VMOVDQU32Z256mr:
636   case X86::VMOVDQA64Z256mr:
637   case X86::VMOVDQU64Z256mr:
638     MemBytes = 32;
639     return true;
640   case X86::VMOVUPSZmr:
641   case X86::VMOVAPSZmr:
642   case X86::VMOVUPDZmr:
643   case X86::VMOVAPDZmr:
644   case X86::VMOVDQU8Zmr:
645   case X86::VMOVDQU16Zmr:
646   case X86::VMOVDQA32Zmr:
647   case X86::VMOVDQU32Zmr:
648   case X86::VMOVDQA64Zmr:
649   case X86::VMOVDQU64Zmr:
650     MemBytes = 64;
651     return true;
652   }
653   return false;
654 }
655 
656 unsigned X86InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
657                                            int &FrameIndex) const {
658   unsigned Dummy;
659   return X86InstrInfo::isLoadFromStackSlot(MI, FrameIndex, Dummy);
660 }
661 
662 unsigned X86InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
663                                            int &FrameIndex,
664                                            unsigned &MemBytes) const {
665   if (isFrameLoadOpcode(MI.getOpcode(), MemBytes))
666     if (MI.getOperand(0).getSubReg() == 0 && isFrameOperand(MI, 1, FrameIndex))
667       return MI.getOperand(0).getReg();
668   return 0;
669 }
670 
671 unsigned X86InstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
672                                                  int &FrameIndex) const {
673   unsigned Dummy;
674   if (isFrameLoadOpcode(MI.getOpcode(), Dummy)) {
675     unsigned Reg;
676     if ((Reg = isLoadFromStackSlot(MI, FrameIndex)))
677       return Reg;
678     // Check for post-frame index elimination operations
679     SmallVector<const MachineMemOperand *, 1> Accesses;
680     if (hasLoadFromStackSlot(MI, Accesses)) {
681       FrameIndex =
682           cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
683               ->getFrameIndex();
684       return MI.getOperand(0).getReg();
685     }
686   }
687   return 0;
688 }
689 
690 unsigned X86InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
691                                           int &FrameIndex) const {
692   unsigned Dummy;
693   return X86InstrInfo::isStoreToStackSlot(MI, FrameIndex, Dummy);
694 }
695 
696 unsigned X86InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
697                                           int &FrameIndex,
698                                           unsigned &MemBytes) const {
699   if (isFrameStoreOpcode(MI.getOpcode(), MemBytes))
700     if (MI.getOperand(X86::AddrNumOperands).getSubReg() == 0 &&
701         isFrameOperand(MI, 0, FrameIndex))
702       return MI.getOperand(X86::AddrNumOperands).getReg();
703   return 0;
704 }
705 
706 unsigned X86InstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
707                                                 int &FrameIndex) const {
708   unsigned Dummy;
709   if (isFrameStoreOpcode(MI.getOpcode(), Dummy)) {
710     unsigned Reg;
711     if ((Reg = isStoreToStackSlot(MI, FrameIndex)))
712       return Reg;
713     // Check for post-frame index elimination operations
714     SmallVector<const MachineMemOperand *, 1> Accesses;
715     if (hasStoreToStackSlot(MI, Accesses)) {
716       FrameIndex =
717           cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
718               ->getFrameIndex();
719       return MI.getOperand(X86::AddrNumOperands).getReg();
720     }
721   }
722   return 0;
723 }
724 
725 /// Return true if register is PIC base; i.e.g defined by X86::MOVPC32r.
726 static bool regIsPICBase(Register BaseReg, const MachineRegisterInfo &MRI) {
727   // Don't waste compile time scanning use-def chains of physregs.
728   if (!BaseReg.isVirtual())
729     return false;
730   bool isPICBase = false;
731   for (MachineRegisterInfo::def_instr_iterator I = MRI.def_instr_begin(BaseReg),
732          E = MRI.def_instr_end(); I != E; ++I) {
733     MachineInstr *DefMI = &*I;
734     if (DefMI->getOpcode() != X86::MOVPC32r)
735       return false;
736     assert(!isPICBase && "More than one PIC base?");
737     isPICBase = true;
738   }
739   return isPICBase;
740 }
741 
742 bool X86InstrInfo::isReallyTriviallyReMaterializable(
743     const MachineInstr &MI) const {
744   switch (MI.getOpcode()) {
745   default:
746     // This function should only be called for opcodes with the ReMaterializable
747     // flag set.
748     llvm_unreachable("Unknown rematerializable operation!");
749     break;
750 
751   case X86::LOAD_STACK_GUARD:
752   case X86::AVX1_SETALLONES:
753   case X86::AVX2_SETALLONES:
754   case X86::AVX512_128_SET0:
755   case X86::AVX512_256_SET0:
756   case X86::AVX512_512_SET0:
757   case X86::AVX512_512_SETALLONES:
758   case X86::AVX512_FsFLD0SD:
759   case X86::AVX512_FsFLD0SH:
760   case X86::AVX512_FsFLD0SS:
761   case X86::AVX512_FsFLD0F128:
762   case X86::AVX_SET0:
763   case X86::FsFLD0SD:
764   case X86::FsFLD0SS:
765   case X86::FsFLD0SH:
766   case X86::FsFLD0F128:
767   case X86::KSET0D:
768   case X86::KSET0Q:
769   case X86::KSET0W:
770   case X86::KSET1D:
771   case X86::KSET1Q:
772   case X86::KSET1W:
773   case X86::MMX_SET0:
774   case X86::MOV32ImmSExti8:
775   case X86::MOV32r0:
776   case X86::MOV32r1:
777   case X86::MOV32r_1:
778   case X86::MOV32ri64:
779   case X86::MOV64ImmSExti8:
780   case X86::V_SET0:
781   case X86::V_SETALLONES:
782   case X86::MOV16ri:
783   case X86::MOV32ri:
784   case X86::MOV64ri:
785   case X86::MOV64ri32:
786   case X86::MOV8ri:
787   case X86::PTILEZEROV:
788     return true;
789 
790   case X86::MOV8rm:
791   case X86::MOV8rm_NOREX:
792   case X86::MOV16rm:
793   case X86::MOV32rm:
794   case X86::MOV64rm:
795   case X86::MOVSSrm:
796   case X86::MOVSSrm_alt:
797   case X86::MOVSDrm:
798   case X86::MOVSDrm_alt:
799   case X86::MOVAPSrm:
800   case X86::MOVUPSrm:
801   case X86::MOVAPDrm:
802   case X86::MOVUPDrm:
803   case X86::MOVDQArm:
804   case X86::MOVDQUrm:
805   case X86::VMOVSSrm:
806   case X86::VMOVSSrm_alt:
807   case X86::VMOVSDrm:
808   case X86::VMOVSDrm_alt:
809   case X86::VMOVAPSrm:
810   case X86::VMOVUPSrm:
811   case X86::VMOVAPDrm:
812   case X86::VMOVUPDrm:
813   case X86::VMOVDQArm:
814   case X86::VMOVDQUrm:
815   case X86::VMOVAPSYrm:
816   case X86::VMOVUPSYrm:
817   case X86::VMOVAPDYrm:
818   case X86::VMOVUPDYrm:
819   case X86::VMOVDQAYrm:
820   case X86::VMOVDQUYrm:
821   case X86::MMX_MOVD64rm:
822   case X86::MMX_MOVQ64rm:
823   // AVX-512
824   case X86::VMOVSSZrm:
825   case X86::VMOVSSZrm_alt:
826   case X86::VMOVSDZrm:
827   case X86::VMOVSDZrm_alt:
828   case X86::VMOVSHZrm:
829   case X86::VMOVSHZrm_alt:
830   case X86::VMOVAPDZ128rm:
831   case X86::VMOVAPDZ256rm:
832   case X86::VMOVAPDZrm:
833   case X86::VMOVAPSZ128rm:
834   case X86::VMOVAPSZ256rm:
835   case X86::VMOVAPSZ128rm_NOVLX:
836   case X86::VMOVAPSZ256rm_NOVLX:
837   case X86::VMOVAPSZrm:
838   case X86::VMOVDQA32Z128rm:
839   case X86::VMOVDQA32Z256rm:
840   case X86::VMOVDQA32Zrm:
841   case X86::VMOVDQA64Z128rm:
842   case X86::VMOVDQA64Z256rm:
843   case X86::VMOVDQA64Zrm:
844   case X86::VMOVDQU16Z128rm:
845   case X86::VMOVDQU16Z256rm:
846   case X86::VMOVDQU16Zrm:
847   case X86::VMOVDQU32Z128rm:
848   case X86::VMOVDQU32Z256rm:
849   case X86::VMOVDQU32Zrm:
850   case X86::VMOVDQU64Z128rm:
851   case X86::VMOVDQU64Z256rm:
852   case X86::VMOVDQU64Zrm:
853   case X86::VMOVDQU8Z128rm:
854   case X86::VMOVDQU8Z256rm:
855   case X86::VMOVDQU8Zrm:
856   case X86::VMOVUPDZ128rm:
857   case X86::VMOVUPDZ256rm:
858   case X86::VMOVUPDZrm:
859   case X86::VMOVUPSZ128rm:
860   case X86::VMOVUPSZ256rm:
861   case X86::VMOVUPSZ128rm_NOVLX:
862   case X86::VMOVUPSZ256rm_NOVLX:
863   case X86::VMOVUPSZrm: {
864     // Loads from constant pools are trivially rematerializable.
865     if (MI.getOperand(1 + X86::AddrBaseReg).isReg() &&
866         MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
867         MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
868         MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
869         MI.isDereferenceableInvariantLoad()) {
870       Register BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
871       if (BaseReg == 0 || BaseReg == X86::RIP)
872         return true;
873       // Allow re-materialization of PIC load.
874       if (!ReMatPICStubLoad && MI.getOperand(1 + X86::AddrDisp).isGlobal())
875         return false;
876       const MachineFunction &MF = *MI.getParent()->getParent();
877       const MachineRegisterInfo &MRI = MF.getRegInfo();
878       return regIsPICBase(BaseReg, MRI);
879     }
880     return false;
881   }
882 
883   case X86::LEA32r:
884   case X86::LEA64r: {
885     if (MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
886         MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
887         MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
888         !MI.getOperand(1 + X86::AddrDisp).isReg()) {
889       // lea fi#, lea GV, etc. are all rematerializable.
890       if (!MI.getOperand(1 + X86::AddrBaseReg).isReg())
891         return true;
892       Register BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
893       if (BaseReg == 0)
894         return true;
895       // Allow re-materialization of lea PICBase + x.
896       const MachineFunction &MF = *MI.getParent()->getParent();
897       const MachineRegisterInfo &MRI = MF.getRegInfo();
898       return regIsPICBase(BaseReg, MRI);
899     }
900     return false;
901   }
902   }
903 }
904 
905 void X86InstrInfo::reMaterialize(MachineBasicBlock &MBB,
906                                  MachineBasicBlock::iterator I,
907                                  Register DestReg, unsigned SubIdx,
908                                  const MachineInstr &Orig,
909                                  const TargetRegisterInfo &TRI) const {
910   bool ClobbersEFLAGS = Orig.modifiesRegister(X86::EFLAGS, &TRI);
911   if (ClobbersEFLAGS && MBB.computeRegisterLiveness(&TRI, X86::EFLAGS, I) !=
912                             MachineBasicBlock::LQR_Dead) {
913     // The instruction clobbers EFLAGS. Re-materialize as MOV32ri to avoid side
914     // effects.
915     int Value;
916     switch (Orig.getOpcode()) {
917     case X86::MOV32r0:  Value = 0; break;
918     case X86::MOV32r1:  Value = 1; break;
919     case X86::MOV32r_1: Value = -1; break;
920     default:
921       llvm_unreachable("Unexpected instruction!");
922     }
923 
924     const DebugLoc &DL = Orig.getDebugLoc();
925     BuildMI(MBB, I, DL, get(X86::MOV32ri))
926         .add(Orig.getOperand(0))
927         .addImm(Value);
928   } else {
929     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
930     MBB.insert(I, MI);
931   }
932 
933   MachineInstr &NewMI = *std::prev(I);
934   NewMI.substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
935 }
936 
937 /// True if MI has a condition code def, e.g. EFLAGS, that is not marked dead.
938 bool X86InstrInfo::hasLiveCondCodeDef(MachineInstr &MI) const {
939   for (const MachineOperand &MO : MI.operands()) {
940     if (MO.isReg() && MO.isDef() &&
941         MO.getReg() == X86::EFLAGS && !MO.isDead()) {
942       return true;
943     }
944   }
945   return false;
946 }
947 
948 /// Check whether the shift count for a machine operand is non-zero.
949 inline static unsigned getTruncatedShiftCount(const MachineInstr &MI,
950                                               unsigned ShiftAmtOperandIdx) {
951   // The shift count is six bits with the REX.W prefix and five bits without.
952   unsigned ShiftCountMask = (MI.getDesc().TSFlags & X86II::REX_W) ? 63 : 31;
953   unsigned Imm = MI.getOperand(ShiftAmtOperandIdx).getImm();
954   return Imm & ShiftCountMask;
955 }
956 
957 /// Check whether the given shift count is appropriate
958 /// can be represented by a LEA instruction.
959 inline static bool isTruncatedShiftCountForLEA(unsigned ShAmt) {
960   // Left shift instructions can be transformed into load-effective-address
961   // instructions if we can encode them appropriately.
962   // A LEA instruction utilizes a SIB byte to encode its scale factor.
963   // The SIB.scale field is two bits wide which means that we can encode any
964   // shift amount less than 4.
965   return ShAmt < 4 && ShAmt > 0;
966 }
967 
968 static bool findRedundantFlagInstr(MachineInstr &CmpInstr,
969                                    MachineInstr &CmpValDefInstr,
970                                    const MachineRegisterInfo *MRI,
971                                    MachineInstr **AndInstr,
972                                    const TargetRegisterInfo *TRI,
973                                    bool &NoSignFlag, bool &ClearsOverflowFlag) {
974   if (!(CmpValDefInstr.getOpcode() == X86::SUBREG_TO_REG &&
975         CmpInstr.getOpcode() == X86::TEST64rr) &&
976       !(CmpValDefInstr.getOpcode() == X86::COPY &&
977         CmpInstr.getOpcode() == X86::TEST16rr))
978     return false;
979 
980   // CmpInstr is a TEST16rr/TEST64rr instruction, and
981   // `X86InstrInfo::analyzeCompare` guarantees that it's analyzable only if two
982   // registers are identical.
983   assert((CmpInstr.getOperand(0).getReg() == CmpInstr.getOperand(1).getReg()) &&
984          "CmpInstr is an analyzable TEST16rr/TEST64rr, and "
985          "`X86InstrInfo::analyzeCompare` requires two reg operands are the"
986          "same.");
987 
988   // Caller (`X86InstrInfo::optimizeCompareInstr`) guarantees that
989   // `CmpValDefInstr` defines the value that's used by `CmpInstr`; in this case
990   // if `CmpValDefInstr` sets the EFLAGS, it is likely that `CmpInstr` is
991   // redundant.
992   assert(
993       (MRI->getVRegDef(CmpInstr.getOperand(0).getReg()) == &CmpValDefInstr) &&
994       "Caller guarantees that TEST64rr is a user of SUBREG_TO_REG or TEST16rr "
995       "is a user of COPY sub16bit.");
996   MachineInstr *VregDefInstr = nullptr;
997   if (CmpInstr.getOpcode() == X86::TEST16rr) {
998     if (!CmpValDefInstr.getOperand(1).getReg().isVirtual())
999       return false;
1000     VregDefInstr = MRI->getVRegDef(CmpValDefInstr.getOperand(1).getReg());
1001     if (!VregDefInstr)
1002       return false;
1003     // We can only remove test when AND32ri or AND64ri32 whose imm can fit 16bit
1004     // size, others 32/64 bit ops would test higher bits which test16rr don't
1005     // want to.
1006     if (!((VregDefInstr->getOpcode() == X86::AND32ri ||
1007            VregDefInstr->getOpcode() == X86::AND64ri32) &&
1008           isUInt<16>(VregDefInstr->getOperand(2).getImm())))
1009       return false;
1010   }
1011 
1012   if (CmpInstr.getOpcode() == X86::TEST64rr) {
1013     // As seen in X86 td files, CmpValDefInstr.getOperand(1).getImm() is
1014     // typically 0.
1015     if (CmpValDefInstr.getOperand(1).getImm() != 0)
1016       return false;
1017 
1018     // As seen in X86 td files, CmpValDefInstr.getOperand(3) is typically
1019     // sub_32bit or sub_xmm.
1020     if (CmpValDefInstr.getOperand(3).getImm() != X86::sub_32bit)
1021       return false;
1022 
1023     VregDefInstr = MRI->getVRegDef(CmpValDefInstr.getOperand(2).getReg());
1024   }
1025 
1026   assert(VregDefInstr && "Must have a definition (SSA)");
1027 
1028   // Requires `CmpValDefInstr` and `VregDefInstr` are from the same MBB
1029   // to simplify the subsequent analysis.
1030   //
1031   // FIXME: If `VregDefInstr->getParent()` is the only predecessor of
1032   // `CmpValDefInstr.getParent()`, this could be handled.
1033   if (VregDefInstr->getParent() != CmpValDefInstr.getParent())
1034     return false;
1035 
1036   if (X86::isAND(VregDefInstr->getOpcode())) {
1037     // Get a sequence of instructions like
1038     //   %reg = and* ...                    // Set EFLAGS
1039     //   ...                                // EFLAGS not changed
1040     //   %extended_reg = subreg_to_reg 0, %reg, %subreg.sub_32bit
1041     //   test64rr %extended_reg, %extended_reg, implicit-def $eflags
1042     // or
1043     //   %reg = and32* ...
1044     //   ...                         // EFLAGS not changed.
1045     //   %src_reg = copy %reg.sub_16bit:gr32
1046     //   test16rr %src_reg, %src_reg, implicit-def $eflags
1047     //
1048     // If subsequent readers use a subset of bits that don't change
1049     // after `and*` instructions, it's likely that the test64rr could
1050     // be optimized away.
1051     for (const MachineInstr &Instr :
1052          make_range(std::next(MachineBasicBlock::iterator(VregDefInstr)),
1053                     MachineBasicBlock::iterator(CmpValDefInstr))) {
1054       // There are instructions between 'VregDefInstr' and
1055       // 'CmpValDefInstr' that modifies EFLAGS.
1056       if (Instr.modifiesRegister(X86::EFLAGS, TRI))
1057         return false;
1058     }
1059 
1060     *AndInstr = VregDefInstr;
1061 
1062     // AND instruction will essentially update SF and clear OF, so
1063     // NoSignFlag should be false in the sense that SF is modified by `AND`.
1064     //
1065     // However, the implementation artifically sets `NoSignFlag` to true
1066     // to poison the SF bit; that is to say, if SF is looked at later, the
1067     // optimization (to erase TEST64rr) will be disabled.
1068     //
1069     // The reason to poison SF bit is that SF bit value could be different
1070     // in the `AND` and `TEST` operation; signed bit is not known for `AND`,
1071     // and is known to be 0 as a result of `TEST64rr`.
1072     //
1073     // FIXME: As opposed to poisoning the SF bit directly, consider peeking into
1074     // the AND instruction and using the static information to guide peephole
1075     // optimization if possible. For example, it's possible to fold a
1076     // conditional move into a copy if the relevant EFLAG bits could be deduced
1077     // from an immediate operand of and operation.
1078     //
1079     NoSignFlag = true;
1080     // ClearsOverflowFlag is true for AND operation (no surprise).
1081     ClearsOverflowFlag = true;
1082     return true;
1083   }
1084   return false;
1085 }
1086 
1087 bool X86InstrInfo::classifyLEAReg(MachineInstr &MI, const MachineOperand &Src,
1088                                   unsigned Opc, bool AllowSP, Register &NewSrc,
1089                                   bool &isKill, MachineOperand &ImplicitOp,
1090                                   LiveVariables *LV, LiveIntervals *LIS) const {
1091   MachineFunction &MF = *MI.getParent()->getParent();
1092   const TargetRegisterClass *RC;
1093   if (AllowSP) {
1094     RC = Opc != X86::LEA32r ? &X86::GR64RegClass : &X86::GR32RegClass;
1095   } else {
1096     RC = Opc != X86::LEA32r ?
1097       &X86::GR64_NOSPRegClass : &X86::GR32_NOSPRegClass;
1098   }
1099   Register SrcReg = Src.getReg();
1100   isKill = MI.killsRegister(SrcReg);
1101 
1102   // For both LEA64 and LEA32 the register already has essentially the right
1103   // type (32-bit or 64-bit) we may just need to forbid SP.
1104   if (Opc != X86::LEA64_32r) {
1105     NewSrc = SrcReg;
1106     assert(!Src.isUndef() && "Undef op doesn't need optimization");
1107 
1108     if (NewSrc.isVirtual() && !MF.getRegInfo().constrainRegClass(NewSrc, RC))
1109       return false;
1110 
1111     return true;
1112   }
1113 
1114   // This is for an LEA64_32r and incoming registers are 32-bit. One way or
1115   // another we need to add 64-bit registers to the final MI.
1116   if (SrcReg.isPhysical()) {
1117     ImplicitOp = Src;
1118     ImplicitOp.setImplicit();
1119 
1120     NewSrc = getX86SubSuperRegister(SrcReg, 64);
1121     assert(NewSrc.isValid() && "Invalid Operand");
1122     assert(!Src.isUndef() && "Undef op doesn't need optimization");
1123   } else {
1124     // Virtual register of the wrong class, we have to create a temporary 64-bit
1125     // vreg to feed into the LEA.
1126     NewSrc = MF.getRegInfo().createVirtualRegister(RC);
1127     MachineInstr *Copy =
1128         BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(TargetOpcode::COPY))
1129             .addReg(NewSrc, RegState::Define | RegState::Undef, X86::sub_32bit)
1130             .addReg(SrcReg, getKillRegState(isKill));
1131 
1132     // Which is obviously going to be dead after we're done with it.
1133     isKill = true;
1134 
1135     if (LV)
1136       LV->replaceKillInstruction(SrcReg, MI, *Copy);
1137 
1138     if (LIS) {
1139       SlotIndex CopyIdx = LIS->InsertMachineInstrInMaps(*Copy);
1140       SlotIndex Idx = LIS->getInstructionIndex(MI);
1141       LiveInterval &LI = LIS->getInterval(SrcReg);
1142       LiveRange::Segment *S = LI.getSegmentContaining(Idx);
1143       if (S->end.getBaseIndex() == Idx)
1144         S->end = CopyIdx.getRegSlot();
1145     }
1146   }
1147 
1148   // We've set all the parameters without issue.
1149   return true;
1150 }
1151 
1152 MachineInstr *X86InstrInfo::convertToThreeAddressWithLEA(unsigned MIOpc,
1153                                                          MachineInstr &MI,
1154                                                          LiveVariables *LV,
1155                                                          LiveIntervals *LIS,
1156                                                          bool Is8BitOp) const {
1157   // We handle 8-bit adds and various 16-bit opcodes in the switch below.
1158   MachineBasicBlock &MBB = *MI.getParent();
1159   MachineRegisterInfo &RegInfo = MBB.getParent()->getRegInfo();
1160   assert((Is8BitOp || RegInfo.getTargetRegisterInfo()->getRegSizeInBits(
1161               *RegInfo.getRegClass(MI.getOperand(0).getReg())) == 16) &&
1162          "Unexpected type for LEA transform");
1163 
1164   // TODO: For a 32-bit target, we need to adjust the LEA variables with
1165   // something like this:
1166   //   Opcode = X86::LEA32r;
1167   //   InRegLEA = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
1168   //   OutRegLEA =
1169   //       Is8BitOp ? RegInfo.createVirtualRegister(&X86::GR32ABCD_RegClass)
1170   //                : RegInfo.createVirtualRegister(&X86::GR32RegClass);
1171   if (!Subtarget.is64Bit())
1172     return nullptr;
1173 
1174   unsigned Opcode = X86::LEA64_32r;
1175   Register InRegLEA = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
1176   Register OutRegLEA = RegInfo.createVirtualRegister(&X86::GR32RegClass);
1177   Register InRegLEA2;
1178 
1179   // Build and insert into an implicit UNDEF value. This is OK because
1180   // we will be shifting and then extracting the lower 8/16-bits.
1181   // This has the potential to cause partial register stall. e.g.
1182   //   movw    (%rbp,%rcx,2), %dx
1183   //   leal    -65(%rdx), %esi
1184   // But testing has shown this *does* help performance in 64-bit mode (at
1185   // least on modern x86 machines).
1186   MachineBasicBlock::iterator MBBI = MI.getIterator();
1187   Register Dest = MI.getOperand(0).getReg();
1188   Register Src = MI.getOperand(1).getReg();
1189   Register Src2;
1190   bool IsDead = MI.getOperand(0).isDead();
1191   bool IsKill = MI.getOperand(1).isKill();
1192   unsigned SubReg = Is8BitOp ? X86::sub_8bit : X86::sub_16bit;
1193   assert(!MI.getOperand(1).isUndef() && "Undef op doesn't need optimization");
1194   MachineInstr *ImpDef =
1195       BuildMI(MBB, MBBI, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), InRegLEA);
1196   MachineInstr *InsMI =
1197       BuildMI(MBB, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
1198           .addReg(InRegLEA, RegState::Define, SubReg)
1199           .addReg(Src, getKillRegState(IsKill));
1200   MachineInstr *ImpDef2 = nullptr;
1201   MachineInstr *InsMI2 = nullptr;
1202 
1203   MachineInstrBuilder MIB =
1204       BuildMI(MBB, MBBI, MI.getDebugLoc(), get(Opcode), OutRegLEA);
1205   switch (MIOpc) {
1206   default: llvm_unreachable("Unreachable!");
1207   case X86::SHL8ri:
1208   case X86::SHL16ri: {
1209     unsigned ShAmt = MI.getOperand(2).getImm();
1210     MIB.addReg(0)
1211         .addImm(1LL << ShAmt)
1212         .addReg(InRegLEA, RegState::Kill)
1213         .addImm(0)
1214         .addReg(0);
1215     break;
1216   }
1217   case X86::INC8r:
1218   case X86::INC16r:
1219     addRegOffset(MIB, InRegLEA, true, 1);
1220     break;
1221   case X86::DEC8r:
1222   case X86::DEC16r:
1223     addRegOffset(MIB, InRegLEA, true, -1);
1224     break;
1225   case X86::ADD8ri:
1226   case X86::ADD8ri_DB:
1227   case X86::ADD16ri:
1228   case X86::ADD16ri_DB:
1229     addRegOffset(MIB, InRegLEA, true, MI.getOperand(2).getImm());
1230     break;
1231   case X86::ADD8rr:
1232   case X86::ADD8rr_DB:
1233   case X86::ADD16rr:
1234   case X86::ADD16rr_DB: {
1235     Src2 = MI.getOperand(2).getReg();
1236     bool IsKill2 = MI.getOperand(2).isKill();
1237     assert(!MI.getOperand(2).isUndef() && "Undef op doesn't need optimization");
1238     if (Src == Src2) {
1239       // ADD8rr/ADD16rr killed %reg1028, %reg1028
1240       // just a single insert_subreg.
1241       addRegReg(MIB, InRegLEA, true, InRegLEA, false);
1242     } else {
1243       if (Subtarget.is64Bit())
1244         InRegLEA2 = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
1245       else
1246         InRegLEA2 = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
1247       // Build and insert into an implicit UNDEF value. This is OK because
1248       // we will be shifting and then extracting the lower 8/16-bits.
1249       ImpDef2 = BuildMI(MBB, &*MIB, MI.getDebugLoc(), get(X86::IMPLICIT_DEF),
1250                         InRegLEA2);
1251       InsMI2 = BuildMI(MBB, &*MIB, MI.getDebugLoc(), get(TargetOpcode::COPY))
1252                    .addReg(InRegLEA2, RegState::Define, SubReg)
1253                    .addReg(Src2, getKillRegState(IsKill2));
1254       addRegReg(MIB, InRegLEA, true, InRegLEA2, true);
1255     }
1256     if (LV && IsKill2 && InsMI2)
1257       LV->replaceKillInstruction(Src2, MI, *InsMI2);
1258     break;
1259   }
1260   }
1261 
1262   MachineInstr *NewMI = MIB;
1263   MachineInstr *ExtMI =
1264       BuildMI(MBB, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
1265           .addReg(Dest, RegState::Define | getDeadRegState(IsDead))
1266           .addReg(OutRegLEA, RegState::Kill, SubReg);
1267 
1268   if (LV) {
1269     // Update live variables.
1270     LV->getVarInfo(InRegLEA).Kills.push_back(NewMI);
1271     if (InRegLEA2)
1272       LV->getVarInfo(InRegLEA2).Kills.push_back(NewMI);
1273     LV->getVarInfo(OutRegLEA).Kills.push_back(ExtMI);
1274     if (IsKill)
1275       LV->replaceKillInstruction(Src, MI, *InsMI);
1276     if (IsDead)
1277       LV->replaceKillInstruction(Dest, MI, *ExtMI);
1278   }
1279 
1280   if (LIS) {
1281     LIS->InsertMachineInstrInMaps(*ImpDef);
1282     SlotIndex InsIdx = LIS->InsertMachineInstrInMaps(*InsMI);
1283     if (ImpDef2)
1284       LIS->InsertMachineInstrInMaps(*ImpDef2);
1285     SlotIndex Ins2Idx;
1286     if (InsMI2)
1287       Ins2Idx = LIS->InsertMachineInstrInMaps(*InsMI2);
1288     SlotIndex NewIdx = LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
1289     SlotIndex ExtIdx = LIS->InsertMachineInstrInMaps(*ExtMI);
1290     LIS->getInterval(InRegLEA);
1291     LIS->getInterval(OutRegLEA);
1292     if (InRegLEA2)
1293       LIS->getInterval(InRegLEA2);
1294 
1295     // Move the use of Src up to InsMI.
1296     LiveInterval &SrcLI = LIS->getInterval(Src);
1297     LiveRange::Segment *SrcSeg = SrcLI.getSegmentContaining(NewIdx);
1298     if (SrcSeg->end == NewIdx.getRegSlot())
1299       SrcSeg->end = InsIdx.getRegSlot();
1300 
1301     if (InsMI2) {
1302       // Move the use of Src2 up to InsMI2.
1303       LiveInterval &Src2LI = LIS->getInterval(Src2);
1304       LiveRange::Segment *Src2Seg = Src2LI.getSegmentContaining(NewIdx);
1305       if (Src2Seg->end == NewIdx.getRegSlot())
1306         Src2Seg->end = Ins2Idx.getRegSlot();
1307     }
1308 
1309     // Move the definition of Dest down to ExtMI.
1310     LiveInterval &DestLI = LIS->getInterval(Dest);
1311     LiveRange::Segment *DestSeg =
1312         DestLI.getSegmentContaining(NewIdx.getRegSlot());
1313     assert(DestSeg->start == NewIdx.getRegSlot() &&
1314            DestSeg->valno->def == NewIdx.getRegSlot());
1315     DestSeg->start = ExtIdx.getRegSlot();
1316     DestSeg->valno->def = ExtIdx.getRegSlot();
1317   }
1318 
1319   return ExtMI;
1320 }
1321 
1322 /// This method must be implemented by targets that
1323 /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
1324 /// may be able to convert a two-address instruction into a true
1325 /// three-address instruction on demand.  This allows the X86 target (for
1326 /// example) to convert ADD and SHL instructions into LEA instructions if they
1327 /// would require register copies due to two-addressness.
1328 ///
1329 /// This method returns a null pointer if the transformation cannot be
1330 /// performed, otherwise it returns the new instruction.
1331 ///
1332 MachineInstr *X86InstrInfo::convertToThreeAddress(MachineInstr &MI,
1333                                                   LiveVariables *LV,
1334                                                   LiveIntervals *LIS) const {
1335   // The following opcodes also sets the condition code register(s). Only
1336   // convert them to equivalent lea if the condition code register def's
1337   // are dead!
1338   if (hasLiveCondCodeDef(MI))
1339     return nullptr;
1340 
1341   MachineFunction &MF = *MI.getParent()->getParent();
1342   // All instructions input are two-addr instructions.  Get the known operands.
1343   const MachineOperand &Dest = MI.getOperand(0);
1344   const MachineOperand &Src = MI.getOperand(1);
1345 
1346   // Ideally, operations with undef should be folded before we get here, but we
1347   // can't guarantee it. Bail out because optimizing undefs is a waste of time.
1348   // Without this, we have to forward undef state to new register operands to
1349   // avoid machine verifier errors.
1350   if (Src.isUndef())
1351     return nullptr;
1352   if (MI.getNumOperands() > 2)
1353     if (MI.getOperand(2).isReg() && MI.getOperand(2).isUndef())
1354       return nullptr;
1355 
1356   MachineInstr *NewMI = nullptr;
1357   Register SrcReg, SrcReg2;
1358   bool Is64Bit = Subtarget.is64Bit();
1359 
1360   bool Is8BitOp = false;
1361   unsigned NumRegOperands = 2;
1362   unsigned MIOpc = MI.getOpcode();
1363   switch (MIOpc) {
1364   default: llvm_unreachable("Unreachable!");
1365   case X86::SHL64ri: {
1366     assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
1367     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
1368     if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
1369 
1370     // LEA can't handle RSP.
1371     if (Src.getReg().isVirtual() && !MF.getRegInfo().constrainRegClass(
1372                                         Src.getReg(), &X86::GR64_NOSPRegClass))
1373       return nullptr;
1374 
1375     NewMI = BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r))
1376                 .add(Dest)
1377                 .addReg(0)
1378                 .addImm(1LL << ShAmt)
1379                 .add(Src)
1380                 .addImm(0)
1381                 .addReg(0);
1382     break;
1383   }
1384   case X86::SHL32ri: {
1385     assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
1386     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
1387     if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
1388 
1389     unsigned Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1390 
1391     // LEA can't handle ESP.
1392     bool isKill;
1393     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1394     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/false, SrcReg, isKill,
1395                         ImplicitOp, LV, LIS))
1396       return nullptr;
1397 
1398     MachineInstrBuilder MIB =
1399         BuildMI(MF, MI.getDebugLoc(), get(Opc))
1400             .add(Dest)
1401             .addReg(0)
1402             .addImm(1LL << ShAmt)
1403             .addReg(SrcReg, getKillRegState(isKill))
1404             .addImm(0)
1405             .addReg(0);
1406     if (ImplicitOp.getReg() != 0)
1407       MIB.add(ImplicitOp);
1408     NewMI = MIB;
1409 
1410     // Add kills if classifyLEAReg created a new register.
1411     if (LV && SrcReg != Src.getReg())
1412       LV->getVarInfo(SrcReg).Kills.push_back(NewMI);
1413     break;
1414   }
1415   case X86::SHL8ri:
1416     Is8BitOp = true;
1417     [[fallthrough]];
1418   case X86::SHL16ri: {
1419     assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
1420     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
1421     if (!isTruncatedShiftCountForLEA(ShAmt))
1422       return nullptr;
1423     return convertToThreeAddressWithLEA(MIOpc, MI, LV, LIS, Is8BitOp);
1424   }
1425   case X86::INC64r:
1426   case X86::INC32r: {
1427     assert(MI.getNumOperands() >= 2 && "Unknown inc instruction!");
1428     unsigned Opc = MIOpc == X86::INC64r ? X86::LEA64r :
1429         (Is64Bit ? X86::LEA64_32r : X86::LEA32r);
1430     bool isKill;
1431     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1432     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/false, SrcReg, isKill,
1433                         ImplicitOp, LV, LIS))
1434       return nullptr;
1435 
1436     MachineInstrBuilder MIB =
1437         BuildMI(MF, MI.getDebugLoc(), get(Opc))
1438             .add(Dest)
1439             .addReg(SrcReg, getKillRegState(isKill));
1440     if (ImplicitOp.getReg() != 0)
1441       MIB.add(ImplicitOp);
1442 
1443     NewMI = addOffset(MIB, 1);
1444 
1445     // Add kills if classifyLEAReg created a new register.
1446     if (LV && SrcReg != Src.getReg())
1447       LV->getVarInfo(SrcReg).Kills.push_back(NewMI);
1448     break;
1449   }
1450   case X86::DEC64r:
1451   case X86::DEC32r: {
1452     assert(MI.getNumOperands() >= 2 && "Unknown dec instruction!");
1453     unsigned Opc = MIOpc == X86::DEC64r ? X86::LEA64r
1454         : (Is64Bit ? X86::LEA64_32r : X86::LEA32r);
1455 
1456     bool isKill;
1457     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1458     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/false, SrcReg, isKill,
1459                         ImplicitOp, LV, LIS))
1460       return nullptr;
1461 
1462     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1463                                   .add(Dest)
1464                                   .addReg(SrcReg, getKillRegState(isKill));
1465     if (ImplicitOp.getReg() != 0)
1466       MIB.add(ImplicitOp);
1467 
1468     NewMI = addOffset(MIB, -1);
1469 
1470     // Add kills if classifyLEAReg created a new register.
1471     if (LV && SrcReg != Src.getReg())
1472       LV->getVarInfo(SrcReg).Kills.push_back(NewMI);
1473     break;
1474   }
1475   case X86::DEC8r:
1476   case X86::INC8r:
1477     Is8BitOp = true;
1478     [[fallthrough]];
1479   case X86::DEC16r:
1480   case X86::INC16r:
1481     return convertToThreeAddressWithLEA(MIOpc, MI, LV, LIS, Is8BitOp);
1482   case X86::ADD64rr:
1483   case X86::ADD64rr_DB:
1484   case X86::ADD32rr:
1485   case X86::ADD32rr_DB: {
1486     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1487     unsigned Opc;
1488     if (MIOpc == X86::ADD64rr || MIOpc == X86::ADD64rr_DB)
1489       Opc = X86::LEA64r;
1490     else
1491       Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1492 
1493     const MachineOperand &Src2 = MI.getOperand(2);
1494     bool isKill2;
1495     MachineOperand ImplicitOp2 = MachineOperand::CreateReg(0, false);
1496     if (!classifyLEAReg(MI, Src2, Opc, /*AllowSP=*/false, SrcReg2, isKill2,
1497                         ImplicitOp2, LV, LIS))
1498       return nullptr;
1499 
1500     bool isKill;
1501     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1502     if (Src.getReg() == Src2.getReg()) {
1503       // Don't call classify LEAReg a second time on the same register, in case
1504       // the first call inserted a COPY from Src2 and marked it as killed.
1505       isKill = isKill2;
1506       SrcReg = SrcReg2;
1507     } else {
1508       if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/true, SrcReg, isKill,
1509                           ImplicitOp, LV, LIS))
1510         return nullptr;
1511     }
1512 
1513     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc)).add(Dest);
1514     if (ImplicitOp.getReg() != 0)
1515       MIB.add(ImplicitOp);
1516     if (ImplicitOp2.getReg() != 0)
1517       MIB.add(ImplicitOp2);
1518 
1519     NewMI = addRegReg(MIB, SrcReg, isKill, SrcReg2, isKill2);
1520 
1521     // Add kills if classifyLEAReg created a new register.
1522     if (LV) {
1523       if (SrcReg2 != Src2.getReg())
1524         LV->getVarInfo(SrcReg2).Kills.push_back(NewMI);
1525       if (SrcReg != SrcReg2 && SrcReg != Src.getReg())
1526         LV->getVarInfo(SrcReg).Kills.push_back(NewMI);
1527     }
1528     NumRegOperands = 3;
1529     break;
1530   }
1531   case X86::ADD8rr:
1532   case X86::ADD8rr_DB:
1533     Is8BitOp = true;
1534     [[fallthrough]];
1535   case X86::ADD16rr:
1536   case X86::ADD16rr_DB:
1537     return convertToThreeAddressWithLEA(MIOpc, MI, LV, LIS, Is8BitOp);
1538   case X86::ADD64ri32:
1539   case X86::ADD64ri32_DB:
1540     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1541     NewMI = addOffset(
1542         BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r)).add(Dest).add(Src),
1543         MI.getOperand(2));
1544     break;
1545   case X86::ADD32ri:
1546   case X86::ADD32ri_DB: {
1547     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1548     unsigned Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1549 
1550     bool isKill;
1551     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1552     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/true, SrcReg, isKill,
1553                         ImplicitOp, LV, LIS))
1554       return nullptr;
1555 
1556     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1557                                   .add(Dest)
1558                                   .addReg(SrcReg, getKillRegState(isKill));
1559     if (ImplicitOp.getReg() != 0)
1560       MIB.add(ImplicitOp);
1561 
1562     NewMI = addOffset(MIB, MI.getOperand(2));
1563 
1564     // Add kills if classifyLEAReg created a new register.
1565     if (LV && SrcReg != Src.getReg())
1566       LV->getVarInfo(SrcReg).Kills.push_back(NewMI);
1567     break;
1568   }
1569   case X86::ADD8ri:
1570   case X86::ADD8ri_DB:
1571     Is8BitOp = true;
1572     [[fallthrough]];
1573   case X86::ADD16ri:
1574   case X86::ADD16ri_DB:
1575     return convertToThreeAddressWithLEA(MIOpc, MI, LV, LIS, Is8BitOp);
1576   case X86::SUB8ri:
1577   case X86::SUB16ri:
1578     /// FIXME: Support these similar to ADD8ri/ADD16ri*.
1579     return nullptr;
1580   case X86::SUB32ri: {
1581     if (!MI.getOperand(2).isImm())
1582       return nullptr;
1583     int64_t Imm = MI.getOperand(2).getImm();
1584     if (!isInt<32>(-Imm))
1585       return nullptr;
1586 
1587     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1588     unsigned Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1589 
1590     bool isKill;
1591     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1592     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/true, SrcReg, isKill,
1593                         ImplicitOp, LV, LIS))
1594       return nullptr;
1595 
1596     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1597                                   .add(Dest)
1598                                   .addReg(SrcReg, getKillRegState(isKill));
1599     if (ImplicitOp.getReg() != 0)
1600       MIB.add(ImplicitOp);
1601 
1602     NewMI = addOffset(MIB, -Imm);
1603 
1604     // Add kills if classifyLEAReg created a new register.
1605     if (LV && SrcReg != Src.getReg())
1606       LV->getVarInfo(SrcReg).Kills.push_back(NewMI);
1607     break;
1608   }
1609 
1610   case X86::SUB64ri32: {
1611     if (!MI.getOperand(2).isImm())
1612       return nullptr;
1613     int64_t Imm = MI.getOperand(2).getImm();
1614     if (!isInt<32>(-Imm))
1615       return nullptr;
1616 
1617     assert(MI.getNumOperands() >= 3 && "Unknown sub instruction!");
1618 
1619     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(),
1620                                       get(X86::LEA64r)).add(Dest).add(Src);
1621     NewMI = addOffset(MIB, -Imm);
1622     break;
1623   }
1624 
1625   case X86::VMOVDQU8Z128rmk:
1626   case X86::VMOVDQU8Z256rmk:
1627   case X86::VMOVDQU8Zrmk:
1628   case X86::VMOVDQU16Z128rmk:
1629   case X86::VMOVDQU16Z256rmk:
1630   case X86::VMOVDQU16Zrmk:
1631   case X86::VMOVDQU32Z128rmk: case X86::VMOVDQA32Z128rmk:
1632   case X86::VMOVDQU32Z256rmk: case X86::VMOVDQA32Z256rmk:
1633   case X86::VMOVDQU32Zrmk:    case X86::VMOVDQA32Zrmk:
1634   case X86::VMOVDQU64Z128rmk: case X86::VMOVDQA64Z128rmk:
1635   case X86::VMOVDQU64Z256rmk: case X86::VMOVDQA64Z256rmk:
1636   case X86::VMOVDQU64Zrmk:    case X86::VMOVDQA64Zrmk:
1637   case X86::VMOVUPDZ128rmk:   case X86::VMOVAPDZ128rmk:
1638   case X86::VMOVUPDZ256rmk:   case X86::VMOVAPDZ256rmk:
1639   case X86::VMOVUPDZrmk:      case X86::VMOVAPDZrmk:
1640   case X86::VMOVUPSZ128rmk:   case X86::VMOVAPSZ128rmk:
1641   case X86::VMOVUPSZ256rmk:   case X86::VMOVAPSZ256rmk:
1642   case X86::VMOVUPSZrmk:      case X86::VMOVAPSZrmk:
1643   case X86::VBROADCASTSDZ256rmk:
1644   case X86::VBROADCASTSDZrmk:
1645   case X86::VBROADCASTSSZ128rmk:
1646   case X86::VBROADCASTSSZ256rmk:
1647   case X86::VBROADCASTSSZrmk:
1648   case X86::VPBROADCASTDZ128rmk:
1649   case X86::VPBROADCASTDZ256rmk:
1650   case X86::VPBROADCASTDZrmk:
1651   case X86::VPBROADCASTQZ128rmk:
1652   case X86::VPBROADCASTQZ256rmk:
1653   case X86::VPBROADCASTQZrmk: {
1654     unsigned Opc;
1655     switch (MIOpc) {
1656     default: llvm_unreachable("Unreachable!");
1657     case X86::VMOVDQU8Z128rmk:     Opc = X86::VPBLENDMBZ128rmk; break;
1658     case X86::VMOVDQU8Z256rmk:     Opc = X86::VPBLENDMBZ256rmk; break;
1659     case X86::VMOVDQU8Zrmk:        Opc = X86::VPBLENDMBZrmk;    break;
1660     case X86::VMOVDQU16Z128rmk:    Opc = X86::VPBLENDMWZ128rmk; break;
1661     case X86::VMOVDQU16Z256rmk:    Opc = X86::VPBLENDMWZ256rmk; break;
1662     case X86::VMOVDQU16Zrmk:       Opc = X86::VPBLENDMWZrmk;    break;
1663     case X86::VMOVDQU32Z128rmk:    Opc = X86::VPBLENDMDZ128rmk; break;
1664     case X86::VMOVDQU32Z256rmk:    Opc = X86::VPBLENDMDZ256rmk; break;
1665     case X86::VMOVDQU32Zrmk:       Opc = X86::VPBLENDMDZrmk;    break;
1666     case X86::VMOVDQU64Z128rmk:    Opc = X86::VPBLENDMQZ128rmk; break;
1667     case X86::VMOVDQU64Z256rmk:    Opc = X86::VPBLENDMQZ256rmk; break;
1668     case X86::VMOVDQU64Zrmk:       Opc = X86::VPBLENDMQZrmk;    break;
1669     case X86::VMOVUPDZ128rmk:      Opc = X86::VBLENDMPDZ128rmk; break;
1670     case X86::VMOVUPDZ256rmk:      Opc = X86::VBLENDMPDZ256rmk; break;
1671     case X86::VMOVUPDZrmk:         Opc = X86::VBLENDMPDZrmk;    break;
1672     case X86::VMOVUPSZ128rmk:      Opc = X86::VBLENDMPSZ128rmk; break;
1673     case X86::VMOVUPSZ256rmk:      Opc = X86::VBLENDMPSZ256rmk; break;
1674     case X86::VMOVUPSZrmk:         Opc = X86::VBLENDMPSZrmk;    break;
1675     case X86::VMOVDQA32Z128rmk:    Opc = X86::VPBLENDMDZ128rmk; break;
1676     case X86::VMOVDQA32Z256rmk:    Opc = X86::VPBLENDMDZ256rmk; break;
1677     case X86::VMOVDQA32Zrmk:       Opc = X86::VPBLENDMDZrmk;    break;
1678     case X86::VMOVDQA64Z128rmk:    Opc = X86::VPBLENDMQZ128rmk; break;
1679     case X86::VMOVDQA64Z256rmk:    Opc = X86::VPBLENDMQZ256rmk; break;
1680     case X86::VMOVDQA64Zrmk:       Opc = X86::VPBLENDMQZrmk;    break;
1681     case X86::VMOVAPDZ128rmk:      Opc = X86::VBLENDMPDZ128rmk; break;
1682     case X86::VMOVAPDZ256rmk:      Opc = X86::VBLENDMPDZ256rmk; break;
1683     case X86::VMOVAPDZrmk:         Opc = X86::VBLENDMPDZrmk;    break;
1684     case X86::VMOVAPSZ128rmk:      Opc = X86::VBLENDMPSZ128rmk; break;
1685     case X86::VMOVAPSZ256rmk:      Opc = X86::VBLENDMPSZ256rmk; break;
1686     case X86::VMOVAPSZrmk:         Opc = X86::VBLENDMPSZrmk;    break;
1687     case X86::VBROADCASTSDZ256rmk: Opc = X86::VBLENDMPDZ256rmbk; break;
1688     case X86::VBROADCASTSDZrmk:    Opc = X86::VBLENDMPDZrmbk;    break;
1689     case X86::VBROADCASTSSZ128rmk: Opc = X86::VBLENDMPSZ128rmbk; break;
1690     case X86::VBROADCASTSSZ256rmk: Opc = X86::VBLENDMPSZ256rmbk; break;
1691     case X86::VBROADCASTSSZrmk:    Opc = X86::VBLENDMPSZrmbk;    break;
1692     case X86::VPBROADCASTDZ128rmk: Opc = X86::VPBLENDMDZ128rmbk; break;
1693     case X86::VPBROADCASTDZ256rmk: Opc = X86::VPBLENDMDZ256rmbk; break;
1694     case X86::VPBROADCASTDZrmk:    Opc = X86::VPBLENDMDZrmbk;    break;
1695     case X86::VPBROADCASTQZ128rmk: Opc = X86::VPBLENDMQZ128rmbk; break;
1696     case X86::VPBROADCASTQZ256rmk: Opc = X86::VPBLENDMQZ256rmbk; break;
1697     case X86::VPBROADCASTQZrmk:    Opc = X86::VPBLENDMQZrmbk;    break;
1698     }
1699 
1700     NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1701               .add(Dest)
1702               .add(MI.getOperand(2))
1703               .add(Src)
1704               .add(MI.getOperand(3))
1705               .add(MI.getOperand(4))
1706               .add(MI.getOperand(5))
1707               .add(MI.getOperand(6))
1708               .add(MI.getOperand(7));
1709     NumRegOperands = 4;
1710     break;
1711   }
1712 
1713   case X86::VMOVDQU8Z128rrk:
1714   case X86::VMOVDQU8Z256rrk:
1715   case X86::VMOVDQU8Zrrk:
1716   case X86::VMOVDQU16Z128rrk:
1717   case X86::VMOVDQU16Z256rrk:
1718   case X86::VMOVDQU16Zrrk:
1719   case X86::VMOVDQU32Z128rrk: case X86::VMOVDQA32Z128rrk:
1720   case X86::VMOVDQU32Z256rrk: case X86::VMOVDQA32Z256rrk:
1721   case X86::VMOVDQU32Zrrk:    case X86::VMOVDQA32Zrrk:
1722   case X86::VMOVDQU64Z128rrk: case X86::VMOVDQA64Z128rrk:
1723   case X86::VMOVDQU64Z256rrk: case X86::VMOVDQA64Z256rrk:
1724   case X86::VMOVDQU64Zrrk:    case X86::VMOVDQA64Zrrk:
1725   case X86::VMOVUPDZ128rrk:   case X86::VMOVAPDZ128rrk:
1726   case X86::VMOVUPDZ256rrk:   case X86::VMOVAPDZ256rrk:
1727   case X86::VMOVUPDZrrk:      case X86::VMOVAPDZrrk:
1728   case X86::VMOVUPSZ128rrk:   case X86::VMOVAPSZ128rrk:
1729   case X86::VMOVUPSZ256rrk:   case X86::VMOVAPSZ256rrk:
1730   case X86::VMOVUPSZrrk:      case X86::VMOVAPSZrrk: {
1731     unsigned Opc;
1732     switch (MIOpc) {
1733     default: llvm_unreachable("Unreachable!");
1734     case X86::VMOVDQU8Z128rrk:  Opc = X86::VPBLENDMBZ128rrk; break;
1735     case X86::VMOVDQU8Z256rrk:  Opc = X86::VPBLENDMBZ256rrk; break;
1736     case X86::VMOVDQU8Zrrk:     Opc = X86::VPBLENDMBZrrk;    break;
1737     case X86::VMOVDQU16Z128rrk: Opc = X86::VPBLENDMWZ128rrk; break;
1738     case X86::VMOVDQU16Z256rrk: Opc = X86::VPBLENDMWZ256rrk; break;
1739     case X86::VMOVDQU16Zrrk:    Opc = X86::VPBLENDMWZrrk;    break;
1740     case X86::VMOVDQU32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1741     case X86::VMOVDQU32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1742     case X86::VMOVDQU32Zrrk:    Opc = X86::VPBLENDMDZrrk;    break;
1743     case X86::VMOVDQU64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1744     case X86::VMOVDQU64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1745     case X86::VMOVDQU64Zrrk:    Opc = X86::VPBLENDMQZrrk;    break;
1746     case X86::VMOVUPDZ128rrk:   Opc = X86::VBLENDMPDZ128rrk; break;
1747     case X86::VMOVUPDZ256rrk:   Opc = X86::VBLENDMPDZ256rrk; break;
1748     case X86::VMOVUPDZrrk:      Opc = X86::VBLENDMPDZrrk;    break;
1749     case X86::VMOVUPSZ128rrk:   Opc = X86::VBLENDMPSZ128rrk; break;
1750     case X86::VMOVUPSZ256rrk:   Opc = X86::VBLENDMPSZ256rrk; break;
1751     case X86::VMOVUPSZrrk:      Opc = X86::VBLENDMPSZrrk;    break;
1752     case X86::VMOVDQA32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1753     case X86::VMOVDQA32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1754     case X86::VMOVDQA32Zrrk:    Opc = X86::VPBLENDMDZrrk;    break;
1755     case X86::VMOVDQA64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1756     case X86::VMOVDQA64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1757     case X86::VMOVDQA64Zrrk:    Opc = X86::VPBLENDMQZrrk;    break;
1758     case X86::VMOVAPDZ128rrk:   Opc = X86::VBLENDMPDZ128rrk; break;
1759     case X86::VMOVAPDZ256rrk:   Opc = X86::VBLENDMPDZ256rrk; break;
1760     case X86::VMOVAPDZrrk:      Opc = X86::VBLENDMPDZrrk;    break;
1761     case X86::VMOVAPSZ128rrk:   Opc = X86::VBLENDMPSZ128rrk; break;
1762     case X86::VMOVAPSZ256rrk:   Opc = X86::VBLENDMPSZ256rrk; break;
1763     case X86::VMOVAPSZrrk:      Opc = X86::VBLENDMPSZrrk;    break;
1764     }
1765 
1766     NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1767               .add(Dest)
1768               .add(MI.getOperand(2))
1769               .add(Src)
1770               .add(MI.getOperand(3));
1771     NumRegOperands = 4;
1772     break;
1773   }
1774   }
1775 
1776   if (!NewMI) return nullptr;
1777 
1778   if (LV) {  // Update live variables
1779     for (unsigned I = 0; I < NumRegOperands; ++I) {
1780       MachineOperand &Op = MI.getOperand(I);
1781       if (Op.isReg() && (Op.isDead() || Op.isKill()))
1782         LV->replaceKillInstruction(Op.getReg(), MI, *NewMI);
1783     }
1784   }
1785 
1786   MachineBasicBlock &MBB = *MI.getParent();
1787   MBB.insert(MI.getIterator(), NewMI); // Insert the new inst
1788 
1789   if (LIS) {
1790     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
1791     if (SrcReg)
1792       LIS->getInterval(SrcReg);
1793     if (SrcReg2)
1794       LIS->getInterval(SrcReg2);
1795   }
1796 
1797   return NewMI;
1798 }
1799 
1800 /// This determines which of three possible cases of a three source commute
1801 /// the source indexes correspond to taking into account any mask operands.
1802 /// All prevents commuting a passthru operand. Returns -1 if the commute isn't
1803 /// possible.
1804 /// Case 0 - Possible to commute the first and second operands.
1805 /// Case 1 - Possible to commute the first and third operands.
1806 /// Case 2 - Possible to commute the second and third operands.
1807 static unsigned getThreeSrcCommuteCase(uint64_t TSFlags, unsigned SrcOpIdx1,
1808                                        unsigned SrcOpIdx2) {
1809   // Put the lowest index to SrcOpIdx1 to simplify the checks below.
1810   if (SrcOpIdx1 > SrcOpIdx2)
1811     std::swap(SrcOpIdx1, SrcOpIdx2);
1812 
1813   unsigned Op1 = 1, Op2 = 2, Op3 = 3;
1814   if (X86II::isKMasked(TSFlags)) {
1815     Op2++;
1816     Op3++;
1817   }
1818 
1819   if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op2)
1820     return 0;
1821   if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op3)
1822     return 1;
1823   if (SrcOpIdx1 == Op2 && SrcOpIdx2 == Op3)
1824     return 2;
1825   llvm_unreachable("Unknown three src commute case.");
1826 }
1827 
1828 unsigned X86InstrInfo::getFMA3OpcodeToCommuteOperands(
1829     const MachineInstr &MI, unsigned SrcOpIdx1, unsigned SrcOpIdx2,
1830     const X86InstrFMA3Group &FMA3Group) const {
1831 
1832   unsigned Opc = MI.getOpcode();
1833 
1834   // TODO: Commuting the 1st operand of FMA*_Int requires some additional
1835   // analysis. The commute optimization is legal only if all users of FMA*_Int
1836   // use only the lowest element of the FMA*_Int instruction. Such analysis are
1837   // not implemented yet. So, just return 0 in that case.
1838   // When such analysis are available this place will be the right place for
1839   // calling it.
1840   assert(!(FMA3Group.isIntrinsic() && (SrcOpIdx1 == 1 || SrcOpIdx2 == 1)) &&
1841          "Intrinsic instructions can't commute operand 1");
1842 
1843   // Determine which case this commute is or if it can't be done.
1844   unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1845                                          SrcOpIdx2);
1846   assert(Case < 3 && "Unexpected case number!");
1847 
1848   // Define the FMA forms mapping array that helps to map input FMA form
1849   // to output FMA form to preserve the operation semantics after
1850   // commuting the operands.
1851   const unsigned Form132Index = 0;
1852   const unsigned Form213Index = 1;
1853   const unsigned Form231Index = 2;
1854   static const unsigned FormMapping[][3] = {
1855     // 0: SrcOpIdx1 == 1 && SrcOpIdx2 == 2;
1856     // FMA132 A, C, b; ==> FMA231 C, A, b;
1857     // FMA213 B, A, c; ==> FMA213 A, B, c;
1858     // FMA231 C, A, b; ==> FMA132 A, C, b;
1859     { Form231Index, Form213Index, Form132Index },
1860     // 1: SrcOpIdx1 == 1 && SrcOpIdx2 == 3;
1861     // FMA132 A, c, B; ==> FMA132 B, c, A;
1862     // FMA213 B, a, C; ==> FMA231 C, a, B;
1863     // FMA231 C, a, B; ==> FMA213 B, a, C;
1864     { Form132Index, Form231Index, Form213Index },
1865     // 2: SrcOpIdx1 == 2 && SrcOpIdx2 == 3;
1866     // FMA132 a, C, B; ==> FMA213 a, B, C;
1867     // FMA213 b, A, C; ==> FMA132 b, C, A;
1868     // FMA231 c, A, B; ==> FMA231 c, B, A;
1869     { Form213Index, Form132Index, Form231Index }
1870   };
1871 
1872   unsigned FMAForms[3];
1873   FMAForms[0] = FMA3Group.get132Opcode();
1874   FMAForms[1] = FMA3Group.get213Opcode();
1875   FMAForms[2] = FMA3Group.get231Opcode();
1876 
1877   // Everything is ready, just adjust the FMA opcode and return it.
1878   for (unsigned FormIndex = 0; FormIndex < 3; FormIndex++)
1879     if (Opc == FMAForms[FormIndex])
1880       return FMAForms[FormMapping[Case][FormIndex]];
1881 
1882   llvm_unreachable("Illegal FMA3 format");
1883 }
1884 
1885 static void commuteVPTERNLOG(MachineInstr &MI, unsigned SrcOpIdx1,
1886                              unsigned SrcOpIdx2) {
1887   // Determine which case this commute is or if it can't be done.
1888   unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1889                                          SrcOpIdx2);
1890   assert(Case < 3 && "Unexpected case value!");
1891 
1892   // For each case we need to swap two pairs of bits in the final immediate.
1893   static const uint8_t SwapMasks[3][4] = {
1894     { 0x04, 0x10, 0x08, 0x20 }, // Swap bits 2/4 and 3/5.
1895     { 0x02, 0x10, 0x08, 0x40 }, // Swap bits 1/4 and 3/6.
1896     { 0x02, 0x04, 0x20, 0x40 }, // Swap bits 1/2 and 5/6.
1897   };
1898 
1899   uint8_t Imm = MI.getOperand(MI.getNumOperands()-1).getImm();
1900   // Clear out the bits we are swapping.
1901   uint8_t NewImm = Imm & ~(SwapMasks[Case][0] | SwapMasks[Case][1] |
1902                            SwapMasks[Case][2] | SwapMasks[Case][3]);
1903   // If the immediate had a bit of the pair set, then set the opposite bit.
1904   if (Imm & SwapMasks[Case][0]) NewImm |= SwapMasks[Case][1];
1905   if (Imm & SwapMasks[Case][1]) NewImm |= SwapMasks[Case][0];
1906   if (Imm & SwapMasks[Case][2]) NewImm |= SwapMasks[Case][3];
1907   if (Imm & SwapMasks[Case][3]) NewImm |= SwapMasks[Case][2];
1908   MI.getOperand(MI.getNumOperands()-1).setImm(NewImm);
1909 }
1910 
1911 // Returns true if this is a VPERMI2 or VPERMT2 instruction that can be
1912 // commuted.
1913 static bool isCommutableVPERMV3Instruction(unsigned Opcode) {
1914 #define VPERM_CASES(Suffix) \
1915   case X86::VPERMI2##Suffix##128rr:    case X86::VPERMT2##Suffix##128rr:    \
1916   case X86::VPERMI2##Suffix##256rr:    case X86::VPERMT2##Suffix##256rr:    \
1917   case X86::VPERMI2##Suffix##rr:       case X86::VPERMT2##Suffix##rr:       \
1918   case X86::VPERMI2##Suffix##128rm:    case X86::VPERMT2##Suffix##128rm:    \
1919   case X86::VPERMI2##Suffix##256rm:    case X86::VPERMT2##Suffix##256rm:    \
1920   case X86::VPERMI2##Suffix##rm:       case X86::VPERMT2##Suffix##rm:       \
1921   case X86::VPERMI2##Suffix##128rrkz:  case X86::VPERMT2##Suffix##128rrkz:  \
1922   case X86::VPERMI2##Suffix##256rrkz:  case X86::VPERMT2##Suffix##256rrkz:  \
1923   case X86::VPERMI2##Suffix##rrkz:     case X86::VPERMT2##Suffix##rrkz:     \
1924   case X86::VPERMI2##Suffix##128rmkz:  case X86::VPERMT2##Suffix##128rmkz:  \
1925   case X86::VPERMI2##Suffix##256rmkz:  case X86::VPERMT2##Suffix##256rmkz:  \
1926   case X86::VPERMI2##Suffix##rmkz:     case X86::VPERMT2##Suffix##rmkz:
1927 
1928 #define VPERM_CASES_BROADCAST(Suffix) \
1929   VPERM_CASES(Suffix) \
1930   case X86::VPERMI2##Suffix##128rmb:   case X86::VPERMT2##Suffix##128rmb:   \
1931   case X86::VPERMI2##Suffix##256rmb:   case X86::VPERMT2##Suffix##256rmb:   \
1932   case X86::VPERMI2##Suffix##rmb:      case X86::VPERMT2##Suffix##rmb:      \
1933   case X86::VPERMI2##Suffix##128rmbkz: case X86::VPERMT2##Suffix##128rmbkz: \
1934   case X86::VPERMI2##Suffix##256rmbkz: case X86::VPERMT2##Suffix##256rmbkz: \
1935   case X86::VPERMI2##Suffix##rmbkz:    case X86::VPERMT2##Suffix##rmbkz:
1936 
1937   switch (Opcode) {
1938   default: return false;
1939   VPERM_CASES(B)
1940   VPERM_CASES_BROADCAST(D)
1941   VPERM_CASES_BROADCAST(PD)
1942   VPERM_CASES_BROADCAST(PS)
1943   VPERM_CASES_BROADCAST(Q)
1944   VPERM_CASES(W)
1945     return true;
1946   }
1947 #undef VPERM_CASES_BROADCAST
1948 #undef VPERM_CASES
1949 }
1950 
1951 // Returns commuted opcode for VPERMI2 and VPERMT2 instructions by switching
1952 // from the I opcode to the T opcode and vice versa.
1953 static unsigned getCommutedVPERMV3Opcode(unsigned Opcode) {
1954 #define VPERM_CASES(Orig, New) \
1955   case X86::Orig##128rr:    return X86::New##128rr;   \
1956   case X86::Orig##128rrkz:  return X86::New##128rrkz; \
1957   case X86::Orig##128rm:    return X86::New##128rm;   \
1958   case X86::Orig##128rmkz:  return X86::New##128rmkz; \
1959   case X86::Orig##256rr:    return X86::New##256rr;   \
1960   case X86::Orig##256rrkz:  return X86::New##256rrkz; \
1961   case X86::Orig##256rm:    return X86::New##256rm;   \
1962   case X86::Orig##256rmkz:  return X86::New##256rmkz; \
1963   case X86::Orig##rr:       return X86::New##rr;      \
1964   case X86::Orig##rrkz:     return X86::New##rrkz;    \
1965   case X86::Orig##rm:       return X86::New##rm;      \
1966   case X86::Orig##rmkz:     return X86::New##rmkz;
1967 
1968 #define VPERM_CASES_BROADCAST(Orig, New) \
1969   VPERM_CASES(Orig, New) \
1970   case X86::Orig##128rmb:   return X86::New##128rmb;   \
1971   case X86::Orig##128rmbkz: return X86::New##128rmbkz; \
1972   case X86::Orig##256rmb:   return X86::New##256rmb;   \
1973   case X86::Orig##256rmbkz: return X86::New##256rmbkz; \
1974   case X86::Orig##rmb:      return X86::New##rmb;      \
1975   case X86::Orig##rmbkz:    return X86::New##rmbkz;
1976 
1977   switch (Opcode) {
1978   VPERM_CASES(VPERMI2B, VPERMT2B)
1979   VPERM_CASES_BROADCAST(VPERMI2D,  VPERMT2D)
1980   VPERM_CASES_BROADCAST(VPERMI2PD, VPERMT2PD)
1981   VPERM_CASES_BROADCAST(VPERMI2PS, VPERMT2PS)
1982   VPERM_CASES_BROADCAST(VPERMI2Q,  VPERMT2Q)
1983   VPERM_CASES(VPERMI2W, VPERMT2W)
1984   VPERM_CASES(VPERMT2B, VPERMI2B)
1985   VPERM_CASES_BROADCAST(VPERMT2D,  VPERMI2D)
1986   VPERM_CASES_BROADCAST(VPERMT2PD, VPERMI2PD)
1987   VPERM_CASES_BROADCAST(VPERMT2PS, VPERMI2PS)
1988   VPERM_CASES_BROADCAST(VPERMT2Q,  VPERMI2Q)
1989   VPERM_CASES(VPERMT2W, VPERMI2W)
1990   }
1991 
1992   llvm_unreachable("Unreachable!");
1993 #undef VPERM_CASES_BROADCAST
1994 #undef VPERM_CASES
1995 }
1996 
1997 MachineInstr *X86InstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
1998                                                    unsigned OpIdx1,
1999                                                    unsigned OpIdx2) const {
2000   auto cloneIfNew = [NewMI](MachineInstr &MI) -> MachineInstr & {
2001     if (NewMI)
2002       return *MI.getParent()->getParent()->CloneMachineInstr(&MI);
2003     return MI;
2004   };
2005 
2006   switch (MI.getOpcode()) {
2007   case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
2008   case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
2009   case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
2010   case X86::SHLD32rri8: // A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
2011   case X86::SHRD64rri8: // A = SHRD64rri8 B, C, I -> A = SHLD64rri8 C, B, (64-I)
2012   case X86::SHLD64rri8:{// A = SHLD64rri8 B, C, I -> A = SHRD64rri8 C, B, (64-I)
2013     unsigned Opc;
2014     unsigned Size;
2015     switch (MI.getOpcode()) {
2016     default: llvm_unreachable("Unreachable!");
2017     case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
2018     case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
2019     case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
2020     case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
2021     case X86::SHRD64rri8: Size = 64; Opc = X86::SHLD64rri8; break;
2022     case X86::SHLD64rri8: Size = 64; Opc = X86::SHRD64rri8; break;
2023     }
2024     unsigned Amt = MI.getOperand(3).getImm();
2025     auto &WorkingMI = cloneIfNew(MI);
2026     WorkingMI.setDesc(get(Opc));
2027     WorkingMI.getOperand(3).setImm(Size - Amt);
2028     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2029                                                    OpIdx1, OpIdx2);
2030   }
2031   case X86::PFSUBrr:
2032   case X86::PFSUBRrr: {
2033     // PFSUB  x, y: x = x - y
2034     // PFSUBR x, y: x = y - x
2035     unsigned Opc =
2036         (X86::PFSUBRrr == MI.getOpcode() ? X86::PFSUBrr : X86::PFSUBRrr);
2037     auto &WorkingMI = cloneIfNew(MI);
2038     WorkingMI.setDesc(get(Opc));
2039     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2040                                                    OpIdx1, OpIdx2);
2041   }
2042   case X86::BLENDPDrri:
2043   case X86::BLENDPSrri:
2044   case X86::VBLENDPDrri:
2045   case X86::VBLENDPSrri:
2046     // If we're optimizing for size, try to use MOVSD/MOVSS.
2047     if (MI.getParent()->getParent()->getFunction().hasOptSize()) {
2048       unsigned Mask, Opc;
2049       switch (MI.getOpcode()) {
2050       default: llvm_unreachable("Unreachable!");
2051       case X86::BLENDPDrri:  Opc = X86::MOVSDrr;  Mask = 0x03; break;
2052       case X86::BLENDPSrri:  Opc = X86::MOVSSrr;  Mask = 0x0F; break;
2053       case X86::VBLENDPDrri: Opc = X86::VMOVSDrr; Mask = 0x03; break;
2054       case X86::VBLENDPSrri: Opc = X86::VMOVSSrr; Mask = 0x0F; break;
2055       }
2056       if ((MI.getOperand(3).getImm() ^ Mask) == 1) {
2057         auto &WorkingMI = cloneIfNew(MI);
2058         WorkingMI.setDesc(get(Opc));
2059         WorkingMI.removeOperand(3);
2060         return TargetInstrInfo::commuteInstructionImpl(WorkingMI,
2061                                                        /*NewMI=*/false,
2062                                                        OpIdx1, OpIdx2);
2063       }
2064     }
2065     [[fallthrough]];
2066   case X86::PBLENDWrri:
2067   case X86::VBLENDPDYrri:
2068   case X86::VBLENDPSYrri:
2069   case X86::VPBLENDDrri:
2070   case X86::VPBLENDWrri:
2071   case X86::VPBLENDDYrri:
2072   case X86::VPBLENDWYrri:{
2073     int8_t Mask;
2074     switch (MI.getOpcode()) {
2075     default: llvm_unreachable("Unreachable!");
2076     case X86::BLENDPDrri:    Mask = (int8_t)0x03; break;
2077     case X86::BLENDPSrri:    Mask = (int8_t)0x0F; break;
2078     case X86::PBLENDWrri:    Mask = (int8_t)0xFF; break;
2079     case X86::VBLENDPDrri:   Mask = (int8_t)0x03; break;
2080     case X86::VBLENDPSrri:   Mask = (int8_t)0x0F; break;
2081     case X86::VBLENDPDYrri:  Mask = (int8_t)0x0F; break;
2082     case X86::VBLENDPSYrri:  Mask = (int8_t)0xFF; break;
2083     case X86::VPBLENDDrri:   Mask = (int8_t)0x0F; break;
2084     case X86::VPBLENDWrri:   Mask = (int8_t)0xFF; break;
2085     case X86::VPBLENDDYrri:  Mask = (int8_t)0xFF; break;
2086     case X86::VPBLENDWYrri:  Mask = (int8_t)0xFF; break;
2087     }
2088     // Only the least significant bits of Imm are used.
2089     // Using int8_t to ensure it will be sign extended to the int64_t that
2090     // setImm takes in order to match isel behavior.
2091     int8_t Imm = MI.getOperand(3).getImm() & Mask;
2092     auto &WorkingMI = cloneIfNew(MI);
2093     WorkingMI.getOperand(3).setImm(Mask ^ Imm);
2094     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2095                                                    OpIdx1, OpIdx2);
2096   }
2097   case X86::INSERTPSrr:
2098   case X86::VINSERTPSrr:
2099   case X86::VINSERTPSZrr: {
2100     unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm();
2101     unsigned ZMask = Imm & 15;
2102     unsigned DstIdx = (Imm >> 4) & 3;
2103     unsigned SrcIdx = (Imm >> 6) & 3;
2104 
2105     // We can commute insertps if we zero 2 of the elements, the insertion is
2106     // "inline" and we don't override the insertion with a zero.
2107     if (DstIdx == SrcIdx && (ZMask & (1 << DstIdx)) == 0 &&
2108         llvm::popcount(ZMask) == 2) {
2109       unsigned AltIdx = llvm::countr_zero((ZMask | (1 << DstIdx)) ^ 15);
2110       assert(AltIdx < 4 && "Illegal insertion index");
2111       unsigned AltImm = (AltIdx << 6) | (AltIdx << 4) | ZMask;
2112       auto &WorkingMI = cloneIfNew(MI);
2113       WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(AltImm);
2114       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2115                                                      OpIdx1, OpIdx2);
2116     }
2117     return nullptr;
2118   }
2119   case X86::MOVSDrr:
2120   case X86::MOVSSrr:
2121   case X86::VMOVSDrr:
2122   case X86::VMOVSSrr:{
2123     // On SSE41 or later we can commute a MOVSS/MOVSD to a BLENDPS/BLENDPD.
2124     if (Subtarget.hasSSE41()) {
2125       unsigned Mask, Opc;
2126       switch (MI.getOpcode()) {
2127       default: llvm_unreachable("Unreachable!");
2128       case X86::MOVSDrr:  Opc = X86::BLENDPDrri;  Mask = 0x02; break;
2129       case X86::MOVSSrr:  Opc = X86::BLENDPSrri;  Mask = 0x0E; break;
2130       case X86::VMOVSDrr: Opc = X86::VBLENDPDrri; Mask = 0x02; break;
2131       case X86::VMOVSSrr: Opc = X86::VBLENDPSrri; Mask = 0x0E; break;
2132       }
2133 
2134       auto &WorkingMI = cloneIfNew(MI);
2135       WorkingMI.setDesc(get(Opc));
2136       WorkingMI.addOperand(MachineOperand::CreateImm(Mask));
2137       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2138                                                      OpIdx1, OpIdx2);
2139     }
2140 
2141     // Convert to SHUFPD.
2142     assert(MI.getOpcode() == X86::MOVSDrr &&
2143            "Can only commute MOVSDrr without SSE4.1");
2144 
2145     auto &WorkingMI = cloneIfNew(MI);
2146     WorkingMI.setDesc(get(X86::SHUFPDrri));
2147     WorkingMI.addOperand(MachineOperand::CreateImm(0x02));
2148     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2149                                                    OpIdx1, OpIdx2);
2150   }
2151   case X86::SHUFPDrri: {
2152     // Commute to MOVSD.
2153     assert(MI.getOperand(3).getImm() == 0x02 && "Unexpected immediate!");
2154     auto &WorkingMI = cloneIfNew(MI);
2155     WorkingMI.setDesc(get(X86::MOVSDrr));
2156     WorkingMI.removeOperand(3);
2157     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2158                                                    OpIdx1, OpIdx2);
2159   }
2160   case X86::PCLMULQDQrr:
2161   case X86::VPCLMULQDQrr:
2162   case X86::VPCLMULQDQYrr:
2163   case X86::VPCLMULQDQZrr:
2164   case X86::VPCLMULQDQZ128rr:
2165   case X86::VPCLMULQDQZ256rr: {
2166     // SRC1 64bits = Imm[0] ? SRC1[127:64] : SRC1[63:0]
2167     // SRC2 64bits = Imm[4] ? SRC2[127:64] : SRC2[63:0]
2168     unsigned Imm = MI.getOperand(3).getImm();
2169     unsigned Src1Hi = Imm & 0x01;
2170     unsigned Src2Hi = Imm & 0x10;
2171     auto &WorkingMI = cloneIfNew(MI);
2172     WorkingMI.getOperand(3).setImm((Src1Hi << 4) | (Src2Hi >> 4));
2173     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2174                                                    OpIdx1, OpIdx2);
2175   }
2176   case X86::VPCMPBZ128rri:  case X86::VPCMPUBZ128rri:
2177   case X86::VPCMPBZ256rri:  case X86::VPCMPUBZ256rri:
2178   case X86::VPCMPBZrri:     case X86::VPCMPUBZrri:
2179   case X86::VPCMPDZ128rri:  case X86::VPCMPUDZ128rri:
2180   case X86::VPCMPDZ256rri:  case X86::VPCMPUDZ256rri:
2181   case X86::VPCMPDZrri:     case X86::VPCMPUDZrri:
2182   case X86::VPCMPQZ128rri:  case X86::VPCMPUQZ128rri:
2183   case X86::VPCMPQZ256rri:  case X86::VPCMPUQZ256rri:
2184   case X86::VPCMPQZrri:     case X86::VPCMPUQZrri:
2185   case X86::VPCMPWZ128rri:  case X86::VPCMPUWZ128rri:
2186   case X86::VPCMPWZ256rri:  case X86::VPCMPUWZ256rri:
2187   case X86::VPCMPWZrri:     case X86::VPCMPUWZrri:
2188   case X86::VPCMPBZ128rrik: case X86::VPCMPUBZ128rrik:
2189   case X86::VPCMPBZ256rrik: case X86::VPCMPUBZ256rrik:
2190   case X86::VPCMPBZrrik:    case X86::VPCMPUBZrrik:
2191   case X86::VPCMPDZ128rrik: case X86::VPCMPUDZ128rrik:
2192   case X86::VPCMPDZ256rrik: case X86::VPCMPUDZ256rrik:
2193   case X86::VPCMPDZrrik:    case X86::VPCMPUDZrrik:
2194   case X86::VPCMPQZ128rrik: case X86::VPCMPUQZ128rrik:
2195   case X86::VPCMPQZ256rrik: case X86::VPCMPUQZ256rrik:
2196   case X86::VPCMPQZrrik:    case X86::VPCMPUQZrrik:
2197   case X86::VPCMPWZ128rrik: case X86::VPCMPUWZ128rrik:
2198   case X86::VPCMPWZ256rrik: case X86::VPCMPUWZ256rrik:
2199   case X86::VPCMPWZrrik:    case X86::VPCMPUWZrrik: {
2200     // Flip comparison mode immediate (if necessary).
2201     unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm() & 0x7;
2202     Imm = X86::getSwappedVPCMPImm(Imm);
2203     auto &WorkingMI = cloneIfNew(MI);
2204     WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(Imm);
2205     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2206                                                    OpIdx1, OpIdx2);
2207   }
2208   case X86::VPCOMBri: case X86::VPCOMUBri:
2209   case X86::VPCOMDri: case X86::VPCOMUDri:
2210   case X86::VPCOMQri: case X86::VPCOMUQri:
2211   case X86::VPCOMWri: case X86::VPCOMUWri: {
2212     // Flip comparison mode immediate (if necessary).
2213     unsigned Imm = MI.getOperand(3).getImm() & 0x7;
2214     Imm = X86::getSwappedVPCOMImm(Imm);
2215     auto &WorkingMI = cloneIfNew(MI);
2216     WorkingMI.getOperand(3).setImm(Imm);
2217     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2218                                                    OpIdx1, OpIdx2);
2219   }
2220   case X86::VCMPSDZrr:
2221   case X86::VCMPSSZrr:
2222   case X86::VCMPPDZrri:
2223   case X86::VCMPPSZrri:
2224   case X86::VCMPSHZrr:
2225   case X86::VCMPPHZrri:
2226   case X86::VCMPPHZ128rri:
2227   case X86::VCMPPHZ256rri:
2228   case X86::VCMPPDZ128rri:
2229   case X86::VCMPPSZ128rri:
2230   case X86::VCMPPDZ256rri:
2231   case X86::VCMPPSZ256rri:
2232   case X86::VCMPPDZrrik:
2233   case X86::VCMPPSZrrik:
2234   case X86::VCMPPDZ128rrik:
2235   case X86::VCMPPSZ128rrik:
2236   case X86::VCMPPDZ256rrik:
2237   case X86::VCMPPSZ256rrik: {
2238     unsigned Imm =
2239                 MI.getOperand(MI.getNumExplicitOperands() - 1).getImm() & 0x1f;
2240     Imm = X86::getSwappedVCMPImm(Imm);
2241     auto &WorkingMI = cloneIfNew(MI);
2242     WorkingMI.getOperand(MI.getNumExplicitOperands() - 1).setImm(Imm);
2243     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2244                                                    OpIdx1, OpIdx2);
2245   }
2246   case X86::VPERM2F128rr:
2247   case X86::VPERM2I128rr: {
2248     // Flip permute source immediate.
2249     // Imm & 0x02: lo = if set, select Op1.lo/hi else Op0.lo/hi.
2250     // Imm & 0x20: hi = if set, select Op1.lo/hi else Op0.lo/hi.
2251     int8_t Imm = MI.getOperand(3).getImm() & 0xFF;
2252     auto &WorkingMI = cloneIfNew(MI);
2253     WorkingMI.getOperand(3).setImm(Imm ^ 0x22);
2254     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2255                                                    OpIdx1, OpIdx2);
2256   }
2257   case X86::MOVHLPSrr:
2258   case X86::UNPCKHPDrr:
2259   case X86::VMOVHLPSrr:
2260   case X86::VUNPCKHPDrr:
2261   case X86::VMOVHLPSZrr:
2262   case X86::VUNPCKHPDZ128rr: {
2263     assert(Subtarget.hasSSE2() && "Commuting MOVHLP/UNPCKHPD requires SSE2!");
2264 
2265     unsigned Opc = MI.getOpcode();
2266     switch (Opc) {
2267     default: llvm_unreachable("Unreachable!");
2268     case X86::MOVHLPSrr:       Opc = X86::UNPCKHPDrr;      break;
2269     case X86::UNPCKHPDrr:      Opc = X86::MOVHLPSrr;       break;
2270     case X86::VMOVHLPSrr:      Opc = X86::VUNPCKHPDrr;     break;
2271     case X86::VUNPCKHPDrr:     Opc = X86::VMOVHLPSrr;      break;
2272     case X86::VMOVHLPSZrr:     Opc = X86::VUNPCKHPDZ128rr; break;
2273     case X86::VUNPCKHPDZ128rr: Opc = X86::VMOVHLPSZrr;     break;
2274     }
2275     auto &WorkingMI = cloneIfNew(MI);
2276     WorkingMI.setDesc(get(Opc));
2277     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2278                                                    OpIdx1, OpIdx2);
2279   }
2280   case X86::CMOV16rr:  case X86::CMOV32rr:  case X86::CMOV64rr: {
2281     auto &WorkingMI = cloneIfNew(MI);
2282     unsigned OpNo = MI.getDesc().getNumOperands() - 1;
2283     X86::CondCode CC = static_cast<X86::CondCode>(MI.getOperand(OpNo).getImm());
2284     WorkingMI.getOperand(OpNo).setImm(X86::GetOppositeBranchCondition(CC));
2285     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2286                                                    OpIdx1, OpIdx2);
2287   }
2288   case X86::VPTERNLOGDZrri:      case X86::VPTERNLOGDZrmi:
2289   case X86::VPTERNLOGDZ128rri:   case X86::VPTERNLOGDZ128rmi:
2290   case X86::VPTERNLOGDZ256rri:   case X86::VPTERNLOGDZ256rmi:
2291   case X86::VPTERNLOGQZrri:      case X86::VPTERNLOGQZrmi:
2292   case X86::VPTERNLOGQZ128rri:   case X86::VPTERNLOGQZ128rmi:
2293   case X86::VPTERNLOGQZ256rri:   case X86::VPTERNLOGQZ256rmi:
2294   case X86::VPTERNLOGDZrrik:
2295   case X86::VPTERNLOGDZ128rrik:
2296   case X86::VPTERNLOGDZ256rrik:
2297   case X86::VPTERNLOGQZrrik:
2298   case X86::VPTERNLOGQZ128rrik:
2299   case X86::VPTERNLOGQZ256rrik:
2300   case X86::VPTERNLOGDZrrikz:    case X86::VPTERNLOGDZrmikz:
2301   case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
2302   case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
2303   case X86::VPTERNLOGQZrrikz:    case X86::VPTERNLOGQZrmikz:
2304   case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
2305   case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
2306   case X86::VPTERNLOGDZ128rmbi:
2307   case X86::VPTERNLOGDZ256rmbi:
2308   case X86::VPTERNLOGDZrmbi:
2309   case X86::VPTERNLOGQZ128rmbi:
2310   case X86::VPTERNLOGQZ256rmbi:
2311   case X86::VPTERNLOGQZrmbi:
2312   case X86::VPTERNLOGDZ128rmbikz:
2313   case X86::VPTERNLOGDZ256rmbikz:
2314   case X86::VPTERNLOGDZrmbikz:
2315   case X86::VPTERNLOGQZ128rmbikz:
2316   case X86::VPTERNLOGQZ256rmbikz:
2317   case X86::VPTERNLOGQZrmbikz: {
2318     auto &WorkingMI = cloneIfNew(MI);
2319     commuteVPTERNLOG(WorkingMI, OpIdx1, OpIdx2);
2320     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2321                                                    OpIdx1, OpIdx2);
2322   }
2323   default: {
2324     if (isCommutableVPERMV3Instruction(MI.getOpcode())) {
2325       unsigned Opc = getCommutedVPERMV3Opcode(MI.getOpcode());
2326       auto &WorkingMI = cloneIfNew(MI);
2327       WorkingMI.setDesc(get(Opc));
2328       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2329                                                      OpIdx1, OpIdx2);
2330     }
2331 
2332     const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
2333                                                       MI.getDesc().TSFlags);
2334     if (FMA3Group) {
2335       unsigned Opc =
2336         getFMA3OpcodeToCommuteOperands(MI, OpIdx1, OpIdx2, *FMA3Group);
2337       auto &WorkingMI = cloneIfNew(MI);
2338       WorkingMI.setDesc(get(Opc));
2339       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
2340                                                      OpIdx1, OpIdx2);
2341     }
2342 
2343     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2344   }
2345   }
2346 }
2347 
2348 bool
2349 X86InstrInfo::findThreeSrcCommutedOpIndices(const MachineInstr &MI,
2350                                             unsigned &SrcOpIdx1,
2351                                             unsigned &SrcOpIdx2,
2352                                             bool IsIntrinsic) const {
2353   uint64_t TSFlags = MI.getDesc().TSFlags;
2354 
2355   unsigned FirstCommutableVecOp = 1;
2356   unsigned LastCommutableVecOp = 3;
2357   unsigned KMaskOp = -1U;
2358   if (X86II::isKMasked(TSFlags)) {
2359     // For k-zero-masked operations it is Ok to commute the first vector
2360     // operand. Unless this is an intrinsic instruction.
2361     // For regular k-masked operations a conservative choice is done as the
2362     // elements of the first vector operand, for which the corresponding bit
2363     // in the k-mask operand is set to 0, are copied to the result of the
2364     // instruction.
2365     // TODO/FIXME: The commute still may be legal if it is known that the
2366     // k-mask operand is set to either all ones or all zeroes.
2367     // It is also Ok to commute the 1st operand if all users of MI use only
2368     // the elements enabled by the k-mask operand. For example,
2369     //   v4 = VFMADD213PSZrk v1, k, v2, v3; // v1[i] = k[i] ? v2[i]*v1[i]+v3[i]
2370     //                                                     : v1[i];
2371     //   VMOVAPSZmrk <mem_addr>, k, v4; // this is the ONLY user of v4 ->
2372     //                                  // Ok, to commute v1 in FMADD213PSZrk.
2373 
2374     // The k-mask operand has index = 2 for masked and zero-masked operations.
2375     KMaskOp = 2;
2376 
2377     // The operand with index = 1 is used as a source for those elements for
2378     // which the corresponding bit in the k-mask is set to 0.
2379     if (X86II::isKMergeMasked(TSFlags) || IsIntrinsic)
2380       FirstCommutableVecOp = 3;
2381 
2382     LastCommutableVecOp++;
2383   } else if (IsIntrinsic) {
2384     // Commuting the first operand of an intrinsic instruction isn't possible
2385     // unless we can prove that only the lowest element of the result is used.
2386     FirstCommutableVecOp = 2;
2387   }
2388 
2389   if (isMem(MI, LastCommutableVecOp))
2390     LastCommutableVecOp--;
2391 
2392   // Only the first RegOpsNum operands are commutable.
2393   // Also, the value 'CommuteAnyOperandIndex' is valid here as it means
2394   // that the operand is not specified/fixed.
2395   if (SrcOpIdx1 != CommuteAnyOperandIndex &&
2396       (SrcOpIdx1 < FirstCommutableVecOp || SrcOpIdx1 > LastCommutableVecOp ||
2397        SrcOpIdx1 == KMaskOp))
2398     return false;
2399   if (SrcOpIdx2 != CommuteAnyOperandIndex &&
2400       (SrcOpIdx2 < FirstCommutableVecOp || SrcOpIdx2 > LastCommutableVecOp ||
2401        SrcOpIdx2 == KMaskOp))
2402     return false;
2403 
2404   // Look for two different register operands assumed to be commutable
2405   // regardless of the FMA opcode. The FMA opcode is adjusted later.
2406   if (SrcOpIdx1 == CommuteAnyOperandIndex ||
2407       SrcOpIdx2 == CommuteAnyOperandIndex) {
2408     unsigned CommutableOpIdx2 = SrcOpIdx2;
2409 
2410     // At least one of operands to be commuted is not specified and
2411     // this method is free to choose appropriate commutable operands.
2412     if (SrcOpIdx1 == SrcOpIdx2)
2413       // Both of operands are not fixed. By default set one of commutable
2414       // operands to the last register operand of the instruction.
2415       CommutableOpIdx2 = LastCommutableVecOp;
2416     else if (SrcOpIdx2 == CommuteAnyOperandIndex)
2417       // Only one of operands is not fixed.
2418       CommutableOpIdx2 = SrcOpIdx1;
2419 
2420     // CommutableOpIdx2 is well defined now. Let's choose another commutable
2421     // operand and assign its index to CommutableOpIdx1.
2422     Register Op2Reg = MI.getOperand(CommutableOpIdx2).getReg();
2423 
2424     unsigned CommutableOpIdx1;
2425     for (CommutableOpIdx1 = LastCommutableVecOp;
2426          CommutableOpIdx1 >= FirstCommutableVecOp; CommutableOpIdx1--) {
2427       // Just ignore and skip the k-mask operand.
2428       if (CommutableOpIdx1 == KMaskOp)
2429         continue;
2430 
2431       // The commuted operands must have different registers.
2432       // Otherwise, the commute transformation does not change anything and
2433       // is useless then.
2434       if (Op2Reg != MI.getOperand(CommutableOpIdx1).getReg())
2435         break;
2436     }
2437 
2438     // No appropriate commutable operands were found.
2439     if (CommutableOpIdx1 < FirstCommutableVecOp)
2440       return false;
2441 
2442     // Assign the found pair of commutable indices to SrcOpIdx1 and SrcOpidx2
2443     // to return those values.
2444     if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2445                               CommutableOpIdx1, CommutableOpIdx2))
2446       return false;
2447   }
2448 
2449   return true;
2450 }
2451 
2452 bool X86InstrInfo::findCommutedOpIndices(const MachineInstr &MI,
2453                                          unsigned &SrcOpIdx1,
2454                                          unsigned &SrcOpIdx2) const {
2455   const MCInstrDesc &Desc = MI.getDesc();
2456   if (!Desc.isCommutable())
2457     return false;
2458 
2459   switch (MI.getOpcode()) {
2460   case X86::CMPSDrr:
2461   case X86::CMPSSrr:
2462   case X86::CMPPDrri:
2463   case X86::CMPPSrri:
2464   case X86::VCMPSDrr:
2465   case X86::VCMPSSrr:
2466   case X86::VCMPPDrri:
2467   case X86::VCMPPSrri:
2468   case X86::VCMPPDYrri:
2469   case X86::VCMPPSYrri:
2470   case X86::VCMPSDZrr:
2471   case X86::VCMPSSZrr:
2472   case X86::VCMPPDZrri:
2473   case X86::VCMPPSZrri:
2474   case X86::VCMPSHZrr:
2475   case X86::VCMPPHZrri:
2476   case X86::VCMPPHZ128rri:
2477   case X86::VCMPPHZ256rri:
2478   case X86::VCMPPDZ128rri:
2479   case X86::VCMPPSZ128rri:
2480   case X86::VCMPPDZ256rri:
2481   case X86::VCMPPSZ256rri:
2482   case X86::VCMPPDZrrik:
2483   case X86::VCMPPSZrrik:
2484   case X86::VCMPPDZ128rrik:
2485   case X86::VCMPPSZ128rrik:
2486   case X86::VCMPPDZ256rrik:
2487   case X86::VCMPPSZ256rrik: {
2488     unsigned OpOffset = X86II::isKMasked(Desc.TSFlags) ? 1 : 0;
2489 
2490     // Float comparison can be safely commuted for
2491     // Ordered/Unordered/Equal/NotEqual tests
2492     unsigned Imm = MI.getOperand(3 + OpOffset).getImm() & 0x7;
2493     switch (Imm) {
2494     default:
2495       // EVEX versions can be commuted.
2496       if ((Desc.TSFlags & X86II::EncodingMask) == X86II::EVEX)
2497         break;
2498       return false;
2499     case 0x00: // EQUAL
2500     case 0x03: // UNORDERED
2501     case 0x04: // NOT EQUAL
2502     case 0x07: // ORDERED
2503       break;
2504     }
2505 
2506     // The indices of the commutable operands are 1 and 2 (or 2 and 3
2507     // when masked).
2508     // Assign them to the returned operand indices here.
2509     return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 1 + OpOffset,
2510                                 2 + OpOffset);
2511   }
2512   case X86::MOVSSrr:
2513     // X86::MOVSDrr is always commutable. MOVSS is only commutable if we can
2514     // form sse4.1 blend. We assume VMOVSSrr/VMOVSDrr is always commutable since
2515     // AVX implies sse4.1.
2516     if (Subtarget.hasSSE41())
2517       return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2518     return false;
2519   case X86::SHUFPDrri:
2520     // We can commute this to MOVSD.
2521     if (MI.getOperand(3).getImm() == 0x02)
2522       return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2523     return false;
2524   case X86::MOVHLPSrr:
2525   case X86::UNPCKHPDrr:
2526   case X86::VMOVHLPSrr:
2527   case X86::VUNPCKHPDrr:
2528   case X86::VMOVHLPSZrr:
2529   case X86::VUNPCKHPDZ128rr:
2530     if (Subtarget.hasSSE2())
2531       return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2532     return false;
2533   case X86::VPTERNLOGDZrri:      case X86::VPTERNLOGDZrmi:
2534   case X86::VPTERNLOGDZ128rri:   case X86::VPTERNLOGDZ128rmi:
2535   case X86::VPTERNLOGDZ256rri:   case X86::VPTERNLOGDZ256rmi:
2536   case X86::VPTERNLOGQZrri:      case X86::VPTERNLOGQZrmi:
2537   case X86::VPTERNLOGQZ128rri:   case X86::VPTERNLOGQZ128rmi:
2538   case X86::VPTERNLOGQZ256rri:   case X86::VPTERNLOGQZ256rmi:
2539   case X86::VPTERNLOGDZrrik:
2540   case X86::VPTERNLOGDZ128rrik:
2541   case X86::VPTERNLOGDZ256rrik:
2542   case X86::VPTERNLOGQZrrik:
2543   case X86::VPTERNLOGQZ128rrik:
2544   case X86::VPTERNLOGQZ256rrik:
2545   case X86::VPTERNLOGDZrrikz:    case X86::VPTERNLOGDZrmikz:
2546   case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
2547   case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
2548   case X86::VPTERNLOGQZrrikz:    case X86::VPTERNLOGQZrmikz:
2549   case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
2550   case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
2551   case X86::VPTERNLOGDZ128rmbi:
2552   case X86::VPTERNLOGDZ256rmbi:
2553   case X86::VPTERNLOGDZrmbi:
2554   case X86::VPTERNLOGQZ128rmbi:
2555   case X86::VPTERNLOGQZ256rmbi:
2556   case X86::VPTERNLOGQZrmbi:
2557   case X86::VPTERNLOGDZ128rmbikz:
2558   case X86::VPTERNLOGDZ256rmbikz:
2559   case X86::VPTERNLOGDZrmbikz:
2560   case X86::VPTERNLOGQZ128rmbikz:
2561   case X86::VPTERNLOGQZ256rmbikz:
2562   case X86::VPTERNLOGQZrmbikz:
2563     return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2564   case X86::VPDPWSSDYrr:
2565   case X86::VPDPWSSDrr:
2566   case X86::VPDPWSSDSYrr:
2567   case X86::VPDPWSSDSrr:
2568   case X86::VPDPWUUDrr:
2569   case X86::VPDPWUUDYrr:
2570   case X86::VPDPWUUDSrr:
2571   case X86::VPDPWUUDSYrr:
2572   case X86::VPDPBSSDSrr:
2573   case X86::VPDPBSSDSYrr:
2574   case X86::VPDPBSSDrr:
2575   case X86::VPDPBSSDYrr:
2576   case X86::VPDPBUUDSrr:
2577   case X86::VPDPBUUDSYrr:
2578   case X86::VPDPBUUDrr:
2579   case X86::VPDPBUUDYrr:
2580   case X86::VPDPWSSDZ128r:
2581   case X86::VPDPWSSDZ128rk:
2582   case X86::VPDPWSSDZ128rkz:
2583   case X86::VPDPWSSDZ256r:
2584   case X86::VPDPWSSDZ256rk:
2585   case X86::VPDPWSSDZ256rkz:
2586   case X86::VPDPWSSDZr:
2587   case X86::VPDPWSSDZrk:
2588   case X86::VPDPWSSDZrkz:
2589   case X86::VPDPWSSDSZ128r:
2590   case X86::VPDPWSSDSZ128rk:
2591   case X86::VPDPWSSDSZ128rkz:
2592   case X86::VPDPWSSDSZ256r:
2593   case X86::VPDPWSSDSZ256rk:
2594   case X86::VPDPWSSDSZ256rkz:
2595   case X86::VPDPWSSDSZr:
2596   case X86::VPDPWSSDSZrk:
2597   case X86::VPDPWSSDSZrkz:
2598   case X86::VPMADD52HUQrr:
2599   case X86::VPMADD52HUQYrr:
2600   case X86::VPMADD52HUQZ128r:
2601   case X86::VPMADD52HUQZ128rk:
2602   case X86::VPMADD52HUQZ128rkz:
2603   case X86::VPMADD52HUQZ256r:
2604   case X86::VPMADD52HUQZ256rk:
2605   case X86::VPMADD52HUQZ256rkz:
2606   case X86::VPMADD52HUQZr:
2607   case X86::VPMADD52HUQZrk:
2608   case X86::VPMADD52HUQZrkz:
2609   case X86::VPMADD52LUQrr:
2610   case X86::VPMADD52LUQYrr:
2611   case X86::VPMADD52LUQZ128r:
2612   case X86::VPMADD52LUQZ128rk:
2613   case X86::VPMADD52LUQZ128rkz:
2614   case X86::VPMADD52LUQZ256r:
2615   case X86::VPMADD52LUQZ256rk:
2616   case X86::VPMADD52LUQZ256rkz:
2617   case X86::VPMADD52LUQZr:
2618   case X86::VPMADD52LUQZrk:
2619   case X86::VPMADD52LUQZrkz:
2620   case X86::VFMADDCPHZr:
2621   case X86::VFMADDCPHZrk:
2622   case X86::VFMADDCPHZrkz:
2623   case X86::VFMADDCPHZ128r:
2624   case X86::VFMADDCPHZ128rk:
2625   case X86::VFMADDCPHZ128rkz:
2626   case X86::VFMADDCPHZ256r:
2627   case X86::VFMADDCPHZ256rk:
2628   case X86::VFMADDCPHZ256rkz:
2629   case X86::VFMADDCSHZr:
2630   case X86::VFMADDCSHZrk:
2631   case X86::VFMADDCSHZrkz: {
2632     unsigned CommutableOpIdx1 = 2;
2633     unsigned CommutableOpIdx2 = 3;
2634     if (X86II::isKMasked(Desc.TSFlags)) {
2635       // Skip the mask register.
2636       ++CommutableOpIdx1;
2637       ++CommutableOpIdx2;
2638     }
2639     if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2640                               CommutableOpIdx1, CommutableOpIdx2))
2641       return false;
2642     if (!MI.getOperand(SrcOpIdx1).isReg() ||
2643         !MI.getOperand(SrcOpIdx2).isReg())
2644       // No idea.
2645       return false;
2646     return true;
2647   }
2648 
2649   default:
2650     const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
2651                                                       MI.getDesc().TSFlags);
2652     if (FMA3Group)
2653       return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2,
2654                                            FMA3Group->isIntrinsic());
2655 
2656     // Handled masked instructions since we need to skip over the mask input
2657     // and the preserved input.
2658     if (X86II::isKMasked(Desc.TSFlags)) {
2659       // First assume that the first input is the mask operand and skip past it.
2660       unsigned CommutableOpIdx1 = Desc.getNumDefs() + 1;
2661       unsigned CommutableOpIdx2 = Desc.getNumDefs() + 2;
2662       // Check if the first input is tied. If there isn't one then we only
2663       // need to skip the mask operand which we did above.
2664       if ((MI.getDesc().getOperandConstraint(Desc.getNumDefs(),
2665                                              MCOI::TIED_TO) != -1)) {
2666         // If this is zero masking instruction with a tied operand, we need to
2667         // move the first index back to the first input since this must
2668         // be a 3 input instruction and we want the first two non-mask inputs.
2669         // Otherwise this is a 2 input instruction with a preserved input and
2670         // mask, so we need to move the indices to skip one more input.
2671         if (X86II::isKMergeMasked(Desc.TSFlags)) {
2672           ++CommutableOpIdx1;
2673           ++CommutableOpIdx2;
2674         } else {
2675           --CommutableOpIdx1;
2676         }
2677       }
2678 
2679       if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2680                                 CommutableOpIdx1, CommutableOpIdx2))
2681         return false;
2682 
2683       if (!MI.getOperand(SrcOpIdx1).isReg() ||
2684           !MI.getOperand(SrcOpIdx2).isReg())
2685         // No idea.
2686         return false;
2687       return true;
2688     }
2689 
2690     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2691   }
2692   return false;
2693 }
2694 
2695 static bool isConvertibleLEA(MachineInstr *MI) {
2696   unsigned Opcode = MI->getOpcode();
2697   if (Opcode != X86::LEA32r && Opcode != X86::LEA64r &&
2698       Opcode != X86::LEA64_32r)
2699     return false;
2700 
2701   const MachineOperand &Scale = MI->getOperand(1 + X86::AddrScaleAmt);
2702   const MachineOperand &Disp = MI->getOperand(1 + X86::AddrDisp);
2703   const MachineOperand &Segment = MI->getOperand(1 + X86::AddrSegmentReg);
2704 
2705   if (Segment.getReg() != 0 || !Disp.isImm() || Disp.getImm() != 0 ||
2706       Scale.getImm() > 1)
2707     return false;
2708 
2709   return true;
2710 }
2711 
2712 bool X86InstrInfo::hasCommutePreference(MachineInstr &MI, bool &Commute) const {
2713   // Currently we're interested in following sequence only.
2714   //   r3 = lea r1, r2
2715   //   r5 = add r3, r4
2716   // Both r3 and r4 are killed in add, we hope the add instruction has the
2717   // operand order
2718   //   r5 = add r4, r3
2719   // So later in X86FixupLEAs the lea instruction can be rewritten as add.
2720   unsigned Opcode = MI.getOpcode();
2721   if (Opcode != X86::ADD32rr && Opcode != X86::ADD64rr)
2722     return false;
2723 
2724   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2725   Register Reg1 = MI.getOperand(1).getReg();
2726   Register Reg2 = MI.getOperand(2).getReg();
2727 
2728   // Check if Reg1 comes from LEA in the same MBB.
2729   if (MachineInstr *Inst = MRI.getUniqueVRegDef(Reg1)) {
2730     if (isConvertibleLEA(Inst) && Inst->getParent() == MI.getParent()) {
2731       Commute = true;
2732       return true;
2733     }
2734   }
2735 
2736   // Check if Reg2 comes from LEA in the same MBB.
2737   if (MachineInstr *Inst = MRI.getUniqueVRegDef(Reg2)) {
2738     if (isConvertibleLEA(Inst) && Inst->getParent() == MI.getParent()) {
2739       Commute = false;
2740       return true;
2741     }
2742   }
2743 
2744   return false;
2745 }
2746 
2747 int X86::getCondSrcNoFromDesc(const MCInstrDesc &MCID) {
2748   unsigned Opcode = MCID.getOpcode();
2749   if (!(X86::isJCC(Opcode) || X86::isSETCC(Opcode) || X86::isCMOVCC(Opcode)))
2750     return -1;
2751   // Assume that condition code is always the last use operand.
2752   unsigned NumUses = MCID.getNumOperands() - MCID.getNumDefs();
2753   return NumUses - 1;
2754 }
2755 
2756 X86::CondCode X86::getCondFromMI(const MachineInstr &MI) {
2757   const MCInstrDesc &MCID = MI.getDesc();
2758   int CondNo = getCondSrcNoFromDesc(MCID);
2759   if (CondNo < 0)
2760     return X86::COND_INVALID;
2761   CondNo += MCID.getNumDefs();
2762   return static_cast<X86::CondCode>(MI.getOperand(CondNo).getImm());
2763 }
2764 
2765 X86::CondCode X86::getCondFromBranch(const MachineInstr &MI) {
2766   return X86::isJCC(MI.getOpcode()) ? X86::getCondFromMI(MI)
2767                                     : X86::COND_INVALID;
2768 }
2769 
2770 X86::CondCode X86::getCondFromSETCC(const MachineInstr &MI) {
2771   return X86::isSETCC(MI.getOpcode()) ? X86::getCondFromMI(MI)
2772                                       : X86::COND_INVALID;
2773 }
2774 
2775 X86::CondCode X86::getCondFromCMov(const MachineInstr &MI) {
2776   return X86::isCMOVCC(MI.getOpcode()) ? X86::getCondFromMI(MI)
2777                                        : X86::COND_INVALID;
2778 }
2779 
2780 /// Return the inverse of the specified condition,
2781 /// e.g. turning COND_E to COND_NE.
2782 X86::CondCode X86::GetOppositeBranchCondition(X86::CondCode CC) {
2783   switch (CC) {
2784   default: llvm_unreachable("Illegal condition code!");
2785   case X86::COND_E:  return X86::COND_NE;
2786   case X86::COND_NE: return X86::COND_E;
2787   case X86::COND_L:  return X86::COND_GE;
2788   case X86::COND_LE: return X86::COND_G;
2789   case X86::COND_G:  return X86::COND_LE;
2790   case X86::COND_GE: return X86::COND_L;
2791   case X86::COND_B:  return X86::COND_AE;
2792   case X86::COND_BE: return X86::COND_A;
2793   case X86::COND_A:  return X86::COND_BE;
2794   case X86::COND_AE: return X86::COND_B;
2795   case X86::COND_S:  return X86::COND_NS;
2796   case X86::COND_NS: return X86::COND_S;
2797   case X86::COND_P:  return X86::COND_NP;
2798   case X86::COND_NP: return X86::COND_P;
2799   case X86::COND_O:  return X86::COND_NO;
2800   case X86::COND_NO: return X86::COND_O;
2801   case X86::COND_NE_OR_P:  return X86::COND_E_AND_NP;
2802   case X86::COND_E_AND_NP: return X86::COND_NE_OR_P;
2803   }
2804 }
2805 
2806 /// Assuming the flags are set by MI(a,b), return the condition code if we
2807 /// modify the instructions such that flags are set by MI(b,a).
2808 static X86::CondCode getSwappedCondition(X86::CondCode CC) {
2809   switch (CC) {
2810   default: return X86::COND_INVALID;
2811   case X86::COND_E:  return X86::COND_E;
2812   case X86::COND_NE: return X86::COND_NE;
2813   case X86::COND_L:  return X86::COND_G;
2814   case X86::COND_LE: return X86::COND_GE;
2815   case X86::COND_G:  return X86::COND_L;
2816   case X86::COND_GE: return X86::COND_LE;
2817   case X86::COND_B:  return X86::COND_A;
2818   case X86::COND_BE: return X86::COND_AE;
2819   case X86::COND_A:  return X86::COND_B;
2820   case X86::COND_AE: return X86::COND_BE;
2821   }
2822 }
2823 
2824 std::pair<X86::CondCode, bool>
2825 X86::getX86ConditionCode(CmpInst::Predicate Predicate) {
2826   X86::CondCode CC = X86::COND_INVALID;
2827   bool NeedSwap = false;
2828   switch (Predicate) {
2829   default: break;
2830   // Floating-point Predicates
2831   case CmpInst::FCMP_UEQ: CC = X86::COND_E;       break;
2832   case CmpInst::FCMP_OLT: NeedSwap = true;        [[fallthrough]];
2833   case CmpInst::FCMP_OGT: CC = X86::COND_A;       break;
2834   case CmpInst::FCMP_OLE: NeedSwap = true;        [[fallthrough]];
2835   case CmpInst::FCMP_OGE: CC = X86::COND_AE;      break;
2836   case CmpInst::FCMP_UGT: NeedSwap = true;        [[fallthrough]];
2837   case CmpInst::FCMP_ULT: CC = X86::COND_B;       break;
2838   case CmpInst::FCMP_UGE: NeedSwap = true;        [[fallthrough]];
2839   case CmpInst::FCMP_ULE: CC = X86::COND_BE;      break;
2840   case CmpInst::FCMP_ONE: CC = X86::COND_NE;      break;
2841   case CmpInst::FCMP_UNO: CC = X86::COND_P;       break;
2842   case CmpInst::FCMP_ORD: CC = X86::COND_NP;      break;
2843   case CmpInst::FCMP_OEQ:                         [[fallthrough]];
2844   case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
2845 
2846   // Integer Predicates
2847   case CmpInst::ICMP_EQ:  CC = X86::COND_E;       break;
2848   case CmpInst::ICMP_NE:  CC = X86::COND_NE;      break;
2849   case CmpInst::ICMP_UGT: CC = X86::COND_A;       break;
2850   case CmpInst::ICMP_UGE: CC = X86::COND_AE;      break;
2851   case CmpInst::ICMP_ULT: CC = X86::COND_B;       break;
2852   case CmpInst::ICMP_ULE: CC = X86::COND_BE;      break;
2853   case CmpInst::ICMP_SGT: CC = X86::COND_G;       break;
2854   case CmpInst::ICMP_SGE: CC = X86::COND_GE;      break;
2855   case CmpInst::ICMP_SLT: CC = X86::COND_L;       break;
2856   case CmpInst::ICMP_SLE: CC = X86::COND_LE;      break;
2857   }
2858 
2859   return std::make_pair(CC, NeedSwap);
2860 }
2861 
2862 /// Return a cmov opcode for the given register size in bytes, and operand type.
2863 unsigned X86::getCMovOpcode(unsigned RegBytes, bool HasMemoryOperand) {
2864   switch(RegBytes) {
2865   default: llvm_unreachable("Illegal register size!");
2866   case 2: return HasMemoryOperand ? X86::CMOV16rm : X86::CMOV16rr;
2867   case 4: return HasMemoryOperand ? X86::CMOV32rm : X86::CMOV32rr;
2868   case 8: return HasMemoryOperand ? X86::CMOV64rm : X86::CMOV64rr;
2869   }
2870 }
2871 
2872 /// Get the VPCMP immediate for the given condition.
2873 unsigned X86::getVPCMPImmForCond(ISD::CondCode CC) {
2874   switch (CC) {
2875   default: llvm_unreachable("Unexpected SETCC condition");
2876   case ISD::SETNE:  return 4;
2877   case ISD::SETEQ:  return 0;
2878   case ISD::SETULT:
2879   case ISD::SETLT: return 1;
2880   case ISD::SETUGT:
2881   case ISD::SETGT: return 6;
2882   case ISD::SETUGE:
2883   case ISD::SETGE: return 5;
2884   case ISD::SETULE:
2885   case ISD::SETLE: return 2;
2886   }
2887 }
2888 
2889 /// Get the VPCMP immediate if the operands are swapped.
2890 unsigned X86::getSwappedVPCMPImm(unsigned Imm) {
2891   switch (Imm) {
2892   default: llvm_unreachable("Unreachable!");
2893   case 0x01: Imm = 0x06; break; // LT  -> NLE
2894   case 0x02: Imm = 0x05; break; // LE  -> NLT
2895   case 0x05: Imm = 0x02; break; // NLT -> LE
2896   case 0x06: Imm = 0x01; break; // NLE -> LT
2897   case 0x00: // EQ
2898   case 0x03: // FALSE
2899   case 0x04: // NE
2900   case 0x07: // TRUE
2901     break;
2902   }
2903 
2904   return Imm;
2905 }
2906 
2907 /// Get the VPCOM immediate if the operands are swapped.
2908 unsigned X86::getSwappedVPCOMImm(unsigned Imm) {
2909   switch (Imm) {
2910   default: llvm_unreachable("Unreachable!");
2911   case 0x00: Imm = 0x02; break; // LT -> GT
2912   case 0x01: Imm = 0x03; break; // LE -> GE
2913   case 0x02: Imm = 0x00; break; // GT -> LT
2914   case 0x03: Imm = 0x01; break; // GE -> LE
2915   case 0x04: // EQ
2916   case 0x05: // NE
2917   case 0x06: // FALSE
2918   case 0x07: // TRUE
2919     break;
2920   }
2921 
2922   return Imm;
2923 }
2924 
2925 /// Get the VCMP immediate if the operands are swapped.
2926 unsigned X86::getSwappedVCMPImm(unsigned Imm) {
2927   // Only need the lower 2 bits to distinquish.
2928   switch (Imm & 0x3) {
2929   default: llvm_unreachable("Unreachable!");
2930   case 0x00: case 0x03:
2931     // EQ/NE/TRUE/FALSE/ORD/UNORD don't change immediate when commuted.
2932     break;
2933   case 0x01: case 0x02:
2934     // Need to toggle bits 3:0. Bit 4 stays the same.
2935     Imm ^= 0xf;
2936     break;
2937   }
2938 
2939   return Imm;
2940 }
2941 
2942 /// Return true if the Reg is X87 register.
2943 static bool isX87Reg(unsigned Reg) {
2944   return (Reg == X86::FPCW || Reg == X86::FPSW ||
2945           (Reg >= X86::ST0 && Reg <= X86::ST7));
2946 }
2947 
2948 /// check if the instruction is X87 instruction
2949 bool X86::isX87Instruction(MachineInstr &MI) {
2950   for (const MachineOperand &MO : MI.operands()) {
2951     if (!MO.isReg())
2952       continue;
2953     if (isX87Reg(MO.getReg()))
2954       return true;
2955   }
2956   return false;
2957 }
2958 
2959 bool X86InstrInfo::isUnconditionalTailCall(const MachineInstr &MI) const {
2960   switch (MI.getOpcode()) {
2961   case X86::TCRETURNdi:
2962   case X86::TCRETURNri:
2963   case X86::TCRETURNmi:
2964   case X86::TCRETURNdi64:
2965   case X86::TCRETURNri64:
2966   case X86::TCRETURNmi64:
2967     return true;
2968   default:
2969     return false;
2970   }
2971 }
2972 
2973 bool X86InstrInfo::canMakeTailCallConditional(
2974     SmallVectorImpl<MachineOperand> &BranchCond,
2975     const MachineInstr &TailCall) const {
2976 
2977   const MachineFunction *MF = TailCall.getMF();
2978 
2979   if (MF->getTarget().getCodeModel() == CodeModel::Kernel) {
2980     // Kernel patches thunk calls in runtime, these should never be conditional.
2981     const MachineOperand &Target = TailCall.getOperand(0);
2982     if (Target.isSymbol()) {
2983       StringRef Symbol(Target.getSymbolName());
2984       // this is currently only relevant to r11/kernel indirect thunk.
2985       if (Symbol.equals("__x86_indirect_thunk_r11"))
2986         return false;
2987     }
2988   }
2989 
2990   if (TailCall.getOpcode() != X86::TCRETURNdi &&
2991       TailCall.getOpcode() != X86::TCRETURNdi64) {
2992     // Only direct calls can be done with a conditional branch.
2993     return false;
2994   }
2995 
2996   if (Subtarget.isTargetWin64() && MF->hasWinCFI()) {
2997     // Conditional tail calls confuse the Win64 unwinder.
2998     return false;
2999   }
3000 
3001   assert(BranchCond.size() == 1);
3002   if (BranchCond[0].getImm() > X86::LAST_VALID_COND) {
3003     // Can't make a conditional tail call with this condition.
3004     return false;
3005   }
3006 
3007   const X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
3008   if (X86FI->getTCReturnAddrDelta() != 0 ||
3009       TailCall.getOperand(1).getImm() != 0) {
3010     // A conditional tail call cannot do any stack adjustment.
3011     return false;
3012   }
3013 
3014   return true;
3015 }
3016 
3017 void X86InstrInfo::replaceBranchWithTailCall(
3018     MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &BranchCond,
3019     const MachineInstr &TailCall) const {
3020   assert(canMakeTailCallConditional(BranchCond, TailCall));
3021 
3022   MachineBasicBlock::iterator I = MBB.end();
3023   while (I != MBB.begin()) {
3024     --I;
3025     if (I->isDebugInstr())
3026       continue;
3027     if (!I->isBranch())
3028       assert(0 && "Can't find the branch to replace!");
3029 
3030     X86::CondCode CC = X86::getCondFromBranch(*I);
3031     assert(BranchCond.size() == 1);
3032     if (CC != BranchCond[0].getImm())
3033       continue;
3034 
3035     break;
3036   }
3037 
3038   unsigned Opc = TailCall.getOpcode() == X86::TCRETURNdi ? X86::TCRETURNdicc
3039                                                          : X86::TCRETURNdi64cc;
3040 
3041   auto MIB = BuildMI(MBB, I, MBB.findDebugLoc(I), get(Opc));
3042   MIB->addOperand(TailCall.getOperand(0)); // Destination.
3043   MIB.addImm(0); // Stack offset (not used).
3044   MIB->addOperand(BranchCond[0]); // Condition.
3045   MIB.copyImplicitOps(TailCall); // Regmask and (imp-used) parameters.
3046 
3047   // Add implicit uses and defs of all live regs potentially clobbered by the
3048   // call. This way they still appear live across the call.
3049   LivePhysRegs LiveRegs(getRegisterInfo());
3050   LiveRegs.addLiveOuts(MBB);
3051   SmallVector<std::pair<MCPhysReg, const MachineOperand *>, 8> Clobbers;
3052   LiveRegs.stepForward(*MIB, Clobbers);
3053   for (const auto &C : Clobbers) {
3054     MIB.addReg(C.first, RegState::Implicit);
3055     MIB.addReg(C.first, RegState::Implicit | RegState::Define);
3056   }
3057 
3058   I->eraseFromParent();
3059 }
3060 
3061 // Given a MBB and its TBB, find the FBB which was a fallthrough MBB (it may
3062 // not be a fallthrough MBB now due to layout changes). Return nullptr if the
3063 // fallthrough MBB cannot be identified.
3064 static MachineBasicBlock *getFallThroughMBB(MachineBasicBlock *MBB,
3065                                             MachineBasicBlock *TBB) {
3066   // Look for non-EHPad successors other than TBB. If we find exactly one, it
3067   // is the fallthrough MBB. If we find zero, then TBB is both the target MBB
3068   // and fallthrough MBB. If we find more than one, we cannot identify the
3069   // fallthrough MBB and should return nullptr.
3070   MachineBasicBlock *FallthroughBB = nullptr;
3071   for (MachineBasicBlock *Succ : MBB->successors()) {
3072     if (Succ->isEHPad() || (Succ == TBB && FallthroughBB))
3073       continue;
3074     // Return a nullptr if we found more than one fallthrough successor.
3075     if (FallthroughBB && FallthroughBB != TBB)
3076       return nullptr;
3077     FallthroughBB = Succ;
3078   }
3079   return FallthroughBB;
3080 }
3081 
3082 bool X86InstrInfo::AnalyzeBranchImpl(
3083     MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB,
3084     SmallVectorImpl<MachineOperand> &Cond,
3085     SmallVectorImpl<MachineInstr *> &CondBranches, bool AllowModify) const {
3086 
3087   // Start from the bottom of the block and work up, examining the
3088   // terminator instructions.
3089   MachineBasicBlock::iterator I = MBB.end();
3090   MachineBasicBlock::iterator UnCondBrIter = MBB.end();
3091   while (I != MBB.begin()) {
3092     --I;
3093     if (I->isDebugInstr())
3094       continue;
3095 
3096     // Working from the bottom, when we see a non-terminator instruction, we're
3097     // done.
3098     if (!isUnpredicatedTerminator(*I))
3099       break;
3100 
3101     // A terminator that isn't a branch can't easily be handled by this
3102     // analysis.
3103     if (!I->isBranch())
3104       return true;
3105 
3106     // Handle unconditional branches.
3107     if (I->getOpcode() == X86::JMP_1) {
3108       UnCondBrIter = I;
3109 
3110       if (!AllowModify) {
3111         TBB = I->getOperand(0).getMBB();
3112         continue;
3113       }
3114 
3115       // If the block has any instructions after a JMP, delete them.
3116       MBB.erase(std::next(I), MBB.end());
3117 
3118       Cond.clear();
3119       FBB = nullptr;
3120 
3121       // Delete the JMP if it's equivalent to a fall-through.
3122       if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
3123         TBB = nullptr;
3124         I->eraseFromParent();
3125         I = MBB.end();
3126         UnCondBrIter = MBB.end();
3127         continue;
3128       }
3129 
3130       // TBB is used to indicate the unconditional destination.
3131       TBB = I->getOperand(0).getMBB();
3132       continue;
3133     }
3134 
3135     // Handle conditional branches.
3136     X86::CondCode BranchCode = X86::getCondFromBranch(*I);
3137     if (BranchCode == X86::COND_INVALID)
3138       return true;  // Can't handle indirect branch.
3139 
3140     // In practice we should never have an undef eflags operand, if we do
3141     // abort here as we are not prepared to preserve the flag.
3142     if (I->findRegisterUseOperand(X86::EFLAGS)->isUndef())
3143       return true;
3144 
3145     // Working from the bottom, handle the first conditional branch.
3146     if (Cond.empty()) {
3147       FBB = TBB;
3148       TBB = I->getOperand(0).getMBB();
3149       Cond.push_back(MachineOperand::CreateImm(BranchCode));
3150       CondBranches.push_back(&*I);
3151       continue;
3152     }
3153 
3154     // Handle subsequent conditional branches. Only handle the case where all
3155     // conditional branches branch to the same destination and their condition
3156     // opcodes fit one of the special multi-branch idioms.
3157     assert(Cond.size() == 1);
3158     assert(TBB);
3159 
3160     // If the conditions are the same, we can leave them alone.
3161     X86::CondCode OldBranchCode = (X86::CondCode)Cond[0].getImm();
3162     auto NewTBB = I->getOperand(0).getMBB();
3163     if (OldBranchCode == BranchCode && TBB == NewTBB)
3164       continue;
3165 
3166     // If they differ, see if they fit one of the known patterns. Theoretically,
3167     // we could handle more patterns here, but we shouldn't expect to see them
3168     // if instruction selection has done a reasonable job.
3169     if (TBB == NewTBB &&
3170                ((OldBranchCode == X86::COND_P && BranchCode == X86::COND_NE) ||
3171                 (OldBranchCode == X86::COND_NE && BranchCode == X86::COND_P))) {
3172       BranchCode = X86::COND_NE_OR_P;
3173     } else if ((OldBranchCode == X86::COND_NP && BranchCode == X86::COND_NE) ||
3174                (OldBranchCode == X86::COND_E && BranchCode == X86::COND_P)) {
3175       if (NewTBB != (FBB ? FBB : getFallThroughMBB(&MBB, TBB)))
3176         return true;
3177 
3178       // X86::COND_E_AND_NP usually has two different branch destinations.
3179       //
3180       // JP B1
3181       // JE B2
3182       // JMP B1
3183       // B1:
3184       // B2:
3185       //
3186       // Here this condition branches to B2 only if NP && E. It has another
3187       // equivalent form:
3188       //
3189       // JNE B1
3190       // JNP B2
3191       // JMP B1
3192       // B1:
3193       // B2:
3194       //
3195       // Similarly it branches to B2 only if E && NP. That is why this condition
3196       // is named with COND_E_AND_NP.
3197       BranchCode = X86::COND_E_AND_NP;
3198     } else
3199       return true;
3200 
3201     // Update the MachineOperand.
3202     Cond[0].setImm(BranchCode);
3203     CondBranches.push_back(&*I);
3204   }
3205 
3206   return false;
3207 }
3208 
3209 bool X86InstrInfo::analyzeBranch(MachineBasicBlock &MBB,
3210                                  MachineBasicBlock *&TBB,
3211                                  MachineBasicBlock *&FBB,
3212                                  SmallVectorImpl<MachineOperand> &Cond,
3213                                  bool AllowModify) const {
3214   SmallVector<MachineInstr *, 4> CondBranches;
3215   return AnalyzeBranchImpl(MBB, TBB, FBB, Cond, CondBranches, AllowModify);
3216 }
3217 
3218 static int getJumpTableIndexFromAddr(const MachineInstr &MI) {
3219   const MCInstrDesc &Desc = MI.getDesc();
3220   int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
3221   assert(MemRefBegin >= 0 && "instr should have memory operand");
3222   MemRefBegin += X86II::getOperandBias(Desc);
3223 
3224   const MachineOperand &MO = MI.getOperand(MemRefBegin + X86::AddrDisp);
3225   if (!MO.isJTI())
3226     return -1;
3227 
3228   return MO.getIndex();
3229 }
3230 
3231 static int getJumpTableIndexFromReg(const MachineRegisterInfo &MRI,
3232                                     Register Reg) {
3233   if (!Reg.isVirtual())
3234     return -1;
3235   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
3236   if (MI == nullptr)
3237     return -1;
3238   unsigned Opcode = MI->getOpcode();
3239   if (Opcode != X86::LEA64r && Opcode != X86::LEA32r)
3240     return -1;
3241   return getJumpTableIndexFromAddr(*MI);
3242 }
3243 
3244 int X86InstrInfo::getJumpTableIndex(const MachineInstr &MI) const {
3245   unsigned Opcode = MI.getOpcode();
3246   // Switch-jump pattern for non-PIC code looks like:
3247   //   JMP64m $noreg, 8, %X, %jump-table.X, $noreg
3248   if (Opcode == X86::JMP64m || Opcode == X86::JMP32m) {
3249     return getJumpTableIndexFromAddr(MI);
3250   }
3251   // The pattern for PIC code looks like:
3252   //   %0 = LEA64r $rip, 1, $noreg, %jump-table.X
3253   //   %1 = MOVSX64rm32 %0, 4, XX, 0, $noreg
3254   //   %2 = ADD64rr %1, %0
3255   //   JMP64r %2
3256   if (Opcode == X86::JMP64r || Opcode == X86::JMP32r) {
3257     Register Reg = MI.getOperand(0).getReg();
3258     if (!Reg.isVirtual())
3259       return -1;
3260     const MachineFunction &MF = *MI.getParent()->getParent();
3261     const MachineRegisterInfo &MRI = MF.getRegInfo();
3262     MachineInstr *Add = MRI.getUniqueVRegDef(Reg);
3263     if (Add == nullptr)
3264       return -1;
3265     if (Add->getOpcode() != X86::ADD64rr && Add->getOpcode() != X86::ADD32rr)
3266       return -1;
3267     int JTI1 = getJumpTableIndexFromReg(MRI, Add->getOperand(1).getReg());
3268     if (JTI1 >= 0)
3269       return JTI1;
3270     int JTI2 = getJumpTableIndexFromReg(MRI, Add->getOperand(2).getReg());
3271     if (JTI2 >= 0)
3272       return JTI2;
3273   }
3274   return -1;
3275 }
3276 
3277 bool X86InstrInfo::analyzeBranchPredicate(MachineBasicBlock &MBB,
3278                                           MachineBranchPredicate &MBP,
3279                                           bool AllowModify) const {
3280   using namespace std::placeholders;
3281 
3282   SmallVector<MachineOperand, 4> Cond;
3283   SmallVector<MachineInstr *, 4> CondBranches;
3284   if (AnalyzeBranchImpl(MBB, MBP.TrueDest, MBP.FalseDest, Cond, CondBranches,
3285                         AllowModify))
3286     return true;
3287 
3288   if (Cond.size() != 1)
3289     return true;
3290 
3291   assert(MBP.TrueDest && "expected!");
3292 
3293   if (!MBP.FalseDest)
3294     MBP.FalseDest = MBB.getNextNode();
3295 
3296   const TargetRegisterInfo *TRI = &getRegisterInfo();
3297 
3298   MachineInstr *ConditionDef = nullptr;
3299   bool SingleUseCondition = true;
3300 
3301   for (MachineInstr &MI : llvm::drop_begin(llvm::reverse(MBB))) {
3302     if (MI.modifiesRegister(X86::EFLAGS, TRI)) {
3303       ConditionDef = &MI;
3304       break;
3305     }
3306 
3307     if (MI.readsRegister(X86::EFLAGS, TRI))
3308       SingleUseCondition = false;
3309   }
3310 
3311   if (!ConditionDef)
3312     return true;
3313 
3314   if (SingleUseCondition) {
3315     for (auto *Succ : MBB.successors())
3316       if (Succ->isLiveIn(X86::EFLAGS))
3317         SingleUseCondition = false;
3318   }
3319 
3320   MBP.ConditionDef = ConditionDef;
3321   MBP.SingleUseCondition = SingleUseCondition;
3322 
3323   // Currently we only recognize the simple pattern:
3324   //
3325   //   test %reg, %reg
3326   //   je %label
3327   //
3328   const unsigned TestOpcode =
3329       Subtarget.is64Bit() ? X86::TEST64rr : X86::TEST32rr;
3330 
3331   if (ConditionDef->getOpcode() == TestOpcode &&
3332       ConditionDef->getNumOperands() == 3 &&
3333       ConditionDef->getOperand(0).isIdenticalTo(ConditionDef->getOperand(1)) &&
3334       (Cond[0].getImm() == X86::COND_NE || Cond[0].getImm() == X86::COND_E)) {
3335     MBP.LHS = ConditionDef->getOperand(0);
3336     MBP.RHS = MachineOperand::CreateImm(0);
3337     MBP.Predicate = Cond[0].getImm() == X86::COND_NE
3338                         ? MachineBranchPredicate::PRED_NE
3339                         : MachineBranchPredicate::PRED_EQ;
3340     return false;
3341   }
3342 
3343   return true;
3344 }
3345 
3346 unsigned X86InstrInfo::removeBranch(MachineBasicBlock &MBB,
3347                                     int *BytesRemoved) const {
3348   assert(!BytesRemoved && "code size not handled");
3349 
3350   MachineBasicBlock::iterator I = MBB.end();
3351   unsigned Count = 0;
3352 
3353   while (I != MBB.begin()) {
3354     --I;
3355     if (I->isDebugInstr())
3356       continue;
3357     if (I->getOpcode() != X86::JMP_1 &&
3358         X86::getCondFromBranch(*I) == X86::COND_INVALID)
3359       break;
3360     // Remove the branch.
3361     I->eraseFromParent();
3362     I = MBB.end();
3363     ++Count;
3364   }
3365 
3366   return Count;
3367 }
3368 
3369 unsigned X86InstrInfo::insertBranch(MachineBasicBlock &MBB,
3370                                     MachineBasicBlock *TBB,
3371                                     MachineBasicBlock *FBB,
3372                                     ArrayRef<MachineOperand> Cond,
3373                                     const DebugLoc &DL,
3374                                     int *BytesAdded) const {
3375   // Shouldn't be a fall through.
3376   assert(TBB && "insertBranch must not be told to insert a fallthrough");
3377   assert((Cond.size() == 1 || Cond.size() == 0) &&
3378          "X86 branch conditions have one component!");
3379   assert(!BytesAdded && "code size not handled");
3380 
3381   if (Cond.empty()) {
3382     // Unconditional branch?
3383     assert(!FBB && "Unconditional branch with multiple successors!");
3384     BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(TBB);
3385     return 1;
3386   }
3387 
3388   // If FBB is null, it is implied to be a fall-through block.
3389   bool FallThru = FBB == nullptr;
3390 
3391   // Conditional branch.
3392   unsigned Count = 0;
3393   X86::CondCode CC = (X86::CondCode)Cond[0].getImm();
3394   switch (CC) {
3395   case X86::COND_NE_OR_P:
3396     // Synthesize NE_OR_P with two branches.
3397     BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(X86::COND_NE);
3398     ++Count;
3399     BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(X86::COND_P);
3400     ++Count;
3401     break;
3402   case X86::COND_E_AND_NP:
3403     // Use the next block of MBB as FBB if it is null.
3404     if (FBB == nullptr) {
3405       FBB = getFallThroughMBB(&MBB, TBB);
3406       assert(FBB && "MBB cannot be the last block in function when the false "
3407                     "body is a fall-through.");
3408     }
3409     // Synthesize COND_E_AND_NP with two branches.
3410     BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(FBB).addImm(X86::COND_NE);
3411     ++Count;
3412     BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(X86::COND_NP);
3413     ++Count;
3414     break;
3415   default: {
3416     BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(CC);
3417     ++Count;
3418   }
3419   }
3420   if (!FallThru) {
3421     // Two-way Conditional branch. Insert the second branch.
3422     BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(FBB);
3423     ++Count;
3424   }
3425   return Count;
3426 }
3427 
3428 bool X86InstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
3429                                    ArrayRef<MachineOperand> Cond,
3430                                    Register DstReg, Register TrueReg,
3431                                    Register FalseReg, int &CondCycles,
3432                                    int &TrueCycles, int &FalseCycles) const {
3433   // Not all subtargets have cmov instructions.
3434   if (!Subtarget.canUseCMOV())
3435     return false;
3436   if (Cond.size() != 1)
3437     return false;
3438   // We cannot do the composite conditions, at least not in SSA form.
3439   if ((X86::CondCode)Cond[0].getImm() > X86::LAST_VALID_COND)
3440     return false;
3441 
3442   // Check register classes.
3443   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3444   const TargetRegisterClass *RC =
3445     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
3446   if (!RC)
3447     return false;
3448 
3449   // We have cmov instructions for 16, 32, and 64 bit general purpose registers.
3450   if (X86::GR16RegClass.hasSubClassEq(RC) ||
3451       X86::GR32RegClass.hasSubClassEq(RC) ||
3452       X86::GR64RegClass.hasSubClassEq(RC)) {
3453     // This latency applies to Pentium M, Merom, Wolfdale, Nehalem, and Sandy
3454     // Bridge. Probably Ivy Bridge as well.
3455     CondCycles = 2;
3456     TrueCycles = 2;
3457     FalseCycles = 2;
3458     return true;
3459   }
3460 
3461   // Can't do vectors.
3462   return false;
3463 }
3464 
3465 void X86InstrInfo::insertSelect(MachineBasicBlock &MBB,
3466                                 MachineBasicBlock::iterator I,
3467                                 const DebugLoc &DL, Register DstReg,
3468                                 ArrayRef<MachineOperand> Cond, Register TrueReg,
3469                                 Register FalseReg) const {
3470   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3471   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
3472   const TargetRegisterClass &RC = *MRI.getRegClass(DstReg);
3473   assert(Cond.size() == 1 && "Invalid Cond array");
3474   unsigned Opc = X86::getCMovOpcode(TRI.getRegSizeInBits(RC) / 8,
3475                                     false /*HasMemoryOperand*/);
3476   BuildMI(MBB, I, DL, get(Opc), DstReg)
3477       .addReg(FalseReg)
3478       .addReg(TrueReg)
3479       .addImm(Cond[0].getImm());
3480 }
3481 
3482 /// Test if the given register is a physical h register.
3483 static bool isHReg(unsigned Reg) {
3484   return X86::GR8_ABCD_HRegClass.contains(Reg);
3485 }
3486 
3487 // Try and copy between VR128/VR64 and GR64 registers.
3488 static unsigned CopyToFromAsymmetricReg(unsigned DestReg, unsigned SrcReg,
3489                                         const X86Subtarget &Subtarget) {
3490   bool HasAVX = Subtarget.hasAVX();
3491   bool HasAVX512 = Subtarget.hasAVX512();
3492 
3493   // SrcReg(MaskReg) -> DestReg(GR64)
3494   // SrcReg(MaskReg) -> DestReg(GR32)
3495 
3496   // All KMASK RegClasses hold the same k registers, can be tested against anyone.
3497   if (X86::VK16RegClass.contains(SrcReg)) {
3498     if (X86::GR64RegClass.contains(DestReg)) {
3499       assert(Subtarget.hasBWI());
3500       return X86::KMOVQrk;
3501     }
3502     if (X86::GR32RegClass.contains(DestReg))
3503       return Subtarget.hasBWI() ? X86::KMOVDrk : X86::KMOVWrk;
3504   }
3505 
3506   // SrcReg(GR64) -> DestReg(MaskReg)
3507   // SrcReg(GR32) -> DestReg(MaskReg)
3508 
3509   // All KMASK RegClasses hold the same k registers, can be tested against anyone.
3510   if (X86::VK16RegClass.contains(DestReg)) {
3511     if (X86::GR64RegClass.contains(SrcReg)) {
3512       assert(Subtarget.hasBWI());
3513       return X86::KMOVQkr;
3514     }
3515     if (X86::GR32RegClass.contains(SrcReg))
3516       return Subtarget.hasBWI() ? X86::KMOVDkr : X86::KMOVWkr;
3517   }
3518 
3519 
3520   // SrcReg(VR128) -> DestReg(GR64)
3521   // SrcReg(VR64)  -> DestReg(GR64)
3522   // SrcReg(GR64)  -> DestReg(VR128)
3523   // SrcReg(GR64)  -> DestReg(VR64)
3524 
3525   if (X86::GR64RegClass.contains(DestReg)) {
3526     if (X86::VR128XRegClass.contains(SrcReg))
3527       // Copy from a VR128 register to a GR64 register.
3528       return HasAVX512 ? X86::VMOVPQIto64Zrr :
3529              HasAVX    ? X86::VMOVPQIto64rr  :
3530                          X86::MOVPQIto64rr;
3531     if (X86::VR64RegClass.contains(SrcReg))
3532       // Copy from a VR64 register to a GR64 register.
3533       return X86::MMX_MOVD64from64rr;
3534   } else if (X86::GR64RegClass.contains(SrcReg)) {
3535     // Copy from a GR64 register to a VR128 register.
3536     if (X86::VR128XRegClass.contains(DestReg))
3537       return HasAVX512 ? X86::VMOV64toPQIZrr :
3538              HasAVX    ? X86::VMOV64toPQIrr  :
3539                          X86::MOV64toPQIrr;
3540     // Copy from a GR64 register to a VR64 register.
3541     if (X86::VR64RegClass.contains(DestReg))
3542       return X86::MMX_MOVD64to64rr;
3543   }
3544 
3545   // SrcReg(VR128) -> DestReg(GR32)
3546   // SrcReg(GR32)  -> DestReg(VR128)
3547 
3548   if (X86::GR32RegClass.contains(DestReg) &&
3549       X86::VR128XRegClass.contains(SrcReg))
3550     // Copy from a VR128 register to a GR32 register.
3551     return HasAVX512 ? X86::VMOVPDI2DIZrr :
3552            HasAVX    ? X86::VMOVPDI2DIrr  :
3553                        X86::MOVPDI2DIrr;
3554 
3555   if (X86::VR128XRegClass.contains(DestReg) &&
3556       X86::GR32RegClass.contains(SrcReg))
3557     // Copy from a VR128 register to a VR128 register.
3558     return HasAVX512 ? X86::VMOVDI2PDIZrr :
3559            HasAVX    ? X86::VMOVDI2PDIrr  :
3560                        X86::MOVDI2PDIrr;
3561   return 0;
3562 }
3563 
3564 void X86InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
3565                                MachineBasicBlock::iterator MI,
3566                                const DebugLoc &DL, MCRegister DestReg,
3567                                MCRegister SrcReg, bool KillSrc) const {
3568   // First deal with the normal symmetric copies.
3569   bool HasAVX = Subtarget.hasAVX();
3570   bool HasVLX = Subtarget.hasVLX();
3571   unsigned Opc = 0;
3572   if (X86::GR64RegClass.contains(DestReg, SrcReg))
3573     Opc = X86::MOV64rr;
3574   else if (X86::GR32RegClass.contains(DestReg, SrcReg))
3575     Opc = X86::MOV32rr;
3576   else if (X86::GR16RegClass.contains(DestReg, SrcReg))
3577     Opc = X86::MOV16rr;
3578   else if (X86::GR8RegClass.contains(DestReg, SrcReg)) {
3579     // Copying to or from a physical H register on x86-64 requires a NOREX
3580     // move.  Otherwise use a normal move.
3581     if ((isHReg(DestReg) || isHReg(SrcReg)) &&
3582         Subtarget.is64Bit()) {
3583       Opc = X86::MOV8rr_NOREX;
3584       // Both operands must be encodable without an REX prefix.
3585       assert(X86::GR8_NOREXRegClass.contains(SrcReg, DestReg) &&
3586              "8-bit H register can not be copied outside GR8_NOREX");
3587     } else
3588       Opc = X86::MOV8rr;
3589   }
3590   else if (X86::VR64RegClass.contains(DestReg, SrcReg))
3591     Opc = X86::MMX_MOVQ64rr;
3592   else if (X86::VR128XRegClass.contains(DestReg, SrcReg)) {
3593     if (HasVLX)
3594       Opc = X86::VMOVAPSZ128rr;
3595     else if (X86::VR128RegClass.contains(DestReg, SrcReg))
3596       Opc = HasAVX ? X86::VMOVAPSrr : X86::MOVAPSrr;
3597     else {
3598       // If this an extended register and we don't have VLX we need to use a
3599       // 512-bit move.
3600       Opc = X86::VMOVAPSZrr;
3601       const TargetRegisterInfo *TRI = &getRegisterInfo();
3602       DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_xmm,
3603                                          &X86::VR512RegClass);
3604       SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm,
3605                                         &X86::VR512RegClass);
3606     }
3607   } else if (X86::VR256XRegClass.contains(DestReg, SrcReg)) {
3608     if (HasVLX)
3609       Opc = X86::VMOVAPSZ256rr;
3610     else if (X86::VR256RegClass.contains(DestReg, SrcReg))
3611       Opc = X86::VMOVAPSYrr;
3612     else {
3613       // If this an extended register and we don't have VLX we need to use a
3614       // 512-bit move.
3615       Opc = X86::VMOVAPSZrr;
3616       const TargetRegisterInfo *TRI = &getRegisterInfo();
3617       DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_ymm,
3618                                          &X86::VR512RegClass);
3619       SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_ymm,
3620                                         &X86::VR512RegClass);
3621     }
3622   } else if (X86::VR512RegClass.contains(DestReg, SrcReg))
3623     Opc = X86::VMOVAPSZrr;
3624   // All KMASK RegClasses hold the same k registers, can be tested against anyone.
3625   else if (X86::VK16RegClass.contains(DestReg, SrcReg))
3626     Opc = Subtarget.hasBWI() ? X86::KMOVQkk : X86::KMOVWkk;
3627   if (!Opc)
3628     Opc = CopyToFromAsymmetricReg(DestReg, SrcReg, Subtarget);
3629 
3630   if (Opc) {
3631     BuildMI(MBB, MI, DL, get(Opc), DestReg)
3632       .addReg(SrcReg, getKillRegState(KillSrc));
3633     return;
3634   }
3635 
3636   if (SrcReg == X86::EFLAGS || DestReg == X86::EFLAGS) {
3637     // FIXME: We use a fatal error here because historically LLVM has tried
3638     // lower some of these physreg copies and we want to ensure we get
3639     // reasonable bug reports if someone encounters a case no other testing
3640     // found. This path should be removed after the LLVM 7 release.
3641     report_fatal_error("Unable to copy EFLAGS physical register!");
3642   }
3643 
3644   LLVM_DEBUG(dbgs() << "Cannot copy " << RI.getName(SrcReg) << " to "
3645                     << RI.getName(DestReg) << '\n');
3646   report_fatal_error("Cannot emit physreg copy instruction");
3647 }
3648 
3649 std::optional<DestSourcePair>
3650 X86InstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
3651   if (MI.isMoveReg())
3652     return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
3653   return std::nullopt;
3654 }
3655 
3656 static unsigned getLoadStoreOpcodeForFP16(bool Load, const X86Subtarget &STI) {
3657   if (STI.hasFP16())
3658     return Load ? X86::VMOVSHZrm_alt : X86::VMOVSHZmr;
3659   if (Load)
3660     return STI.hasAVX512() ? X86::VMOVSSZrm
3661            : STI.hasAVX()  ? X86::VMOVSSrm
3662                            : X86::MOVSSrm;
3663   else
3664     return STI.hasAVX512() ? X86::VMOVSSZmr
3665            : STI.hasAVX()  ? X86::VMOVSSmr
3666                            : X86::MOVSSmr;
3667 }
3668 
3669 static unsigned getLoadStoreRegOpcode(Register Reg,
3670                                       const TargetRegisterClass *RC,
3671                                       bool IsStackAligned,
3672                                       const X86Subtarget &STI, bool Load) {
3673   bool HasAVX = STI.hasAVX();
3674   bool HasAVX512 = STI.hasAVX512();
3675   bool HasVLX = STI.hasVLX();
3676 
3677   assert(RC != nullptr && "Invalid target register class");
3678   switch (STI.getRegisterInfo()->getSpillSize(*RC)) {
3679   default:
3680     llvm_unreachable("Unknown spill size");
3681   case 1:
3682     assert(X86::GR8RegClass.hasSubClassEq(RC) && "Unknown 1-byte regclass");
3683     if (STI.is64Bit())
3684       // Copying to or from a physical H register on x86-64 requires a NOREX
3685       // move.  Otherwise use a normal move.
3686       if (isHReg(Reg) || X86::GR8_ABCD_HRegClass.hasSubClassEq(RC))
3687         return Load ? X86::MOV8rm_NOREX : X86::MOV8mr_NOREX;
3688     return Load ? X86::MOV8rm : X86::MOV8mr;
3689   case 2:
3690     if (X86::VK16RegClass.hasSubClassEq(RC))
3691       return Load ? X86::KMOVWkm : X86::KMOVWmk;
3692     assert(X86::GR16RegClass.hasSubClassEq(RC) && "Unknown 2-byte regclass");
3693     return Load ? X86::MOV16rm : X86::MOV16mr;
3694   case 4:
3695     if (X86::GR32RegClass.hasSubClassEq(RC))
3696       return Load ? X86::MOV32rm : X86::MOV32mr;
3697     if (X86::FR32XRegClass.hasSubClassEq(RC))
3698       return Load ?
3699         (HasAVX512 ? X86::VMOVSSZrm_alt :
3700          HasAVX    ? X86::VMOVSSrm_alt :
3701                      X86::MOVSSrm_alt) :
3702         (HasAVX512 ? X86::VMOVSSZmr :
3703          HasAVX    ? X86::VMOVSSmr :
3704                      X86::MOVSSmr);
3705     if (X86::RFP32RegClass.hasSubClassEq(RC))
3706       return Load ? X86::LD_Fp32m : X86::ST_Fp32m;
3707     if (X86::VK32RegClass.hasSubClassEq(RC)) {
3708       assert(STI.hasBWI() && "KMOVD requires BWI");
3709       return Load ? X86::KMOVDkm : X86::KMOVDmk;
3710     }
3711     // All of these mask pair classes have the same spill size, the same kind
3712     // of kmov instructions can be used with all of them.
3713     if (X86::VK1PAIRRegClass.hasSubClassEq(RC) ||
3714         X86::VK2PAIRRegClass.hasSubClassEq(RC) ||
3715         X86::VK4PAIRRegClass.hasSubClassEq(RC) ||
3716         X86::VK8PAIRRegClass.hasSubClassEq(RC) ||
3717         X86::VK16PAIRRegClass.hasSubClassEq(RC))
3718       return Load ? X86::MASKPAIR16LOAD : X86::MASKPAIR16STORE;
3719     if (X86::FR16RegClass.hasSubClassEq(RC) ||
3720         X86::FR16XRegClass.hasSubClassEq(RC))
3721       return getLoadStoreOpcodeForFP16(Load, STI);
3722     llvm_unreachable("Unknown 4-byte regclass");
3723   case 8:
3724     if (X86::GR64RegClass.hasSubClassEq(RC))
3725       return Load ? X86::MOV64rm : X86::MOV64mr;
3726     if (X86::FR64XRegClass.hasSubClassEq(RC))
3727       return Load ?
3728         (HasAVX512 ? X86::VMOVSDZrm_alt :
3729          HasAVX    ? X86::VMOVSDrm_alt :
3730                      X86::MOVSDrm_alt) :
3731         (HasAVX512 ? X86::VMOVSDZmr :
3732          HasAVX    ? X86::VMOVSDmr :
3733                      X86::MOVSDmr);
3734     if (X86::VR64RegClass.hasSubClassEq(RC))
3735       return Load ? X86::MMX_MOVQ64rm : X86::MMX_MOVQ64mr;
3736     if (X86::RFP64RegClass.hasSubClassEq(RC))
3737       return Load ? X86::LD_Fp64m : X86::ST_Fp64m;
3738     if (X86::VK64RegClass.hasSubClassEq(RC)) {
3739       assert(STI.hasBWI() && "KMOVQ requires BWI");
3740       return Load ? X86::KMOVQkm : X86::KMOVQmk;
3741     }
3742     llvm_unreachable("Unknown 8-byte regclass");
3743   case 10:
3744     assert(X86::RFP80RegClass.hasSubClassEq(RC) && "Unknown 10-byte regclass");
3745     return Load ? X86::LD_Fp80m : X86::ST_FpP80m;
3746   case 16: {
3747     if (X86::VR128XRegClass.hasSubClassEq(RC)) {
3748       // If stack is realigned we can use aligned stores.
3749       if (IsStackAligned)
3750         return Load ?
3751           (HasVLX    ? X86::VMOVAPSZ128rm :
3752            HasAVX512 ? X86::VMOVAPSZ128rm_NOVLX :
3753            HasAVX    ? X86::VMOVAPSrm :
3754                        X86::MOVAPSrm):
3755           (HasVLX    ? X86::VMOVAPSZ128mr :
3756            HasAVX512 ? X86::VMOVAPSZ128mr_NOVLX :
3757            HasAVX    ? X86::VMOVAPSmr :
3758                        X86::MOVAPSmr);
3759       else
3760         return Load ?
3761           (HasVLX    ? X86::VMOVUPSZ128rm :
3762            HasAVX512 ? X86::VMOVUPSZ128rm_NOVLX :
3763            HasAVX    ? X86::VMOVUPSrm :
3764                        X86::MOVUPSrm):
3765           (HasVLX    ? X86::VMOVUPSZ128mr :
3766            HasAVX512 ? X86::VMOVUPSZ128mr_NOVLX :
3767            HasAVX    ? X86::VMOVUPSmr :
3768                        X86::MOVUPSmr);
3769     }
3770     llvm_unreachable("Unknown 16-byte regclass");
3771   }
3772   case 32:
3773     assert(X86::VR256XRegClass.hasSubClassEq(RC) && "Unknown 32-byte regclass");
3774     // If stack is realigned we can use aligned stores.
3775     if (IsStackAligned)
3776       return Load ?
3777         (HasVLX    ? X86::VMOVAPSZ256rm :
3778          HasAVX512 ? X86::VMOVAPSZ256rm_NOVLX :
3779                      X86::VMOVAPSYrm) :
3780         (HasVLX    ? X86::VMOVAPSZ256mr :
3781          HasAVX512 ? X86::VMOVAPSZ256mr_NOVLX :
3782                      X86::VMOVAPSYmr);
3783     else
3784       return Load ?
3785         (HasVLX    ? X86::VMOVUPSZ256rm :
3786          HasAVX512 ? X86::VMOVUPSZ256rm_NOVLX :
3787                      X86::VMOVUPSYrm) :
3788         (HasVLX    ? X86::VMOVUPSZ256mr :
3789          HasAVX512 ? X86::VMOVUPSZ256mr_NOVLX :
3790                      X86::VMOVUPSYmr);
3791   case 64:
3792     assert(X86::VR512RegClass.hasSubClassEq(RC) && "Unknown 64-byte regclass");
3793     assert(STI.hasAVX512() && "Using 512-bit register requires AVX512");
3794     if (IsStackAligned)
3795       return Load ? X86::VMOVAPSZrm : X86::VMOVAPSZmr;
3796     else
3797       return Load ? X86::VMOVUPSZrm : X86::VMOVUPSZmr;
3798   case 1024:
3799     assert(X86::TILERegClass.hasSubClassEq(RC) && "Unknown 1024-byte regclass");
3800     assert(STI.hasAMXTILE() && "Using 8*1024-bit register requires AMX-TILE");
3801     return Load ? X86::TILELOADD : X86::TILESTORED;
3802   }
3803 }
3804 
3805 std::optional<ExtAddrMode>
3806 X86InstrInfo::getAddrModeFromMemoryOp(const MachineInstr &MemI,
3807                                       const TargetRegisterInfo *TRI) const {
3808   const MCInstrDesc &Desc = MemI.getDesc();
3809   int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
3810   if (MemRefBegin < 0)
3811     return std::nullopt;
3812 
3813   MemRefBegin += X86II::getOperandBias(Desc);
3814 
3815   auto &BaseOp = MemI.getOperand(MemRefBegin + X86::AddrBaseReg);
3816   if (!BaseOp.isReg()) // Can be an MO_FrameIndex
3817     return std::nullopt;
3818 
3819   const MachineOperand &DispMO = MemI.getOperand(MemRefBegin + X86::AddrDisp);
3820   // Displacement can be symbolic
3821   if (!DispMO.isImm())
3822     return std::nullopt;
3823 
3824   ExtAddrMode AM;
3825   AM.BaseReg = BaseOp.getReg();
3826   AM.ScaledReg = MemI.getOperand(MemRefBegin + X86::AddrIndexReg).getReg();
3827   AM.Scale = MemI.getOperand(MemRefBegin + X86::AddrScaleAmt).getImm();
3828   AM.Displacement = DispMO.getImm();
3829   return AM;
3830 }
3831 
3832 bool X86InstrInfo::verifyInstruction(const MachineInstr &MI,
3833                                      StringRef &ErrInfo) const {
3834   std::optional<ExtAddrMode> AMOrNone = getAddrModeFromMemoryOp(MI, nullptr);
3835   if (!AMOrNone)
3836     return true;
3837 
3838   ExtAddrMode AM = *AMOrNone;
3839 
3840   if (AM.ScaledReg != X86::NoRegister) {
3841     switch (AM.Scale) {
3842     case 1:
3843     case 2:
3844     case 4:
3845     case 8:
3846       break;
3847     default:
3848       ErrInfo = "Scale factor in address must be 1, 2, 4 or 8";
3849       return false;
3850     }
3851   }
3852   if (!isInt<32>(AM.Displacement)) {
3853     ErrInfo = "Displacement in address must fit into 32-bit signed "
3854               "integer";
3855     return false;
3856   }
3857 
3858   return true;
3859 }
3860 
3861 bool X86InstrInfo::getConstValDefinedInReg(const MachineInstr &MI,
3862                                            const Register Reg,
3863                                            int64_t &ImmVal) const {
3864   if (MI.getOpcode() != X86::MOV32ri && MI.getOpcode() != X86::MOV64ri)
3865     return false;
3866   // Mov Src can be a global address.
3867   if (!MI.getOperand(1).isImm() || MI.getOperand(0).getReg() != Reg)
3868     return false;
3869   ImmVal = MI.getOperand(1).getImm();
3870   return true;
3871 }
3872 
3873 bool X86InstrInfo::preservesZeroValueInReg(
3874     const MachineInstr *MI, const Register NullValueReg,
3875     const TargetRegisterInfo *TRI) const {
3876   if (!MI->modifiesRegister(NullValueReg, TRI))
3877     return true;
3878   switch (MI->getOpcode()) {
3879   // Shift right/left of a null unto itself is still a null, i.e. rax = shl rax
3880   // X.
3881   case X86::SHR64ri:
3882   case X86::SHR32ri:
3883   case X86::SHL64ri:
3884   case X86::SHL32ri:
3885     assert(MI->getOperand(0).isDef() && MI->getOperand(1).isUse() &&
3886            "expected for shift opcode!");
3887     return MI->getOperand(0).getReg() == NullValueReg &&
3888            MI->getOperand(1).getReg() == NullValueReg;
3889   // Zero extend of a sub-reg of NullValueReg into itself does not change the
3890   // null value.
3891   case X86::MOV32rr:
3892     return llvm::all_of(MI->operands(), [&](const MachineOperand &MO) {
3893       return TRI->isSubRegisterEq(NullValueReg, MO.getReg());
3894     });
3895   default:
3896     return false;
3897   }
3898   llvm_unreachable("Should be handled above!");
3899 }
3900 
3901 bool X86InstrInfo::getMemOperandsWithOffsetWidth(
3902     const MachineInstr &MemOp, SmallVectorImpl<const MachineOperand *> &BaseOps,
3903     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
3904     const TargetRegisterInfo *TRI) const {
3905   const MCInstrDesc &Desc = MemOp.getDesc();
3906   int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
3907   if (MemRefBegin < 0)
3908     return false;
3909 
3910   MemRefBegin += X86II::getOperandBias(Desc);
3911 
3912   const MachineOperand *BaseOp =
3913       &MemOp.getOperand(MemRefBegin + X86::AddrBaseReg);
3914   if (!BaseOp->isReg()) // Can be an MO_FrameIndex
3915     return false;
3916 
3917   if (MemOp.getOperand(MemRefBegin + X86::AddrScaleAmt).getImm() != 1)
3918     return false;
3919 
3920   if (MemOp.getOperand(MemRefBegin + X86::AddrIndexReg).getReg() !=
3921       X86::NoRegister)
3922     return false;
3923 
3924   const MachineOperand &DispMO = MemOp.getOperand(MemRefBegin + X86::AddrDisp);
3925 
3926   // Displacement can be symbolic
3927   if (!DispMO.isImm())
3928     return false;
3929 
3930   Offset = DispMO.getImm();
3931 
3932   if (!BaseOp->isReg())
3933     return false;
3934 
3935   OffsetIsScalable = false;
3936   // FIXME: Relying on memoperands() may not be right thing to do here. Check
3937   // with X86 maintainers, and fix it accordingly. For now, it is ok, since
3938   // there is no use of `Width` for X86 back-end at the moment.
3939   Width =
3940       !MemOp.memoperands_empty() ? MemOp.memoperands().front()->getSize() : 0;
3941   BaseOps.push_back(BaseOp);
3942   return true;
3943 }
3944 
3945 static unsigned getStoreRegOpcode(Register SrcReg,
3946                                   const TargetRegisterClass *RC,
3947                                   bool IsStackAligned,
3948                                   const X86Subtarget &STI) {
3949   return getLoadStoreRegOpcode(SrcReg, RC, IsStackAligned, STI, false);
3950 }
3951 
3952 static unsigned getLoadRegOpcode(Register DestReg,
3953                                  const TargetRegisterClass *RC,
3954                                  bool IsStackAligned, const X86Subtarget &STI) {
3955   return getLoadStoreRegOpcode(DestReg, RC, IsStackAligned, STI, true);
3956 }
3957 
3958 static bool isAMXOpcode(unsigned Opc) {
3959   switch (Opc) {
3960   default:
3961     return false;
3962   case X86::TILELOADD:
3963   case X86::TILESTORED:
3964     return true;
3965   }
3966 }
3967 
3968 void X86InstrInfo::loadStoreTileReg(MachineBasicBlock &MBB,
3969                                     MachineBasicBlock::iterator MI,
3970                                     unsigned Opc, Register Reg, int FrameIdx,
3971                                     bool isKill) const {
3972   switch (Opc) {
3973   default:
3974     llvm_unreachable("Unexpected special opcode!");
3975   case X86::TILESTORED: {
3976     // tilestored %tmm, (%sp, %idx)
3977     MachineRegisterInfo &RegInfo = MBB.getParent()->getRegInfo();
3978     Register VirtReg = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
3979     BuildMI(MBB, MI, DebugLoc(), get(X86::MOV64ri), VirtReg).addImm(64);
3980     MachineInstr *NewMI =
3981         addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc)), FrameIdx)
3982             .addReg(Reg, getKillRegState(isKill));
3983     MachineOperand &MO = NewMI->getOperand(X86::AddrIndexReg);
3984     MO.setReg(VirtReg);
3985     MO.setIsKill(true);
3986     break;
3987   }
3988   case X86::TILELOADD: {
3989     // tileloadd (%sp, %idx), %tmm
3990     MachineRegisterInfo &RegInfo = MBB.getParent()->getRegInfo();
3991     Register VirtReg = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
3992     BuildMI(MBB, MI, DebugLoc(), get(X86::MOV64ri), VirtReg).addImm(64);
3993     MachineInstr *NewMI = addFrameReference(
3994         BuildMI(MBB, MI, DebugLoc(), get(Opc), Reg), FrameIdx);
3995     MachineOperand &MO = NewMI->getOperand(1 + X86::AddrIndexReg);
3996     MO.setReg(VirtReg);
3997     MO.setIsKill(true);
3998     break;
3999   }
4000   }
4001 }
4002 
4003 void X86InstrInfo::storeRegToStackSlot(
4004     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
4005     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
4006     const TargetRegisterInfo *TRI, Register VReg) const {
4007   const MachineFunction &MF = *MBB.getParent();
4008   const MachineFrameInfo &MFI = MF.getFrameInfo();
4009   assert(MFI.getObjectSize(FrameIdx) >= TRI->getSpillSize(*RC) &&
4010          "Stack slot too small for store");
4011 
4012   unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
4013   bool isAligned =
4014       (Subtarget.getFrameLowering()->getStackAlign() >= Alignment) ||
4015       (RI.canRealignStack(MF) && !MFI.isFixedObjectIndex(FrameIdx));
4016 
4017   unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
4018   if (isAMXOpcode(Opc))
4019     loadStoreTileReg(MBB, MI, Opc, SrcReg, FrameIdx, isKill);
4020   else
4021     addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc)), FrameIdx)
4022         .addReg(SrcReg, getKillRegState(isKill));
4023 }
4024 
4025 void X86InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
4026                                         MachineBasicBlock::iterator MI,
4027                                         Register DestReg, int FrameIdx,
4028                                         const TargetRegisterClass *RC,
4029                                         const TargetRegisterInfo *TRI,
4030                                         Register VReg) const {
4031   const MachineFunction &MF = *MBB.getParent();
4032   const MachineFrameInfo &MFI = MF.getFrameInfo();
4033   assert(MFI.getObjectSize(FrameIdx) >= TRI->getSpillSize(*RC) &&
4034          "Load size exceeds stack slot");
4035   unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
4036   bool isAligned =
4037       (Subtarget.getFrameLowering()->getStackAlign() >= Alignment) ||
4038       (RI.canRealignStack(MF) && !MFI.isFixedObjectIndex(FrameIdx));
4039 
4040   unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
4041   if (isAMXOpcode(Opc))
4042     loadStoreTileReg(MBB, MI, Opc, DestReg, FrameIdx);
4043   else
4044     addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc), DestReg),
4045                       FrameIdx);
4046 }
4047 
4048 bool X86InstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
4049                                   Register &SrcReg2, int64_t &CmpMask,
4050                                   int64_t &CmpValue) const {
4051   switch (MI.getOpcode()) {
4052   default: break;
4053   case X86::CMP64ri32:
4054   case X86::CMP32ri:
4055   case X86::CMP16ri:
4056   case X86::CMP8ri:
4057     SrcReg = MI.getOperand(0).getReg();
4058     SrcReg2 = 0;
4059     if (MI.getOperand(1).isImm()) {
4060       CmpMask = ~0;
4061       CmpValue = MI.getOperand(1).getImm();
4062     } else {
4063       CmpMask = CmpValue = 0;
4064     }
4065     return true;
4066   // A SUB can be used to perform comparison.
4067   case X86::SUB64rm:
4068   case X86::SUB32rm:
4069   case X86::SUB16rm:
4070   case X86::SUB8rm:
4071     SrcReg = MI.getOperand(1).getReg();
4072     SrcReg2 = 0;
4073     CmpMask = 0;
4074     CmpValue = 0;
4075     return true;
4076   case X86::SUB64rr:
4077   case X86::SUB32rr:
4078   case X86::SUB16rr:
4079   case X86::SUB8rr:
4080     SrcReg = MI.getOperand(1).getReg();
4081     SrcReg2 = MI.getOperand(2).getReg();
4082     CmpMask = 0;
4083     CmpValue = 0;
4084     return true;
4085   case X86::SUB64ri32:
4086   case X86::SUB32ri:
4087   case X86::SUB16ri:
4088   case X86::SUB8ri:
4089     SrcReg = MI.getOperand(1).getReg();
4090     SrcReg2 = 0;
4091     if (MI.getOperand(2).isImm()) {
4092       CmpMask = ~0;
4093       CmpValue = MI.getOperand(2).getImm();
4094     } else {
4095       CmpMask = CmpValue = 0;
4096     }
4097     return true;
4098   case X86::CMP64rr:
4099   case X86::CMP32rr:
4100   case X86::CMP16rr:
4101   case X86::CMP8rr:
4102     SrcReg = MI.getOperand(0).getReg();
4103     SrcReg2 = MI.getOperand(1).getReg();
4104     CmpMask = 0;
4105     CmpValue = 0;
4106     return true;
4107   case X86::TEST8rr:
4108   case X86::TEST16rr:
4109   case X86::TEST32rr:
4110   case X86::TEST64rr:
4111     SrcReg = MI.getOperand(0).getReg();
4112     if (MI.getOperand(1).getReg() != SrcReg)
4113       return false;
4114     // Compare against zero.
4115     SrcReg2 = 0;
4116     CmpMask = ~0;
4117     CmpValue = 0;
4118     return true;
4119   }
4120   return false;
4121 }
4122 
4123 bool X86InstrInfo::isRedundantFlagInstr(const MachineInstr &FlagI,
4124                                         Register SrcReg, Register SrcReg2,
4125                                         int64_t ImmMask, int64_t ImmValue,
4126                                         const MachineInstr &OI, bool *IsSwapped,
4127                                         int64_t *ImmDelta) const {
4128   switch (OI.getOpcode()) {
4129   case X86::CMP64rr:
4130   case X86::CMP32rr:
4131   case X86::CMP16rr:
4132   case X86::CMP8rr:
4133   case X86::SUB64rr:
4134   case X86::SUB32rr:
4135   case X86::SUB16rr:
4136   case X86::SUB8rr: {
4137     Register OISrcReg;
4138     Register OISrcReg2;
4139     int64_t OIMask;
4140     int64_t OIValue;
4141     if (!analyzeCompare(OI, OISrcReg, OISrcReg2, OIMask, OIValue) ||
4142         OIMask != ImmMask || OIValue != ImmValue)
4143       return false;
4144     if (SrcReg == OISrcReg && SrcReg2 == OISrcReg2) {
4145       *IsSwapped = false;
4146       return true;
4147     }
4148     if (SrcReg == OISrcReg2 && SrcReg2 == OISrcReg) {
4149       *IsSwapped = true;
4150       return true;
4151     }
4152     return false;
4153   }
4154   case X86::CMP64ri32:
4155   case X86::CMP32ri:
4156   case X86::CMP16ri:
4157   case X86::CMP8ri:
4158   case X86::SUB64ri32:
4159   case X86::SUB32ri:
4160   case X86::SUB16ri:
4161   case X86::SUB8ri:
4162   case X86::TEST64rr:
4163   case X86::TEST32rr:
4164   case X86::TEST16rr:
4165   case X86::TEST8rr: {
4166     if (ImmMask != 0) {
4167       Register OISrcReg;
4168       Register OISrcReg2;
4169       int64_t OIMask;
4170       int64_t OIValue;
4171       if (analyzeCompare(OI, OISrcReg, OISrcReg2, OIMask, OIValue) &&
4172           SrcReg == OISrcReg && ImmMask == OIMask) {
4173         if (OIValue == ImmValue) {
4174           *ImmDelta = 0;
4175           return true;
4176         } else if (static_cast<uint64_t>(ImmValue) ==
4177                    static_cast<uint64_t>(OIValue) - 1) {
4178           *ImmDelta = -1;
4179           return true;
4180         } else if (static_cast<uint64_t>(ImmValue) ==
4181                    static_cast<uint64_t>(OIValue) + 1) {
4182           *ImmDelta = 1;
4183           return true;
4184         } else {
4185           return false;
4186         }
4187       }
4188     }
4189     return FlagI.isIdenticalTo(OI);
4190   }
4191   default:
4192     return false;
4193   }
4194 }
4195 
4196 /// Check whether the definition can be converted
4197 /// to remove a comparison against zero.
4198 inline static bool isDefConvertible(const MachineInstr &MI, bool &NoSignFlag,
4199                                     bool &ClearsOverflowFlag) {
4200   NoSignFlag = false;
4201   ClearsOverflowFlag = false;
4202 
4203   // "ELF Handling for Thread-Local Storage" specifies that x86-64 GOTTPOFF, and
4204   // i386 GOTNTPOFF/INDNTPOFF relocations can convert an ADD to a LEA during
4205   // Initial Exec to Local Exec relaxation. In these cases, we must not depend
4206   // on the EFLAGS modification of ADD actually happening in the final binary.
4207   if (MI.getOpcode() == X86::ADD64rm || MI.getOpcode() == X86::ADD32rm) {
4208     unsigned Flags = MI.getOperand(5).getTargetFlags();
4209     if (Flags == X86II::MO_GOTTPOFF || Flags == X86II::MO_INDNTPOFF ||
4210         Flags == X86II::MO_GOTNTPOFF)
4211       return false;
4212   }
4213 
4214   switch (MI.getOpcode()) {
4215   default: return false;
4216 
4217   // The shift instructions only modify ZF if their shift count is non-zero.
4218   // N.B.: The processor truncates the shift count depending on the encoding.
4219   case X86::SAR8ri:    case X86::SAR16ri:  case X86::SAR32ri:case X86::SAR64ri:
4220   case X86::SHR8ri:    case X86::SHR16ri:  case X86::SHR32ri:case X86::SHR64ri:
4221      return getTruncatedShiftCount(MI, 2) != 0;
4222 
4223   // Some left shift instructions can be turned into LEA instructions but only
4224   // if their flags aren't used. Avoid transforming such instructions.
4225   case X86::SHL8ri:    case X86::SHL16ri:  case X86::SHL32ri:case X86::SHL64ri:{
4226     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
4227     if (isTruncatedShiftCountForLEA(ShAmt)) return false;
4228     return ShAmt != 0;
4229   }
4230 
4231   case X86::SHRD16rri8:case X86::SHRD32rri8:case X86::SHRD64rri8:
4232   case X86::SHLD16rri8:case X86::SHLD32rri8:case X86::SHLD64rri8:
4233      return getTruncatedShiftCount(MI, 3) != 0;
4234 
4235   case X86::SUB64ri32: case X86::SUB32ri:  case X86::SUB16ri:
4236   case X86::SUB8ri:    case X86::SUB64rr:  case X86::SUB32rr:
4237   case X86::SUB16rr:   case X86::SUB8rr:   case X86::SUB64rm:
4238   case X86::SUB32rm:   case X86::SUB16rm:  case X86::SUB8rm:
4239   case X86::DEC64r:    case X86::DEC32r:   case X86::DEC16r: case X86::DEC8r:
4240   case X86::ADD64ri32: case X86::ADD32ri:  case X86::ADD16ri:
4241   case X86::ADD8ri:    case X86::ADD64rr:  case X86::ADD32rr:
4242   case X86::ADD16rr:   case X86::ADD8rr:   case X86::ADD64rm:
4243   case X86::ADD32rm:   case X86::ADD16rm:  case X86::ADD8rm:
4244   case X86::INC64r:    case X86::INC32r:   case X86::INC16r: case X86::INC8r:
4245   case X86::ADC64ri32: case X86::ADC32ri:  case X86::ADC16ri:
4246   case X86::ADC8ri:    case X86::ADC64rr:  case X86::ADC32rr:
4247   case X86::ADC16rr:   case X86::ADC8rr:   case X86::ADC64rm:
4248   case X86::ADC32rm:   case X86::ADC16rm:  case X86::ADC8rm:
4249   case X86::SBB64ri32: case X86::SBB32ri:  case X86::SBB16ri:
4250   case X86::SBB8ri:    case X86::SBB64rr:  case X86::SBB32rr:
4251   case X86::SBB16rr:   case X86::SBB8rr:   case X86::SBB64rm:
4252   case X86::SBB32rm:   case X86::SBB16rm:  case X86::SBB8rm:
4253   case X86::NEG8r:     case X86::NEG16r:   case X86::NEG32r: case X86::NEG64r:
4254   case X86::LZCNT16rr: case X86::LZCNT16rm:
4255   case X86::LZCNT32rr: case X86::LZCNT32rm:
4256   case X86::LZCNT64rr: case X86::LZCNT64rm:
4257   case X86::POPCNT16rr:case X86::POPCNT16rm:
4258   case X86::POPCNT32rr:case X86::POPCNT32rm:
4259   case X86::POPCNT64rr:case X86::POPCNT64rm:
4260   case X86::TZCNT16rr: case X86::TZCNT16rm:
4261   case X86::TZCNT32rr: case X86::TZCNT32rm:
4262   case X86::TZCNT64rr: case X86::TZCNT64rm:
4263     return true;
4264   case X86::AND64ri32:   case X86::AND32ri:   case X86::AND16ri:
4265   case X86::AND8ri:      case X86::AND64rr:   case X86::AND32rr:
4266   case X86::AND16rr:     case X86::AND8rr:    case X86::AND64rm:
4267   case X86::AND32rm:     case X86::AND16rm:   case X86::AND8rm:
4268   case X86::XOR64ri32:   case X86::XOR32ri:   case X86::XOR16ri:
4269   case X86::XOR8ri:      case X86::XOR64rr:   case X86::XOR32rr:
4270   case X86::XOR16rr:     case X86::XOR8rr:    case X86::XOR64rm:
4271   case X86::XOR32rm:     case X86::XOR16rm:   case X86::XOR8rm:
4272   case X86::OR64ri32:    case X86::OR32ri:    case X86::OR16ri:
4273   case X86::OR8ri:       case X86::OR64rr:    case X86::OR32rr:
4274   case X86::OR16rr:      case X86::OR8rr:     case X86::OR64rm:
4275   case X86::OR32rm:      case X86::OR16rm:    case X86::OR8rm:
4276   case X86::ANDN32rr:    case X86::ANDN32rm:
4277   case X86::ANDN64rr:    case X86::ANDN64rm:
4278   case X86::BLSI32rr:    case X86::BLSI32rm:
4279   case X86::BLSI64rr:    case X86::BLSI64rm:
4280   case X86::BLSMSK32rr:  case X86::BLSMSK32rm:
4281   case X86::BLSMSK64rr:  case X86::BLSMSK64rm:
4282   case X86::BLSR32rr:    case X86::BLSR32rm:
4283   case X86::BLSR64rr:    case X86::BLSR64rm:
4284   case X86::BLCFILL32rr: case X86::BLCFILL32rm:
4285   case X86::BLCFILL64rr: case X86::BLCFILL64rm:
4286   case X86::BLCI32rr:    case X86::BLCI32rm:
4287   case X86::BLCI64rr:    case X86::BLCI64rm:
4288   case X86::BLCIC32rr:   case X86::BLCIC32rm:
4289   case X86::BLCIC64rr:   case X86::BLCIC64rm:
4290   case X86::BLCMSK32rr:  case X86::BLCMSK32rm:
4291   case X86::BLCMSK64rr:  case X86::BLCMSK64rm:
4292   case X86::BLCS32rr:    case X86::BLCS32rm:
4293   case X86::BLCS64rr:    case X86::BLCS64rm:
4294   case X86::BLSFILL32rr: case X86::BLSFILL32rm:
4295   case X86::BLSFILL64rr: case X86::BLSFILL64rm:
4296   case X86::BLSIC32rr:   case X86::BLSIC32rm:
4297   case X86::BLSIC64rr:   case X86::BLSIC64rm:
4298   case X86::BZHI32rr:    case X86::BZHI32rm:
4299   case X86::BZHI64rr:    case X86::BZHI64rm:
4300   case X86::T1MSKC32rr:  case X86::T1MSKC32rm:
4301   case X86::T1MSKC64rr:  case X86::T1MSKC64rm:
4302   case X86::TZMSK32rr:   case X86::TZMSK32rm:
4303   case X86::TZMSK64rr:   case X86::TZMSK64rm:
4304     // These instructions clear the overflow flag just like TEST.
4305     // FIXME: These are not the only instructions in this switch that clear the
4306     // overflow flag.
4307     ClearsOverflowFlag = true;
4308     return true;
4309   case X86::BEXTR32rr:   case X86::BEXTR64rr:
4310   case X86::BEXTR32rm:   case X86::BEXTR64rm:
4311   case X86::BEXTRI32ri:  case X86::BEXTRI32mi:
4312   case X86::BEXTRI64ri:  case X86::BEXTRI64mi:
4313     // BEXTR doesn't update the sign flag so we can't use it. It does clear
4314     // the overflow flag, but that's not useful without the sign flag.
4315     NoSignFlag = true;
4316     return true;
4317   }
4318 }
4319 
4320 /// Check whether the use can be converted to remove a comparison against zero.
4321 static X86::CondCode isUseDefConvertible(const MachineInstr &MI) {
4322   switch (MI.getOpcode()) {
4323   default: return X86::COND_INVALID;
4324   case X86::NEG8r:
4325   case X86::NEG16r:
4326   case X86::NEG32r:
4327   case X86::NEG64r:
4328     return X86::COND_AE;
4329   case X86::LZCNT16rr:
4330   case X86::LZCNT32rr:
4331   case X86::LZCNT64rr:
4332     return X86::COND_B;
4333   case X86::POPCNT16rr:
4334   case X86::POPCNT32rr:
4335   case X86::POPCNT64rr:
4336     return X86::COND_E;
4337   case X86::TZCNT16rr:
4338   case X86::TZCNT32rr:
4339   case X86::TZCNT64rr:
4340     return X86::COND_B;
4341   case X86::BSF16rr:
4342   case X86::BSF32rr:
4343   case X86::BSF64rr:
4344   case X86::BSR16rr:
4345   case X86::BSR32rr:
4346   case X86::BSR64rr:
4347     return X86::COND_E;
4348   case X86::BLSI32rr:
4349   case X86::BLSI64rr:
4350     return X86::COND_AE;
4351   case X86::BLSR32rr:
4352   case X86::BLSR64rr:
4353   case X86::BLSMSK32rr:
4354   case X86::BLSMSK64rr:
4355     return X86::COND_B;
4356   // TODO: TBM instructions.
4357   }
4358 }
4359 
4360 /// Check if there exists an earlier instruction that
4361 /// operates on the same source operands and sets flags in the same way as
4362 /// Compare; remove Compare if possible.
4363 bool X86InstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
4364                                         Register SrcReg2, int64_t CmpMask,
4365                                         int64_t CmpValue,
4366                                         const MachineRegisterInfo *MRI) const {
4367   // Check whether we can replace SUB with CMP.
4368   switch (CmpInstr.getOpcode()) {
4369   default: break;
4370   case X86::SUB64ri32:
4371   case X86::SUB32ri:
4372   case X86::SUB16ri:
4373   case X86::SUB8ri:
4374   case X86::SUB64rm:
4375   case X86::SUB32rm:
4376   case X86::SUB16rm:
4377   case X86::SUB8rm:
4378   case X86::SUB64rr:
4379   case X86::SUB32rr:
4380   case X86::SUB16rr:
4381   case X86::SUB8rr: {
4382     if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
4383       return false;
4384     // There is no use of the destination register, we can replace SUB with CMP.
4385     unsigned NewOpcode = 0;
4386     switch (CmpInstr.getOpcode()) {
4387     default: llvm_unreachable("Unreachable!");
4388     case X86::SUB64rm:   NewOpcode = X86::CMP64rm;   break;
4389     case X86::SUB32rm:   NewOpcode = X86::CMP32rm;   break;
4390     case X86::SUB16rm:   NewOpcode = X86::CMP16rm;   break;
4391     case X86::SUB8rm:    NewOpcode = X86::CMP8rm;    break;
4392     case X86::SUB64rr:   NewOpcode = X86::CMP64rr;   break;
4393     case X86::SUB32rr:   NewOpcode = X86::CMP32rr;   break;
4394     case X86::SUB16rr:   NewOpcode = X86::CMP16rr;   break;
4395     case X86::SUB8rr:    NewOpcode = X86::CMP8rr;    break;
4396     case X86::SUB64ri32: NewOpcode = X86::CMP64ri32; break;
4397     case X86::SUB32ri:   NewOpcode = X86::CMP32ri;   break;
4398     case X86::SUB16ri:   NewOpcode = X86::CMP16ri;   break;
4399     case X86::SUB8ri:    NewOpcode = X86::CMP8ri;    break;
4400     }
4401     CmpInstr.setDesc(get(NewOpcode));
4402     CmpInstr.removeOperand(0);
4403     // Mutating this instruction invalidates any debug data associated with it.
4404     CmpInstr.dropDebugNumber();
4405     // Fall through to optimize Cmp if Cmp is CMPrr or CMPri.
4406     if (NewOpcode == X86::CMP64rm || NewOpcode == X86::CMP32rm ||
4407         NewOpcode == X86::CMP16rm || NewOpcode == X86::CMP8rm)
4408       return false;
4409   }
4410   }
4411 
4412   // The following code tries to remove the comparison by re-using EFLAGS
4413   // from earlier instructions.
4414 
4415   bool IsCmpZero = (CmpMask != 0 && CmpValue == 0);
4416 
4417   // Transformation currently requires SSA values.
4418   if (SrcReg2.isPhysical())
4419     return false;
4420   MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg);
4421   assert(SrcRegDef && "Must have a definition (SSA)");
4422 
4423   MachineInstr *MI = nullptr;
4424   MachineInstr *Sub = nullptr;
4425   MachineInstr *Movr0Inst = nullptr;
4426   bool NoSignFlag = false;
4427   bool ClearsOverflowFlag = false;
4428   bool ShouldUpdateCC = false;
4429   bool IsSwapped = false;
4430   X86::CondCode NewCC = X86::COND_INVALID;
4431   int64_t ImmDelta = 0;
4432 
4433   // Search backward from CmpInstr for the next instruction defining EFLAGS.
4434   const TargetRegisterInfo *TRI = &getRegisterInfo();
4435   MachineBasicBlock &CmpMBB = *CmpInstr.getParent();
4436   MachineBasicBlock::reverse_iterator From =
4437       std::next(MachineBasicBlock::reverse_iterator(CmpInstr));
4438   for (MachineBasicBlock *MBB = &CmpMBB;;) {
4439     for (MachineInstr &Inst : make_range(From, MBB->rend())) {
4440       // Try to use EFLAGS from the instruction defining %SrcReg. Example:
4441       //     %eax = addl ...
4442       //     ...                // EFLAGS not changed
4443       //     testl %eax, %eax   // <-- can be removed
4444       if (&Inst == SrcRegDef) {
4445         if (IsCmpZero &&
4446             isDefConvertible(Inst, NoSignFlag, ClearsOverflowFlag)) {
4447           MI = &Inst;
4448           break;
4449         }
4450 
4451         // Look back for the following pattern, in which case the
4452         // test16rr/test64rr instruction could be erased.
4453         //
4454         // Example for test16rr:
4455         //  %reg = and32ri %in_reg, 5
4456         //  ...                         // EFLAGS not changed.
4457         //  %src_reg = copy %reg.sub_16bit:gr32
4458         //  test16rr %src_reg, %src_reg, implicit-def $eflags
4459         // Example for test64rr:
4460         //  %reg = and32ri %in_reg, 5
4461         //  ...                         // EFLAGS not changed.
4462         //  %src_reg = subreg_to_reg 0, %reg, %subreg.sub_index
4463         //  test64rr %src_reg, %src_reg, implicit-def $eflags
4464         MachineInstr *AndInstr = nullptr;
4465         if (IsCmpZero &&
4466             findRedundantFlagInstr(CmpInstr, Inst, MRI, &AndInstr, TRI,
4467                                    NoSignFlag, ClearsOverflowFlag)) {
4468           assert(AndInstr != nullptr && X86::isAND(AndInstr->getOpcode()));
4469           MI = AndInstr;
4470           break;
4471         }
4472         // Cannot find other candidates before definition of SrcReg.
4473         return false;
4474       }
4475 
4476       if (Inst.modifiesRegister(X86::EFLAGS, TRI)) {
4477         // Try to use EFLAGS produced by an instruction reading %SrcReg.
4478         // Example:
4479         //      %eax = ...
4480         //      ...
4481         //      popcntl %eax
4482         //      ...                 // EFLAGS not changed
4483         //      testl %eax, %eax    // <-- can be removed
4484         if (IsCmpZero) {
4485           NewCC = isUseDefConvertible(Inst);
4486           if (NewCC != X86::COND_INVALID && Inst.getOperand(1).isReg() &&
4487               Inst.getOperand(1).getReg() == SrcReg) {
4488             ShouldUpdateCC = true;
4489             MI = &Inst;
4490             break;
4491           }
4492         }
4493 
4494         // Try to use EFLAGS from an instruction with similar flag results.
4495         // Example:
4496         //     sub x, y  or  cmp x, y
4497         //     ...           // EFLAGS not changed
4498         //     cmp x, y      // <-- can be removed
4499         if (isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpMask, CmpValue,
4500                                  Inst, &IsSwapped, &ImmDelta)) {
4501           Sub = &Inst;
4502           break;
4503         }
4504 
4505         // MOV32r0 is implemented with xor which clobbers condition code. It is
4506         // safe to move up, if the definition to EFLAGS is dead and earlier
4507         // instructions do not read or write EFLAGS.
4508         if (!Movr0Inst && Inst.getOpcode() == X86::MOV32r0 &&
4509             Inst.registerDefIsDead(X86::EFLAGS, TRI)) {
4510           Movr0Inst = &Inst;
4511           continue;
4512         }
4513 
4514         // Cannot do anything for any other EFLAG changes.
4515         return false;
4516       }
4517     }
4518 
4519     if (MI || Sub)
4520       break;
4521 
4522     // Reached begin of basic block. Continue in predecessor if there is
4523     // exactly one.
4524     if (MBB->pred_size() != 1)
4525       return false;
4526     MBB = *MBB->pred_begin();
4527     From = MBB->rbegin();
4528   }
4529 
4530   // Scan forward from the instruction after CmpInstr for uses of EFLAGS.
4531   // It is safe to remove CmpInstr if EFLAGS is redefined or killed.
4532   // If we are done with the basic block, we need to check whether EFLAGS is
4533   // live-out.
4534   bool FlagsMayLiveOut = true;
4535   SmallVector<std::pair<MachineInstr*, X86::CondCode>, 4> OpsToUpdate;
4536   MachineBasicBlock::iterator AfterCmpInstr =
4537       std::next(MachineBasicBlock::iterator(CmpInstr));
4538   for (MachineInstr &Instr : make_range(AfterCmpInstr, CmpMBB.end())) {
4539     bool ModifyEFLAGS = Instr.modifiesRegister(X86::EFLAGS, TRI);
4540     bool UseEFLAGS = Instr.readsRegister(X86::EFLAGS, TRI);
4541     // We should check the usage if this instruction uses and updates EFLAGS.
4542     if (!UseEFLAGS && ModifyEFLAGS) {
4543       // It is safe to remove CmpInstr if EFLAGS is updated again.
4544       FlagsMayLiveOut = false;
4545       break;
4546     }
4547     if (!UseEFLAGS && !ModifyEFLAGS)
4548       continue;
4549 
4550     // EFLAGS is used by this instruction.
4551     X86::CondCode OldCC = X86::getCondFromMI(Instr);
4552     if ((MI || IsSwapped || ImmDelta != 0) && OldCC == X86::COND_INVALID)
4553       return false;
4554 
4555     X86::CondCode ReplacementCC = X86::COND_INVALID;
4556     if (MI) {
4557       switch (OldCC) {
4558       default: break;
4559       case X86::COND_A: case X86::COND_AE:
4560       case X86::COND_B: case X86::COND_BE:
4561         // CF is used, we can't perform this optimization.
4562         return false;
4563       case X86::COND_G: case X86::COND_GE:
4564       case X86::COND_L: case X86::COND_LE:
4565         // If SF is used, but the instruction doesn't update the SF, then we
4566         // can't do the optimization.
4567         if (NoSignFlag)
4568           return false;
4569         [[fallthrough]];
4570       case X86::COND_O: case X86::COND_NO:
4571         // If OF is used, the instruction needs to clear it like CmpZero does.
4572         if (!ClearsOverflowFlag)
4573           return false;
4574         break;
4575       case X86::COND_S: case X86::COND_NS:
4576         // If SF is used, but the instruction doesn't update the SF, then we
4577         // can't do the optimization.
4578         if (NoSignFlag)
4579           return false;
4580         break;
4581       }
4582 
4583       // If we're updating the condition code check if we have to reverse the
4584       // condition.
4585       if (ShouldUpdateCC)
4586         switch (OldCC) {
4587         default:
4588           return false;
4589         case X86::COND_E:
4590           ReplacementCC = NewCC;
4591           break;
4592         case X86::COND_NE:
4593           ReplacementCC = GetOppositeBranchCondition(NewCC);
4594           break;
4595         }
4596     } else if (IsSwapped) {
4597       // If we have SUB(r1, r2) and CMP(r2, r1), the condition code needs
4598       // to be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
4599       // We swap the condition code and synthesize the new opcode.
4600       ReplacementCC = getSwappedCondition(OldCC);
4601       if (ReplacementCC == X86::COND_INVALID)
4602         return false;
4603       ShouldUpdateCC = true;
4604     } else if (ImmDelta != 0) {
4605       unsigned BitWidth = TRI->getRegSizeInBits(*MRI->getRegClass(SrcReg));
4606       // Shift amount for min/max constants to adjust for 8/16/32 instruction
4607       // sizes.
4608       switch (OldCC) {
4609       case X86::COND_L: // x <s (C + 1)  -->  x <=s C
4610         if (ImmDelta != 1 || APInt::getSignedMinValue(BitWidth) == CmpValue)
4611           return false;
4612         ReplacementCC = X86::COND_LE;
4613         break;
4614       case X86::COND_B: // x <u (C + 1)  -->  x <=u C
4615         if (ImmDelta != 1 || CmpValue == 0)
4616           return false;
4617         ReplacementCC = X86::COND_BE;
4618         break;
4619       case X86::COND_GE: // x >=s (C + 1)  -->  x >s C
4620         if (ImmDelta != 1 || APInt::getSignedMinValue(BitWidth) == CmpValue)
4621           return false;
4622         ReplacementCC = X86::COND_G;
4623         break;
4624       case X86::COND_AE: // x >=u (C + 1)  -->  x >u C
4625         if (ImmDelta != 1 || CmpValue == 0)
4626           return false;
4627         ReplacementCC = X86::COND_A;
4628         break;
4629       case X86::COND_G: // x >s (C - 1)  -->  x >=s C
4630         if (ImmDelta != -1 || APInt::getSignedMaxValue(BitWidth) == CmpValue)
4631           return false;
4632         ReplacementCC = X86::COND_GE;
4633         break;
4634       case X86::COND_A: // x >u (C - 1)  -->  x >=u C
4635         if (ImmDelta != -1 || APInt::getMaxValue(BitWidth) == CmpValue)
4636           return false;
4637         ReplacementCC = X86::COND_AE;
4638         break;
4639       case X86::COND_LE: // x <=s (C - 1)  -->  x <s C
4640         if (ImmDelta != -1 || APInt::getSignedMaxValue(BitWidth) == CmpValue)
4641           return false;
4642         ReplacementCC = X86::COND_L;
4643         break;
4644       case X86::COND_BE: // x <=u (C - 1)  -->  x <u C
4645         if (ImmDelta != -1 || APInt::getMaxValue(BitWidth) == CmpValue)
4646           return false;
4647         ReplacementCC = X86::COND_B;
4648         break;
4649       default:
4650         return false;
4651       }
4652       ShouldUpdateCC = true;
4653     }
4654 
4655     if (ShouldUpdateCC && ReplacementCC != OldCC) {
4656       // Push the MachineInstr to OpsToUpdate.
4657       // If it is safe to remove CmpInstr, the condition code of these
4658       // instructions will be modified.
4659       OpsToUpdate.push_back(std::make_pair(&Instr, ReplacementCC));
4660     }
4661     if (ModifyEFLAGS || Instr.killsRegister(X86::EFLAGS, TRI)) {
4662       // It is safe to remove CmpInstr if EFLAGS is updated again or killed.
4663       FlagsMayLiveOut = false;
4664       break;
4665     }
4666   }
4667 
4668   // If we have to update users but EFLAGS is live-out abort, since we cannot
4669   // easily find all of the users.
4670   if ((MI != nullptr || ShouldUpdateCC) && FlagsMayLiveOut) {
4671     for (MachineBasicBlock *Successor : CmpMBB.successors())
4672       if (Successor->isLiveIn(X86::EFLAGS))
4673         return false;
4674   }
4675 
4676   // The instruction to be updated is either Sub or MI.
4677   assert((MI == nullptr || Sub == nullptr) && "Should not have Sub and MI set");
4678   Sub = MI != nullptr ? MI : Sub;
4679   MachineBasicBlock *SubBB = Sub->getParent();
4680   // Move Movr0Inst to the appropriate place before Sub.
4681   if (Movr0Inst) {
4682     // Only move within the same block so we don't accidentally move to a
4683     // block with higher execution frequency.
4684     if (&CmpMBB != SubBB)
4685       return false;
4686     // Look backwards until we find a def that doesn't use the current EFLAGS.
4687     MachineBasicBlock::reverse_iterator InsertI = Sub,
4688                                         InsertE = Sub->getParent()->rend();
4689     for (; InsertI != InsertE; ++InsertI) {
4690       MachineInstr *Instr = &*InsertI;
4691       if (!Instr->readsRegister(X86::EFLAGS, TRI) &&
4692           Instr->modifiesRegister(X86::EFLAGS, TRI)) {
4693         Movr0Inst->getParent()->remove(Movr0Inst);
4694         Instr->getParent()->insert(MachineBasicBlock::iterator(Instr),
4695                                    Movr0Inst);
4696         break;
4697       }
4698     }
4699     if (InsertI == InsertE)
4700       return false;
4701   }
4702 
4703   // Make sure Sub instruction defines EFLAGS and mark the def live.
4704   MachineOperand *FlagDef = Sub->findRegisterDefOperand(X86::EFLAGS);
4705   assert(FlagDef && "Unable to locate a def EFLAGS operand");
4706   FlagDef->setIsDead(false);
4707 
4708   CmpInstr.eraseFromParent();
4709 
4710   // Modify the condition code of instructions in OpsToUpdate.
4711   for (auto &Op : OpsToUpdate) {
4712     Op.first->getOperand(Op.first->getDesc().getNumOperands() - 1)
4713         .setImm(Op.second);
4714   }
4715   // Add EFLAGS to block live-ins between CmpBB and block of flags producer.
4716   for (MachineBasicBlock *MBB = &CmpMBB; MBB != SubBB;
4717        MBB = *MBB->pred_begin()) {
4718     assert(MBB->pred_size() == 1 && "Expected exactly one predecessor");
4719     if (!MBB->isLiveIn(X86::EFLAGS))
4720       MBB->addLiveIn(X86::EFLAGS);
4721   }
4722   return true;
4723 }
4724 
4725 /// Try to remove the load by folding it to a register
4726 /// operand at the use. We fold the load instructions if load defines a virtual
4727 /// register, the virtual register is used once in the same BB, and the
4728 /// instructions in-between do not load or store, and have no side effects.
4729 MachineInstr *X86InstrInfo::optimizeLoadInstr(MachineInstr &MI,
4730                                               const MachineRegisterInfo *MRI,
4731                                               Register &FoldAsLoadDefReg,
4732                                               MachineInstr *&DefMI) const {
4733   // Check whether we can move DefMI here.
4734   DefMI = MRI->getVRegDef(FoldAsLoadDefReg);
4735   assert(DefMI);
4736   bool SawStore = false;
4737   if (!DefMI->isSafeToMove(nullptr, SawStore))
4738     return nullptr;
4739 
4740   // Collect information about virtual register operands of MI.
4741   SmallVector<unsigned, 1> SrcOperandIds;
4742   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4743     MachineOperand &MO = MI.getOperand(i);
4744     if (!MO.isReg())
4745       continue;
4746     Register Reg = MO.getReg();
4747     if (Reg != FoldAsLoadDefReg)
4748       continue;
4749     // Do not fold if we have a subreg use or a def.
4750     if (MO.getSubReg() || MO.isDef())
4751       return nullptr;
4752     SrcOperandIds.push_back(i);
4753   }
4754   if (SrcOperandIds.empty())
4755     return nullptr;
4756 
4757   // Check whether we can fold the def into SrcOperandId.
4758   if (MachineInstr *FoldMI = foldMemoryOperand(MI, SrcOperandIds, *DefMI)) {
4759     FoldAsLoadDefReg = 0;
4760     return FoldMI;
4761   }
4762 
4763   return nullptr;
4764 }
4765 
4766 /// Expand a single-def pseudo instruction to a two-addr
4767 /// instruction with two undef reads of the register being defined.
4768 /// This is used for mapping:
4769 ///   %xmm4 = V_SET0
4770 /// to:
4771 ///   %xmm4 = PXORrr undef %xmm4, undef %xmm4
4772 ///
4773 static bool Expand2AddrUndef(MachineInstrBuilder &MIB,
4774                              const MCInstrDesc &Desc) {
4775   assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
4776   Register Reg = MIB.getReg(0);
4777   MIB->setDesc(Desc);
4778 
4779   // MachineInstr::addOperand() will insert explicit operands before any
4780   // implicit operands.
4781   MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
4782   // But we don't trust that.
4783   assert(MIB.getReg(1) == Reg &&
4784          MIB.getReg(2) == Reg && "Misplaced operand");
4785   return true;
4786 }
4787 
4788 /// Expand a single-def pseudo instruction to a two-addr
4789 /// instruction with two %k0 reads.
4790 /// This is used for mapping:
4791 ///   %k4 = K_SET1
4792 /// to:
4793 ///   %k4 = KXNORrr %k0, %k0
4794 static bool Expand2AddrKreg(MachineInstrBuilder &MIB, const MCInstrDesc &Desc,
4795                             Register Reg) {
4796   assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
4797   MIB->setDesc(Desc);
4798   MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
4799   return true;
4800 }
4801 
4802 static bool expandMOV32r1(MachineInstrBuilder &MIB, const TargetInstrInfo &TII,
4803                           bool MinusOne) {
4804   MachineBasicBlock &MBB = *MIB->getParent();
4805   const DebugLoc &DL = MIB->getDebugLoc();
4806   Register Reg = MIB.getReg(0);
4807 
4808   // Insert the XOR.
4809   BuildMI(MBB, MIB.getInstr(), DL, TII.get(X86::XOR32rr), Reg)
4810       .addReg(Reg, RegState::Undef)
4811       .addReg(Reg, RegState::Undef);
4812 
4813   // Turn the pseudo into an INC or DEC.
4814   MIB->setDesc(TII.get(MinusOne ? X86::DEC32r : X86::INC32r));
4815   MIB.addReg(Reg);
4816 
4817   return true;
4818 }
4819 
4820 static bool ExpandMOVImmSExti8(MachineInstrBuilder &MIB,
4821                                const TargetInstrInfo &TII,
4822                                const X86Subtarget &Subtarget) {
4823   MachineBasicBlock &MBB = *MIB->getParent();
4824   const DebugLoc &DL = MIB->getDebugLoc();
4825   int64_t Imm = MIB->getOperand(1).getImm();
4826   assert(Imm != 0 && "Using push/pop for 0 is not efficient.");
4827   MachineBasicBlock::iterator I = MIB.getInstr();
4828 
4829   int StackAdjustment;
4830 
4831   if (Subtarget.is64Bit()) {
4832     assert(MIB->getOpcode() == X86::MOV64ImmSExti8 ||
4833            MIB->getOpcode() == X86::MOV32ImmSExti8);
4834 
4835     // Can't use push/pop lowering if the function might write to the red zone.
4836     X86MachineFunctionInfo *X86FI =
4837         MBB.getParent()->getInfo<X86MachineFunctionInfo>();
4838     if (X86FI->getUsesRedZone()) {
4839       MIB->setDesc(TII.get(MIB->getOpcode() ==
4840                            X86::MOV32ImmSExti8 ? X86::MOV32ri : X86::MOV64ri));
4841       return true;
4842     }
4843 
4844     // 64-bit mode doesn't have 32-bit push/pop, so use 64-bit operations and
4845     // widen the register if necessary.
4846     StackAdjustment = 8;
4847     BuildMI(MBB, I, DL, TII.get(X86::PUSH64i32)).addImm(Imm);
4848     MIB->setDesc(TII.get(X86::POP64r));
4849     MIB->getOperand(0)
4850         .setReg(getX86SubSuperRegister(MIB.getReg(0), 64));
4851   } else {
4852     assert(MIB->getOpcode() == X86::MOV32ImmSExti8);
4853     StackAdjustment = 4;
4854     BuildMI(MBB, I, DL, TII.get(X86::PUSH32i)).addImm(Imm);
4855     MIB->setDesc(TII.get(X86::POP32r));
4856   }
4857   MIB->removeOperand(1);
4858   MIB->addImplicitDefUseOperands(*MBB.getParent());
4859 
4860   // Build CFI if necessary.
4861   MachineFunction &MF = *MBB.getParent();
4862   const X86FrameLowering *TFL = Subtarget.getFrameLowering();
4863   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
4864   bool NeedsDwarfCFI = !IsWin64Prologue && MF.needsFrameMoves();
4865   bool EmitCFI = !TFL->hasFP(MF) && NeedsDwarfCFI;
4866   if (EmitCFI) {
4867     TFL->BuildCFI(MBB, I, DL,
4868         MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
4869     TFL->BuildCFI(MBB, std::next(I), DL,
4870         MCCFIInstruction::createAdjustCfaOffset(nullptr, -StackAdjustment));
4871   }
4872 
4873   return true;
4874 }
4875 
4876 // LoadStackGuard has so far only been implemented for 64-bit MachO. Different
4877 // code sequence is needed for other targets.
4878 static void expandLoadStackGuard(MachineInstrBuilder &MIB,
4879                                  const TargetInstrInfo &TII) {
4880   MachineBasicBlock &MBB = *MIB->getParent();
4881   const DebugLoc &DL = MIB->getDebugLoc();
4882   Register Reg = MIB.getReg(0);
4883   const GlobalValue *GV =
4884       cast<GlobalValue>((*MIB->memoperands_begin())->getValue());
4885   auto Flags = MachineMemOperand::MOLoad |
4886                MachineMemOperand::MODereferenceable |
4887                MachineMemOperand::MOInvariant;
4888   MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
4889       MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 8, Align(8));
4890   MachineBasicBlock::iterator I = MIB.getInstr();
4891 
4892   BuildMI(MBB, I, DL, TII.get(X86::MOV64rm), Reg).addReg(X86::RIP).addImm(1)
4893       .addReg(0).addGlobalAddress(GV, 0, X86II::MO_GOTPCREL).addReg(0)
4894       .addMemOperand(MMO);
4895   MIB->setDebugLoc(DL);
4896   MIB->setDesc(TII.get(X86::MOV64rm));
4897   MIB.addReg(Reg, RegState::Kill).addImm(1).addReg(0).addImm(0).addReg(0);
4898 }
4899 
4900 static bool expandXorFP(MachineInstrBuilder &MIB, const TargetInstrInfo &TII) {
4901   MachineBasicBlock &MBB = *MIB->getParent();
4902   MachineFunction &MF = *MBB.getParent();
4903   const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
4904   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4905   unsigned XorOp =
4906       MIB->getOpcode() == X86::XOR64_FP ? X86::XOR64rr : X86::XOR32rr;
4907   MIB->setDesc(TII.get(XorOp));
4908   MIB.addReg(TRI->getFrameRegister(MF), RegState::Undef);
4909   return true;
4910 }
4911 
4912 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4913 // but not VLX. If it uses an extended register we need to use an instruction
4914 // that loads the lower 128/256-bit, but is available with only AVX512F.
4915 static bool expandNOVLXLoad(MachineInstrBuilder &MIB,
4916                             const TargetRegisterInfo *TRI,
4917                             const MCInstrDesc &LoadDesc,
4918                             const MCInstrDesc &BroadcastDesc,
4919                             unsigned SubIdx) {
4920   Register DestReg = MIB.getReg(0);
4921   // Check if DestReg is XMM16-31 or YMM16-31.
4922   if (TRI->getEncodingValue(DestReg) < 16) {
4923     // We can use a normal VEX encoded load.
4924     MIB->setDesc(LoadDesc);
4925   } else {
4926     // Use a 128/256-bit VBROADCAST instruction.
4927     MIB->setDesc(BroadcastDesc);
4928     // Change the destination to a 512-bit register.
4929     DestReg = TRI->getMatchingSuperReg(DestReg, SubIdx, &X86::VR512RegClass);
4930     MIB->getOperand(0).setReg(DestReg);
4931   }
4932   return true;
4933 }
4934 
4935 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4936 // but not VLX. If it uses an extended register we need to use an instruction
4937 // that stores the lower 128/256-bit, but is available with only AVX512F.
4938 static bool expandNOVLXStore(MachineInstrBuilder &MIB,
4939                              const TargetRegisterInfo *TRI,
4940                              const MCInstrDesc &StoreDesc,
4941                              const MCInstrDesc &ExtractDesc,
4942                              unsigned SubIdx) {
4943   Register SrcReg = MIB.getReg(X86::AddrNumOperands);
4944   // Check if DestReg is XMM16-31 or YMM16-31.
4945   if (TRI->getEncodingValue(SrcReg) < 16) {
4946     // We can use a normal VEX encoded store.
4947     MIB->setDesc(StoreDesc);
4948   } else {
4949     // Use a VEXTRACTF instruction.
4950     MIB->setDesc(ExtractDesc);
4951     // Change the destination to a 512-bit register.
4952     SrcReg = TRI->getMatchingSuperReg(SrcReg, SubIdx, &X86::VR512RegClass);
4953     MIB->getOperand(X86::AddrNumOperands).setReg(SrcReg);
4954     MIB.addImm(0x0); // Append immediate to extract from the lower bits.
4955   }
4956 
4957   return true;
4958 }
4959 
4960 static bool expandSHXDROT(MachineInstrBuilder &MIB, const MCInstrDesc &Desc) {
4961   MIB->setDesc(Desc);
4962   int64_t ShiftAmt = MIB->getOperand(2).getImm();
4963   // Temporarily remove the immediate so we can add another source register.
4964   MIB->removeOperand(2);
4965   // Add the register. Don't copy the kill flag if there is one.
4966   MIB.addReg(MIB.getReg(1),
4967              getUndefRegState(MIB->getOperand(1).isUndef()));
4968   // Add back the immediate.
4969   MIB.addImm(ShiftAmt);
4970   return true;
4971 }
4972 
4973 bool X86InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
4974   bool HasAVX = Subtarget.hasAVX();
4975   MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4976   switch (MI.getOpcode()) {
4977   case X86::MOV32r0:
4978     return Expand2AddrUndef(MIB, get(X86::XOR32rr));
4979   case X86::MOV32r1:
4980     return expandMOV32r1(MIB, *this, /*MinusOne=*/ false);
4981   case X86::MOV32r_1:
4982     return expandMOV32r1(MIB, *this, /*MinusOne=*/ true);
4983   case X86::MOV32ImmSExti8:
4984   case X86::MOV64ImmSExti8:
4985     return ExpandMOVImmSExti8(MIB, *this, Subtarget);
4986   case X86::SETB_C32r:
4987     return Expand2AddrUndef(MIB, get(X86::SBB32rr));
4988   case X86::SETB_C64r:
4989     return Expand2AddrUndef(MIB, get(X86::SBB64rr));
4990   case X86::MMX_SET0:
4991     return Expand2AddrUndef(MIB, get(X86::MMX_PXORrr));
4992   case X86::V_SET0:
4993   case X86::FsFLD0SS:
4994   case X86::FsFLD0SD:
4995   case X86::FsFLD0SH:
4996   case X86::FsFLD0F128:
4997     return Expand2AddrUndef(MIB, get(HasAVX ? X86::VXORPSrr : X86::XORPSrr));
4998   case X86::AVX_SET0: {
4999     assert(HasAVX && "AVX not supported");
5000     const TargetRegisterInfo *TRI = &getRegisterInfo();
5001     Register SrcReg = MIB.getReg(0);
5002     Register XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
5003     MIB->getOperand(0).setReg(XReg);
5004     Expand2AddrUndef(MIB, get(X86::VXORPSrr));
5005     MIB.addReg(SrcReg, RegState::ImplicitDefine);
5006     return true;
5007   }
5008   case X86::AVX512_128_SET0:
5009   case X86::AVX512_FsFLD0SH:
5010   case X86::AVX512_FsFLD0SS:
5011   case X86::AVX512_FsFLD0SD:
5012   case X86::AVX512_FsFLD0F128: {
5013     bool HasVLX = Subtarget.hasVLX();
5014     Register SrcReg = MIB.getReg(0);
5015     const TargetRegisterInfo *TRI = &getRegisterInfo();
5016     if (HasVLX || TRI->getEncodingValue(SrcReg) < 16)
5017       return Expand2AddrUndef(MIB,
5018                               get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
5019     // Extended register without VLX. Use a larger XOR.
5020     SrcReg =
5021         TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm, &X86::VR512RegClass);
5022     MIB->getOperand(0).setReg(SrcReg);
5023     return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
5024   }
5025   case X86::AVX512_256_SET0:
5026   case X86::AVX512_512_SET0: {
5027     bool HasVLX = Subtarget.hasVLX();
5028     Register SrcReg = MIB.getReg(0);
5029     const TargetRegisterInfo *TRI = &getRegisterInfo();
5030     if (HasVLX || TRI->getEncodingValue(SrcReg) < 16) {
5031       Register XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
5032       MIB->getOperand(0).setReg(XReg);
5033       Expand2AddrUndef(MIB,
5034                        get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
5035       MIB.addReg(SrcReg, RegState::ImplicitDefine);
5036       return true;
5037     }
5038     if (MI.getOpcode() == X86::AVX512_256_SET0) {
5039       // No VLX so we must reference a zmm.
5040       unsigned ZReg =
5041         TRI->getMatchingSuperReg(SrcReg, X86::sub_ymm, &X86::VR512RegClass);
5042       MIB->getOperand(0).setReg(ZReg);
5043     }
5044     return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
5045   }
5046   case X86::V_SETALLONES:
5047     return Expand2AddrUndef(MIB, get(HasAVX ? X86::VPCMPEQDrr : X86::PCMPEQDrr));
5048   case X86::AVX2_SETALLONES:
5049     return Expand2AddrUndef(MIB, get(X86::VPCMPEQDYrr));
5050   case X86::AVX1_SETALLONES: {
5051     Register Reg = MIB.getReg(0);
5052     // VCMPPSYrri with an immediate 0xf should produce VCMPTRUEPS.
5053     MIB->setDesc(get(X86::VCMPPSYrri));
5054     MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xf);
5055     return true;
5056   }
5057   case X86::AVX512_512_SETALLONES: {
5058     Register Reg = MIB.getReg(0);
5059     MIB->setDesc(get(X86::VPTERNLOGDZrri));
5060     // VPTERNLOGD needs 3 register inputs and an immediate.
5061     // 0xff will return 1s for any input.
5062     MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef)
5063        .addReg(Reg, RegState::Undef).addImm(0xff);
5064     return true;
5065   }
5066   case X86::AVX512_512_SEXT_MASK_32:
5067   case X86::AVX512_512_SEXT_MASK_64: {
5068     Register Reg = MIB.getReg(0);
5069     Register MaskReg = MIB.getReg(1);
5070     unsigned MaskState = getRegState(MIB->getOperand(1));
5071     unsigned Opc = (MI.getOpcode() == X86::AVX512_512_SEXT_MASK_64) ?
5072                    X86::VPTERNLOGQZrrikz : X86::VPTERNLOGDZrrikz;
5073     MI.removeOperand(1);
5074     MIB->setDesc(get(Opc));
5075     // VPTERNLOG needs 3 register inputs and an immediate.
5076     // 0xff will return 1s for any input.
5077     MIB.addReg(Reg, RegState::Undef).addReg(MaskReg, MaskState)
5078        .addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xff);
5079     return true;
5080   }
5081   case X86::VMOVAPSZ128rm_NOVLX:
5082     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSrm),
5083                            get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
5084   case X86::VMOVUPSZ128rm_NOVLX:
5085     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSrm),
5086                            get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
5087   case X86::VMOVAPSZ256rm_NOVLX:
5088     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSYrm),
5089                            get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
5090   case X86::VMOVUPSZ256rm_NOVLX:
5091     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSYrm),
5092                            get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
5093   case X86::VMOVAPSZ128mr_NOVLX:
5094     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSmr),
5095                             get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
5096   case X86::VMOVUPSZ128mr_NOVLX:
5097     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSmr),
5098                             get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
5099   case X86::VMOVAPSZ256mr_NOVLX:
5100     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSYmr),
5101                             get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
5102   case X86::VMOVUPSZ256mr_NOVLX:
5103     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSYmr),
5104                             get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
5105   case X86::MOV32ri64: {
5106     Register Reg = MIB.getReg(0);
5107     Register Reg32 = RI.getSubReg(Reg, X86::sub_32bit);
5108     MI.setDesc(get(X86::MOV32ri));
5109     MIB->getOperand(0).setReg(Reg32);
5110     MIB.addReg(Reg, RegState::ImplicitDefine);
5111     return true;
5112   }
5113 
5114   case X86::RDFLAGS32:
5115   case X86::RDFLAGS64: {
5116     unsigned Is64Bit = MI.getOpcode() == X86::RDFLAGS64;
5117     MachineBasicBlock &MBB = *MIB->getParent();
5118 
5119     MachineInstr *NewMI =
5120         BuildMI(MBB, MI, MIB->getDebugLoc(),
5121                 get(Is64Bit ? X86::PUSHF64 : X86::PUSHF32))
5122             .getInstr();
5123 
5124     // Permit reads of the EFLAGS and DF registers without them being defined.
5125     // This intrinsic exists to read external processor state in flags, such as
5126     // the trap flag, interrupt flag, and direction flag, none of which are
5127     // modeled by the backend.
5128     assert(NewMI->getOperand(2).getReg() == X86::EFLAGS &&
5129            "Unexpected register in operand! Should be EFLAGS.");
5130     NewMI->getOperand(2).setIsUndef();
5131     assert(NewMI->getOperand(3).getReg() == X86::DF &&
5132            "Unexpected register in operand! Should be DF.");
5133     NewMI->getOperand(3).setIsUndef();
5134 
5135     MIB->setDesc(get(Is64Bit ? X86::POP64r : X86::POP32r));
5136     return true;
5137   }
5138 
5139   case X86::WRFLAGS32:
5140   case X86::WRFLAGS64: {
5141     unsigned Is64Bit = MI.getOpcode() == X86::WRFLAGS64;
5142     MachineBasicBlock &MBB = *MIB->getParent();
5143 
5144     BuildMI(MBB, MI, MIB->getDebugLoc(),
5145             get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
5146         .addReg(MI.getOperand(0).getReg());
5147     BuildMI(MBB, MI, MIB->getDebugLoc(),
5148             get(Is64Bit ? X86::POPF64 : X86::POPF32));
5149     MI.eraseFromParent();
5150     return true;
5151   }
5152 
5153   // KNL does not recognize dependency-breaking idioms for mask registers,
5154   // so kxnor %k1, %k1, %k2 has a RAW dependence on %k1.
5155   // Using %k0 as the undef input register is a performance heuristic based
5156   // on the assumption that %k0 is used less frequently than the other mask
5157   // registers, since it is not usable as a write mask.
5158   // FIXME: A more advanced approach would be to choose the best input mask
5159   // register based on context.
5160   case X86::KSET0W: return Expand2AddrKreg(MIB, get(X86::KXORWrr), X86::K0);
5161   case X86::KSET0D: return Expand2AddrKreg(MIB, get(X86::KXORDrr), X86::K0);
5162   case X86::KSET0Q: return Expand2AddrKreg(MIB, get(X86::KXORQrr), X86::K0);
5163   case X86::KSET1W: return Expand2AddrKreg(MIB, get(X86::KXNORWrr), X86::K0);
5164   case X86::KSET1D: return Expand2AddrKreg(MIB, get(X86::KXNORDrr), X86::K0);
5165   case X86::KSET1Q: return Expand2AddrKreg(MIB, get(X86::KXNORQrr), X86::K0);
5166   case TargetOpcode::LOAD_STACK_GUARD:
5167     expandLoadStackGuard(MIB, *this);
5168     return true;
5169   case X86::XOR64_FP:
5170   case X86::XOR32_FP:
5171     return expandXorFP(MIB, *this);
5172   case X86::SHLDROT32ri: return expandSHXDROT(MIB, get(X86::SHLD32rri8));
5173   case X86::SHLDROT64ri: return expandSHXDROT(MIB, get(X86::SHLD64rri8));
5174   case X86::SHRDROT32ri: return expandSHXDROT(MIB, get(X86::SHRD32rri8));
5175   case X86::SHRDROT64ri: return expandSHXDROT(MIB, get(X86::SHRD64rri8));
5176   case X86::ADD8rr_DB:    MIB->setDesc(get(X86::OR8rr));    break;
5177   case X86::ADD16rr_DB:   MIB->setDesc(get(X86::OR16rr));   break;
5178   case X86::ADD32rr_DB:   MIB->setDesc(get(X86::OR32rr));   break;
5179   case X86::ADD64rr_DB:   MIB->setDesc(get(X86::OR64rr));   break;
5180   case X86::ADD8ri_DB:    MIB->setDesc(get(X86::OR8ri));    break;
5181   case X86::ADD16ri_DB:   MIB->setDesc(get(X86::OR16ri));   break;
5182   case X86::ADD32ri_DB:   MIB->setDesc(get(X86::OR32ri));   break;
5183   case X86::ADD64ri32_DB: MIB->setDesc(get(X86::OR64ri32)); break;
5184   }
5185   return false;
5186 }
5187 
5188 /// Return true for all instructions that only update
5189 /// the first 32 or 64-bits of the destination register and leave the rest
5190 /// unmodified. This can be used to avoid folding loads if the instructions
5191 /// only update part of the destination register, and the non-updated part is
5192 /// not needed. e.g. cvtss2sd, sqrtss. Unfolding the load from these
5193 /// instructions breaks the partial register dependency and it can improve
5194 /// performance. e.g.:
5195 ///
5196 ///   movss (%rdi), %xmm0
5197 ///   cvtss2sd %xmm0, %xmm0
5198 ///
5199 /// Instead of
5200 ///   cvtss2sd (%rdi), %xmm0
5201 ///
5202 /// FIXME: This should be turned into a TSFlags.
5203 ///
5204 static bool hasPartialRegUpdate(unsigned Opcode,
5205                                 const X86Subtarget &Subtarget,
5206                                 bool ForLoadFold = false) {
5207   switch (Opcode) {
5208   case X86::CVTSI2SSrr:
5209   case X86::CVTSI2SSrm:
5210   case X86::CVTSI642SSrr:
5211   case X86::CVTSI642SSrm:
5212   case X86::CVTSI2SDrr:
5213   case X86::CVTSI2SDrm:
5214   case X86::CVTSI642SDrr:
5215   case X86::CVTSI642SDrm:
5216     // Load folding won't effect the undef register update since the input is
5217     // a GPR.
5218     return !ForLoadFold;
5219   case X86::CVTSD2SSrr:
5220   case X86::CVTSD2SSrm:
5221   case X86::CVTSS2SDrr:
5222   case X86::CVTSS2SDrm:
5223   case X86::MOVHPDrm:
5224   case X86::MOVHPSrm:
5225   case X86::MOVLPDrm:
5226   case X86::MOVLPSrm:
5227   case X86::RCPSSr:
5228   case X86::RCPSSm:
5229   case X86::RCPSSr_Int:
5230   case X86::RCPSSm_Int:
5231   case X86::ROUNDSDr:
5232   case X86::ROUNDSDm:
5233   case X86::ROUNDSSr:
5234   case X86::ROUNDSSm:
5235   case X86::RSQRTSSr:
5236   case X86::RSQRTSSm:
5237   case X86::RSQRTSSr_Int:
5238   case X86::RSQRTSSm_Int:
5239   case X86::SQRTSSr:
5240   case X86::SQRTSSm:
5241   case X86::SQRTSSr_Int:
5242   case X86::SQRTSSm_Int:
5243   case X86::SQRTSDr:
5244   case X86::SQRTSDm:
5245   case X86::SQRTSDr_Int:
5246   case X86::SQRTSDm_Int:
5247     return true;
5248   case X86::VFCMULCPHZ128rm:
5249   case X86::VFCMULCPHZ128rmb:
5250   case X86::VFCMULCPHZ128rmbkz:
5251   case X86::VFCMULCPHZ128rmkz:
5252   case X86::VFCMULCPHZ128rr:
5253   case X86::VFCMULCPHZ128rrkz:
5254   case X86::VFCMULCPHZ256rm:
5255   case X86::VFCMULCPHZ256rmb:
5256   case X86::VFCMULCPHZ256rmbkz:
5257   case X86::VFCMULCPHZ256rmkz:
5258   case X86::VFCMULCPHZ256rr:
5259   case X86::VFCMULCPHZ256rrkz:
5260   case X86::VFCMULCPHZrm:
5261   case X86::VFCMULCPHZrmb:
5262   case X86::VFCMULCPHZrmbkz:
5263   case X86::VFCMULCPHZrmkz:
5264   case X86::VFCMULCPHZrr:
5265   case X86::VFCMULCPHZrrb:
5266   case X86::VFCMULCPHZrrbkz:
5267   case X86::VFCMULCPHZrrkz:
5268   case X86::VFMULCPHZ128rm:
5269   case X86::VFMULCPHZ128rmb:
5270   case X86::VFMULCPHZ128rmbkz:
5271   case X86::VFMULCPHZ128rmkz:
5272   case X86::VFMULCPHZ128rr:
5273   case X86::VFMULCPHZ128rrkz:
5274   case X86::VFMULCPHZ256rm:
5275   case X86::VFMULCPHZ256rmb:
5276   case X86::VFMULCPHZ256rmbkz:
5277   case X86::VFMULCPHZ256rmkz:
5278   case X86::VFMULCPHZ256rr:
5279   case X86::VFMULCPHZ256rrkz:
5280   case X86::VFMULCPHZrm:
5281   case X86::VFMULCPHZrmb:
5282   case X86::VFMULCPHZrmbkz:
5283   case X86::VFMULCPHZrmkz:
5284   case X86::VFMULCPHZrr:
5285   case X86::VFMULCPHZrrb:
5286   case X86::VFMULCPHZrrbkz:
5287   case X86::VFMULCPHZrrkz:
5288   case X86::VFCMULCSHZrm:
5289   case X86::VFCMULCSHZrmkz:
5290   case X86::VFCMULCSHZrr:
5291   case X86::VFCMULCSHZrrb:
5292   case X86::VFCMULCSHZrrbkz:
5293   case X86::VFCMULCSHZrrkz:
5294   case X86::VFMULCSHZrm:
5295   case X86::VFMULCSHZrmkz:
5296   case X86::VFMULCSHZrr:
5297   case X86::VFMULCSHZrrb:
5298   case X86::VFMULCSHZrrbkz:
5299   case X86::VFMULCSHZrrkz:
5300     return Subtarget.hasMULCFalseDeps();
5301   case X86::VPERMDYrm:
5302   case X86::VPERMDYrr:
5303   case X86::VPERMQYmi:
5304   case X86::VPERMQYri:
5305   case X86::VPERMPSYrm:
5306   case X86::VPERMPSYrr:
5307   case X86::VPERMPDYmi:
5308   case X86::VPERMPDYri:
5309   case X86::VPERMDZ256rm:
5310   case X86::VPERMDZ256rmb:
5311   case X86::VPERMDZ256rmbkz:
5312   case X86::VPERMDZ256rmkz:
5313   case X86::VPERMDZ256rr:
5314   case X86::VPERMDZ256rrkz:
5315   case X86::VPERMDZrm:
5316   case X86::VPERMDZrmb:
5317   case X86::VPERMDZrmbkz:
5318   case X86::VPERMDZrmkz:
5319   case X86::VPERMDZrr:
5320   case X86::VPERMDZrrkz:
5321   case X86::VPERMQZ256mbi:
5322   case X86::VPERMQZ256mbikz:
5323   case X86::VPERMQZ256mi:
5324   case X86::VPERMQZ256mikz:
5325   case X86::VPERMQZ256ri:
5326   case X86::VPERMQZ256rikz:
5327   case X86::VPERMQZ256rm:
5328   case X86::VPERMQZ256rmb:
5329   case X86::VPERMQZ256rmbkz:
5330   case X86::VPERMQZ256rmkz:
5331   case X86::VPERMQZ256rr:
5332   case X86::VPERMQZ256rrkz:
5333   case X86::VPERMQZmbi:
5334   case X86::VPERMQZmbikz:
5335   case X86::VPERMQZmi:
5336   case X86::VPERMQZmikz:
5337   case X86::VPERMQZri:
5338   case X86::VPERMQZrikz:
5339   case X86::VPERMQZrm:
5340   case X86::VPERMQZrmb:
5341   case X86::VPERMQZrmbkz:
5342   case X86::VPERMQZrmkz:
5343   case X86::VPERMQZrr:
5344   case X86::VPERMQZrrkz:
5345   case X86::VPERMPSZ256rm:
5346   case X86::VPERMPSZ256rmb:
5347   case X86::VPERMPSZ256rmbkz:
5348   case X86::VPERMPSZ256rmkz:
5349   case X86::VPERMPSZ256rr:
5350   case X86::VPERMPSZ256rrkz:
5351   case X86::VPERMPSZrm:
5352   case X86::VPERMPSZrmb:
5353   case X86::VPERMPSZrmbkz:
5354   case X86::VPERMPSZrmkz:
5355   case X86::VPERMPSZrr:
5356   case X86::VPERMPSZrrkz:
5357   case X86::VPERMPDZ256mbi:
5358   case X86::VPERMPDZ256mbikz:
5359   case X86::VPERMPDZ256mi:
5360   case X86::VPERMPDZ256mikz:
5361   case X86::VPERMPDZ256ri:
5362   case X86::VPERMPDZ256rikz:
5363   case X86::VPERMPDZ256rm:
5364   case X86::VPERMPDZ256rmb:
5365   case X86::VPERMPDZ256rmbkz:
5366   case X86::VPERMPDZ256rmkz:
5367   case X86::VPERMPDZ256rr:
5368   case X86::VPERMPDZ256rrkz:
5369   case X86::VPERMPDZmbi:
5370   case X86::VPERMPDZmbikz:
5371   case X86::VPERMPDZmi:
5372   case X86::VPERMPDZmikz:
5373   case X86::VPERMPDZri:
5374   case X86::VPERMPDZrikz:
5375   case X86::VPERMPDZrm:
5376   case X86::VPERMPDZrmb:
5377   case X86::VPERMPDZrmbkz:
5378   case X86::VPERMPDZrmkz:
5379   case X86::VPERMPDZrr:
5380   case X86::VPERMPDZrrkz:
5381     return Subtarget.hasPERMFalseDeps();
5382   case X86::VRANGEPDZ128rmbi:
5383   case X86::VRANGEPDZ128rmbikz:
5384   case X86::VRANGEPDZ128rmi:
5385   case X86::VRANGEPDZ128rmikz:
5386   case X86::VRANGEPDZ128rri:
5387   case X86::VRANGEPDZ128rrikz:
5388   case X86::VRANGEPDZ256rmbi:
5389   case X86::VRANGEPDZ256rmbikz:
5390   case X86::VRANGEPDZ256rmi:
5391   case X86::VRANGEPDZ256rmikz:
5392   case X86::VRANGEPDZ256rri:
5393   case X86::VRANGEPDZ256rrikz:
5394   case X86::VRANGEPDZrmbi:
5395   case X86::VRANGEPDZrmbikz:
5396   case X86::VRANGEPDZrmi:
5397   case X86::VRANGEPDZrmikz:
5398   case X86::VRANGEPDZrri:
5399   case X86::VRANGEPDZrrib:
5400   case X86::VRANGEPDZrribkz:
5401   case X86::VRANGEPDZrrikz:
5402   case X86::VRANGEPSZ128rmbi:
5403   case X86::VRANGEPSZ128rmbikz:
5404   case X86::VRANGEPSZ128rmi:
5405   case X86::VRANGEPSZ128rmikz:
5406   case X86::VRANGEPSZ128rri:
5407   case X86::VRANGEPSZ128rrikz:
5408   case X86::VRANGEPSZ256rmbi:
5409   case X86::VRANGEPSZ256rmbikz:
5410   case X86::VRANGEPSZ256rmi:
5411   case X86::VRANGEPSZ256rmikz:
5412   case X86::VRANGEPSZ256rri:
5413   case X86::VRANGEPSZ256rrikz:
5414   case X86::VRANGEPSZrmbi:
5415   case X86::VRANGEPSZrmbikz:
5416   case X86::VRANGEPSZrmi:
5417   case X86::VRANGEPSZrmikz:
5418   case X86::VRANGEPSZrri:
5419   case X86::VRANGEPSZrrib:
5420   case X86::VRANGEPSZrribkz:
5421   case X86::VRANGEPSZrrikz:
5422   case X86::VRANGESDZrmi:
5423   case X86::VRANGESDZrmikz:
5424   case X86::VRANGESDZrri:
5425   case X86::VRANGESDZrrib:
5426   case X86::VRANGESDZrribkz:
5427   case X86::VRANGESDZrrikz:
5428   case X86::VRANGESSZrmi:
5429   case X86::VRANGESSZrmikz:
5430   case X86::VRANGESSZrri:
5431   case X86::VRANGESSZrrib:
5432   case X86::VRANGESSZrribkz:
5433   case X86::VRANGESSZrrikz:
5434     return Subtarget.hasRANGEFalseDeps();
5435   case X86::VGETMANTSSZrmi:
5436   case X86::VGETMANTSSZrmikz:
5437   case X86::VGETMANTSSZrri:
5438   case X86::VGETMANTSSZrrib:
5439   case X86::VGETMANTSSZrribkz:
5440   case X86::VGETMANTSSZrrikz:
5441   case X86::VGETMANTSDZrmi:
5442   case X86::VGETMANTSDZrmikz:
5443   case X86::VGETMANTSDZrri:
5444   case X86::VGETMANTSDZrrib:
5445   case X86::VGETMANTSDZrribkz:
5446   case X86::VGETMANTSDZrrikz:
5447   case X86::VGETMANTSHZrmi:
5448   case X86::VGETMANTSHZrmikz:
5449   case X86::VGETMANTSHZrri:
5450   case X86::VGETMANTSHZrrib:
5451   case X86::VGETMANTSHZrribkz:
5452   case X86::VGETMANTSHZrrikz:
5453   case X86::VGETMANTPSZ128rmbi:
5454   case X86::VGETMANTPSZ128rmbikz:
5455   case X86::VGETMANTPSZ128rmi:
5456   case X86::VGETMANTPSZ128rmikz:
5457   case X86::VGETMANTPSZ256rmbi:
5458   case X86::VGETMANTPSZ256rmbikz:
5459   case X86::VGETMANTPSZ256rmi:
5460   case X86::VGETMANTPSZ256rmikz:
5461   case X86::VGETMANTPSZrmbi:
5462   case X86::VGETMANTPSZrmbikz:
5463   case X86::VGETMANTPSZrmi:
5464   case X86::VGETMANTPSZrmikz:
5465   case X86::VGETMANTPDZ128rmbi:
5466   case X86::VGETMANTPDZ128rmbikz:
5467   case X86::VGETMANTPDZ128rmi:
5468   case X86::VGETMANTPDZ128rmikz:
5469   case X86::VGETMANTPDZ256rmbi:
5470   case X86::VGETMANTPDZ256rmbikz:
5471   case X86::VGETMANTPDZ256rmi:
5472   case X86::VGETMANTPDZ256rmikz:
5473   case X86::VGETMANTPDZrmbi:
5474   case X86::VGETMANTPDZrmbikz:
5475   case X86::VGETMANTPDZrmi:
5476   case X86::VGETMANTPDZrmikz:
5477     return Subtarget.hasGETMANTFalseDeps();
5478   case X86::VPMULLQZ128rm:
5479   case X86::VPMULLQZ128rmb:
5480   case X86::VPMULLQZ128rmbkz:
5481   case X86::VPMULLQZ128rmkz:
5482   case X86::VPMULLQZ128rr:
5483   case X86::VPMULLQZ128rrkz:
5484   case X86::VPMULLQZ256rm:
5485   case X86::VPMULLQZ256rmb:
5486   case X86::VPMULLQZ256rmbkz:
5487   case X86::VPMULLQZ256rmkz:
5488   case X86::VPMULLQZ256rr:
5489   case X86::VPMULLQZ256rrkz:
5490   case X86::VPMULLQZrm:
5491   case X86::VPMULLQZrmb:
5492   case X86::VPMULLQZrmbkz:
5493   case X86::VPMULLQZrmkz:
5494   case X86::VPMULLQZrr:
5495   case X86::VPMULLQZrrkz:
5496     return Subtarget.hasMULLQFalseDeps();
5497   // GPR
5498   case X86::POPCNT32rm:
5499   case X86::POPCNT32rr:
5500   case X86::POPCNT64rm:
5501   case X86::POPCNT64rr:
5502     return Subtarget.hasPOPCNTFalseDeps();
5503   case X86::LZCNT32rm:
5504   case X86::LZCNT32rr:
5505   case X86::LZCNT64rm:
5506   case X86::LZCNT64rr:
5507   case X86::TZCNT32rm:
5508   case X86::TZCNT32rr:
5509   case X86::TZCNT64rm:
5510   case X86::TZCNT64rr:
5511     return Subtarget.hasLZCNTFalseDeps();
5512   }
5513 
5514   return false;
5515 }
5516 
5517 /// Inform the BreakFalseDeps pass how many idle
5518 /// instructions we would like before a partial register update.
5519 unsigned X86InstrInfo::getPartialRegUpdateClearance(
5520     const MachineInstr &MI, unsigned OpNum,
5521     const TargetRegisterInfo *TRI) const {
5522   if (OpNum != 0 || !hasPartialRegUpdate(MI.getOpcode(), Subtarget))
5523     return 0;
5524 
5525   // If MI is marked as reading Reg, the partial register update is wanted.
5526   const MachineOperand &MO = MI.getOperand(0);
5527   Register Reg = MO.getReg();
5528   if (Reg.isVirtual()) {
5529     if (MO.readsReg() || MI.readsVirtualRegister(Reg))
5530       return 0;
5531   } else {
5532     if (MI.readsRegister(Reg, TRI))
5533       return 0;
5534   }
5535 
5536   // If any instructions in the clearance range are reading Reg, insert a
5537   // dependency breaking instruction, which is inexpensive and is likely to
5538   // be hidden in other instruction's cycles.
5539   return PartialRegUpdateClearance;
5540 }
5541 
5542 // Return true for any instruction the copies the high bits of the first source
5543 // operand into the unused high bits of the destination operand.
5544 // Also returns true for instructions that have two inputs where one may
5545 // be undef and we want it to use the same register as the other input.
5546 static bool hasUndefRegUpdate(unsigned Opcode, unsigned OpNum,
5547                               bool ForLoadFold = false) {
5548   // Set the OpNum parameter to the first source operand.
5549   switch (Opcode) {
5550   case X86::MMX_PUNPCKHBWrr:
5551   case X86::MMX_PUNPCKHWDrr:
5552   case X86::MMX_PUNPCKHDQrr:
5553   case X86::MMX_PUNPCKLBWrr:
5554   case X86::MMX_PUNPCKLWDrr:
5555   case X86::MMX_PUNPCKLDQrr:
5556   case X86::MOVHLPSrr:
5557   case X86::PACKSSWBrr:
5558   case X86::PACKUSWBrr:
5559   case X86::PACKSSDWrr:
5560   case X86::PACKUSDWrr:
5561   case X86::PUNPCKHBWrr:
5562   case X86::PUNPCKLBWrr:
5563   case X86::PUNPCKHWDrr:
5564   case X86::PUNPCKLWDrr:
5565   case X86::PUNPCKHDQrr:
5566   case X86::PUNPCKLDQrr:
5567   case X86::PUNPCKHQDQrr:
5568   case X86::PUNPCKLQDQrr:
5569   case X86::SHUFPDrri:
5570   case X86::SHUFPSrri:
5571     // These instructions are sometimes used with an undef first or second
5572     // source. Return true here so BreakFalseDeps will assign this source to the
5573     // same register as the first source to avoid a false dependency.
5574     // Operand 1 of these instructions is tied so they're separate from their
5575     // VEX counterparts.
5576     return OpNum == 2 && !ForLoadFold;
5577 
5578   case X86::VMOVLHPSrr:
5579   case X86::VMOVLHPSZrr:
5580   case X86::VPACKSSWBrr:
5581   case X86::VPACKUSWBrr:
5582   case X86::VPACKSSDWrr:
5583   case X86::VPACKUSDWrr:
5584   case X86::VPACKSSWBZ128rr:
5585   case X86::VPACKUSWBZ128rr:
5586   case X86::VPACKSSDWZ128rr:
5587   case X86::VPACKUSDWZ128rr:
5588   case X86::VPERM2F128rr:
5589   case X86::VPERM2I128rr:
5590   case X86::VSHUFF32X4Z256rri:
5591   case X86::VSHUFF32X4Zrri:
5592   case X86::VSHUFF64X2Z256rri:
5593   case X86::VSHUFF64X2Zrri:
5594   case X86::VSHUFI32X4Z256rri:
5595   case X86::VSHUFI32X4Zrri:
5596   case X86::VSHUFI64X2Z256rri:
5597   case X86::VSHUFI64X2Zrri:
5598   case X86::VPUNPCKHBWrr:
5599   case X86::VPUNPCKLBWrr:
5600   case X86::VPUNPCKHBWYrr:
5601   case X86::VPUNPCKLBWYrr:
5602   case X86::VPUNPCKHBWZ128rr:
5603   case X86::VPUNPCKLBWZ128rr:
5604   case X86::VPUNPCKHBWZ256rr:
5605   case X86::VPUNPCKLBWZ256rr:
5606   case X86::VPUNPCKHBWZrr:
5607   case X86::VPUNPCKLBWZrr:
5608   case X86::VPUNPCKHWDrr:
5609   case X86::VPUNPCKLWDrr:
5610   case X86::VPUNPCKHWDYrr:
5611   case X86::VPUNPCKLWDYrr:
5612   case X86::VPUNPCKHWDZ128rr:
5613   case X86::VPUNPCKLWDZ128rr:
5614   case X86::VPUNPCKHWDZ256rr:
5615   case X86::VPUNPCKLWDZ256rr:
5616   case X86::VPUNPCKHWDZrr:
5617   case X86::VPUNPCKLWDZrr:
5618   case X86::VPUNPCKHDQrr:
5619   case X86::VPUNPCKLDQrr:
5620   case X86::VPUNPCKHDQYrr:
5621   case X86::VPUNPCKLDQYrr:
5622   case X86::VPUNPCKHDQZ128rr:
5623   case X86::VPUNPCKLDQZ128rr:
5624   case X86::VPUNPCKHDQZ256rr:
5625   case X86::VPUNPCKLDQZ256rr:
5626   case X86::VPUNPCKHDQZrr:
5627   case X86::VPUNPCKLDQZrr:
5628   case X86::VPUNPCKHQDQrr:
5629   case X86::VPUNPCKLQDQrr:
5630   case X86::VPUNPCKHQDQYrr:
5631   case X86::VPUNPCKLQDQYrr:
5632   case X86::VPUNPCKHQDQZ128rr:
5633   case X86::VPUNPCKLQDQZ128rr:
5634   case X86::VPUNPCKHQDQZ256rr:
5635   case X86::VPUNPCKLQDQZ256rr:
5636   case X86::VPUNPCKHQDQZrr:
5637   case X86::VPUNPCKLQDQZrr:
5638     // These instructions are sometimes used with an undef first or second
5639     // source. Return true here so BreakFalseDeps will assign this source to the
5640     // same register as the first source to avoid a false dependency.
5641     return (OpNum == 1 || OpNum == 2) && !ForLoadFold;
5642 
5643   case X86::VCVTSI2SSrr:
5644   case X86::VCVTSI2SSrm:
5645   case X86::VCVTSI2SSrr_Int:
5646   case X86::VCVTSI2SSrm_Int:
5647   case X86::VCVTSI642SSrr:
5648   case X86::VCVTSI642SSrm:
5649   case X86::VCVTSI642SSrr_Int:
5650   case X86::VCVTSI642SSrm_Int:
5651   case X86::VCVTSI2SDrr:
5652   case X86::VCVTSI2SDrm:
5653   case X86::VCVTSI2SDrr_Int:
5654   case X86::VCVTSI2SDrm_Int:
5655   case X86::VCVTSI642SDrr:
5656   case X86::VCVTSI642SDrm:
5657   case X86::VCVTSI642SDrr_Int:
5658   case X86::VCVTSI642SDrm_Int:
5659   // AVX-512
5660   case X86::VCVTSI2SSZrr:
5661   case X86::VCVTSI2SSZrm:
5662   case X86::VCVTSI2SSZrr_Int:
5663   case X86::VCVTSI2SSZrrb_Int:
5664   case X86::VCVTSI2SSZrm_Int:
5665   case X86::VCVTSI642SSZrr:
5666   case X86::VCVTSI642SSZrm:
5667   case X86::VCVTSI642SSZrr_Int:
5668   case X86::VCVTSI642SSZrrb_Int:
5669   case X86::VCVTSI642SSZrm_Int:
5670   case X86::VCVTSI2SDZrr:
5671   case X86::VCVTSI2SDZrm:
5672   case X86::VCVTSI2SDZrr_Int:
5673   case X86::VCVTSI2SDZrm_Int:
5674   case X86::VCVTSI642SDZrr:
5675   case X86::VCVTSI642SDZrm:
5676   case X86::VCVTSI642SDZrr_Int:
5677   case X86::VCVTSI642SDZrrb_Int:
5678   case X86::VCVTSI642SDZrm_Int:
5679   case X86::VCVTUSI2SSZrr:
5680   case X86::VCVTUSI2SSZrm:
5681   case X86::VCVTUSI2SSZrr_Int:
5682   case X86::VCVTUSI2SSZrrb_Int:
5683   case X86::VCVTUSI2SSZrm_Int:
5684   case X86::VCVTUSI642SSZrr:
5685   case X86::VCVTUSI642SSZrm:
5686   case X86::VCVTUSI642SSZrr_Int:
5687   case X86::VCVTUSI642SSZrrb_Int:
5688   case X86::VCVTUSI642SSZrm_Int:
5689   case X86::VCVTUSI2SDZrr:
5690   case X86::VCVTUSI2SDZrm:
5691   case X86::VCVTUSI2SDZrr_Int:
5692   case X86::VCVTUSI2SDZrm_Int:
5693   case X86::VCVTUSI642SDZrr:
5694   case X86::VCVTUSI642SDZrm:
5695   case X86::VCVTUSI642SDZrr_Int:
5696   case X86::VCVTUSI642SDZrrb_Int:
5697   case X86::VCVTUSI642SDZrm_Int:
5698   case X86::VCVTSI2SHZrr:
5699   case X86::VCVTSI2SHZrm:
5700   case X86::VCVTSI2SHZrr_Int:
5701   case X86::VCVTSI2SHZrrb_Int:
5702   case X86::VCVTSI2SHZrm_Int:
5703   case X86::VCVTSI642SHZrr:
5704   case X86::VCVTSI642SHZrm:
5705   case X86::VCVTSI642SHZrr_Int:
5706   case X86::VCVTSI642SHZrrb_Int:
5707   case X86::VCVTSI642SHZrm_Int:
5708   case X86::VCVTUSI2SHZrr:
5709   case X86::VCVTUSI2SHZrm:
5710   case X86::VCVTUSI2SHZrr_Int:
5711   case X86::VCVTUSI2SHZrrb_Int:
5712   case X86::VCVTUSI2SHZrm_Int:
5713   case X86::VCVTUSI642SHZrr:
5714   case X86::VCVTUSI642SHZrm:
5715   case X86::VCVTUSI642SHZrr_Int:
5716   case X86::VCVTUSI642SHZrrb_Int:
5717   case X86::VCVTUSI642SHZrm_Int:
5718     // Load folding won't effect the undef register update since the input is
5719     // a GPR.
5720     return OpNum == 1 && !ForLoadFold;
5721   case X86::VCVTSD2SSrr:
5722   case X86::VCVTSD2SSrm:
5723   case X86::VCVTSD2SSrr_Int:
5724   case X86::VCVTSD2SSrm_Int:
5725   case X86::VCVTSS2SDrr:
5726   case X86::VCVTSS2SDrm:
5727   case X86::VCVTSS2SDrr_Int:
5728   case X86::VCVTSS2SDrm_Int:
5729   case X86::VRCPSSr:
5730   case X86::VRCPSSr_Int:
5731   case X86::VRCPSSm:
5732   case X86::VRCPSSm_Int:
5733   case X86::VROUNDSDr:
5734   case X86::VROUNDSDm:
5735   case X86::VROUNDSDr_Int:
5736   case X86::VROUNDSDm_Int:
5737   case X86::VROUNDSSr:
5738   case X86::VROUNDSSm:
5739   case X86::VROUNDSSr_Int:
5740   case X86::VROUNDSSm_Int:
5741   case X86::VRSQRTSSr:
5742   case X86::VRSQRTSSr_Int:
5743   case X86::VRSQRTSSm:
5744   case X86::VRSQRTSSm_Int:
5745   case X86::VSQRTSSr:
5746   case X86::VSQRTSSr_Int:
5747   case X86::VSQRTSSm:
5748   case X86::VSQRTSSm_Int:
5749   case X86::VSQRTSDr:
5750   case X86::VSQRTSDr_Int:
5751   case X86::VSQRTSDm:
5752   case X86::VSQRTSDm_Int:
5753   // AVX-512
5754   case X86::VCVTSD2SSZrr:
5755   case X86::VCVTSD2SSZrr_Int:
5756   case X86::VCVTSD2SSZrrb_Int:
5757   case X86::VCVTSD2SSZrm:
5758   case X86::VCVTSD2SSZrm_Int:
5759   case X86::VCVTSS2SDZrr:
5760   case X86::VCVTSS2SDZrr_Int:
5761   case X86::VCVTSS2SDZrrb_Int:
5762   case X86::VCVTSS2SDZrm:
5763   case X86::VCVTSS2SDZrm_Int:
5764   case X86::VGETEXPSDZr:
5765   case X86::VGETEXPSDZrb:
5766   case X86::VGETEXPSDZm:
5767   case X86::VGETEXPSSZr:
5768   case X86::VGETEXPSSZrb:
5769   case X86::VGETEXPSSZm:
5770   case X86::VGETMANTSDZrri:
5771   case X86::VGETMANTSDZrrib:
5772   case X86::VGETMANTSDZrmi:
5773   case X86::VGETMANTSSZrri:
5774   case X86::VGETMANTSSZrrib:
5775   case X86::VGETMANTSSZrmi:
5776   case X86::VRNDSCALESDZr:
5777   case X86::VRNDSCALESDZr_Int:
5778   case X86::VRNDSCALESDZrb_Int:
5779   case X86::VRNDSCALESDZm:
5780   case X86::VRNDSCALESDZm_Int:
5781   case X86::VRNDSCALESSZr:
5782   case X86::VRNDSCALESSZr_Int:
5783   case X86::VRNDSCALESSZrb_Int:
5784   case X86::VRNDSCALESSZm:
5785   case X86::VRNDSCALESSZm_Int:
5786   case X86::VRCP14SDZrr:
5787   case X86::VRCP14SDZrm:
5788   case X86::VRCP14SSZrr:
5789   case X86::VRCP14SSZrm:
5790   case X86::VRCPSHZrr:
5791   case X86::VRCPSHZrm:
5792   case X86::VRSQRTSHZrr:
5793   case X86::VRSQRTSHZrm:
5794   case X86::VREDUCESHZrmi:
5795   case X86::VREDUCESHZrri:
5796   case X86::VREDUCESHZrrib:
5797   case X86::VGETEXPSHZr:
5798   case X86::VGETEXPSHZrb:
5799   case X86::VGETEXPSHZm:
5800   case X86::VGETMANTSHZrri:
5801   case X86::VGETMANTSHZrrib:
5802   case X86::VGETMANTSHZrmi:
5803   case X86::VRNDSCALESHZr:
5804   case X86::VRNDSCALESHZr_Int:
5805   case X86::VRNDSCALESHZrb_Int:
5806   case X86::VRNDSCALESHZm:
5807   case X86::VRNDSCALESHZm_Int:
5808   case X86::VSQRTSHZr:
5809   case X86::VSQRTSHZr_Int:
5810   case X86::VSQRTSHZrb_Int:
5811   case X86::VSQRTSHZm:
5812   case X86::VSQRTSHZm_Int:
5813   case X86::VRCP28SDZr:
5814   case X86::VRCP28SDZrb:
5815   case X86::VRCP28SDZm:
5816   case X86::VRCP28SSZr:
5817   case X86::VRCP28SSZrb:
5818   case X86::VRCP28SSZm:
5819   case X86::VREDUCESSZrmi:
5820   case X86::VREDUCESSZrri:
5821   case X86::VREDUCESSZrrib:
5822   case X86::VRSQRT14SDZrr:
5823   case X86::VRSQRT14SDZrm:
5824   case X86::VRSQRT14SSZrr:
5825   case X86::VRSQRT14SSZrm:
5826   case X86::VRSQRT28SDZr:
5827   case X86::VRSQRT28SDZrb:
5828   case X86::VRSQRT28SDZm:
5829   case X86::VRSQRT28SSZr:
5830   case X86::VRSQRT28SSZrb:
5831   case X86::VRSQRT28SSZm:
5832   case X86::VSQRTSSZr:
5833   case X86::VSQRTSSZr_Int:
5834   case X86::VSQRTSSZrb_Int:
5835   case X86::VSQRTSSZm:
5836   case X86::VSQRTSSZm_Int:
5837   case X86::VSQRTSDZr:
5838   case X86::VSQRTSDZr_Int:
5839   case X86::VSQRTSDZrb_Int:
5840   case X86::VSQRTSDZm:
5841   case X86::VSQRTSDZm_Int:
5842   case X86::VCVTSD2SHZrr:
5843   case X86::VCVTSD2SHZrr_Int:
5844   case X86::VCVTSD2SHZrrb_Int:
5845   case X86::VCVTSD2SHZrm:
5846   case X86::VCVTSD2SHZrm_Int:
5847   case X86::VCVTSS2SHZrr:
5848   case X86::VCVTSS2SHZrr_Int:
5849   case X86::VCVTSS2SHZrrb_Int:
5850   case X86::VCVTSS2SHZrm:
5851   case X86::VCVTSS2SHZrm_Int:
5852   case X86::VCVTSH2SDZrr:
5853   case X86::VCVTSH2SDZrr_Int:
5854   case X86::VCVTSH2SDZrrb_Int:
5855   case X86::VCVTSH2SDZrm:
5856   case X86::VCVTSH2SDZrm_Int:
5857   case X86::VCVTSH2SSZrr:
5858   case X86::VCVTSH2SSZrr_Int:
5859   case X86::VCVTSH2SSZrrb_Int:
5860   case X86::VCVTSH2SSZrm:
5861   case X86::VCVTSH2SSZrm_Int:
5862     return OpNum == 1;
5863   case X86::VMOVSSZrrk:
5864   case X86::VMOVSDZrrk:
5865     return OpNum == 3 && !ForLoadFold;
5866   case X86::VMOVSSZrrkz:
5867   case X86::VMOVSDZrrkz:
5868     return OpNum == 2 && !ForLoadFold;
5869   }
5870 
5871   return false;
5872 }
5873 
5874 /// Inform the BreakFalseDeps pass how many idle instructions we would like
5875 /// before certain undef register reads.
5876 ///
5877 /// This catches the VCVTSI2SD family of instructions:
5878 ///
5879 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
5880 ///
5881 /// We should to be careful *not* to catch VXOR idioms which are presumably
5882 /// handled specially in the pipeline:
5883 ///
5884 /// vxorps undef %xmm1, undef %xmm1, %xmm1
5885 ///
5886 /// Like getPartialRegUpdateClearance, this makes a strong assumption that the
5887 /// high bits that are passed-through are not live.
5888 unsigned
5889 X86InstrInfo::getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
5890                                    const TargetRegisterInfo *TRI) const {
5891   const MachineOperand &MO = MI.getOperand(OpNum);
5892   if (MO.getReg().isPhysical() && hasUndefRegUpdate(MI.getOpcode(), OpNum))
5893     return UndefRegClearance;
5894 
5895   return 0;
5896 }
5897 
5898 void X86InstrInfo::breakPartialRegDependency(
5899     MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
5900   Register Reg = MI.getOperand(OpNum).getReg();
5901   // If MI kills this register, the false dependence is already broken.
5902   if (MI.killsRegister(Reg, TRI))
5903     return;
5904 
5905   if (X86::VR128RegClass.contains(Reg)) {
5906     // These instructions are all floating point domain, so xorps is the best
5907     // choice.
5908     unsigned Opc = Subtarget.hasAVX() ? X86::VXORPSrr : X86::XORPSrr;
5909     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(Opc), Reg)
5910         .addReg(Reg, RegState::Undef)
5911         .addReg(Reg, RegState::Undef);
5912     MI.addRegisterKilled(Reg, TRI, true);
5913   } else if (X86::VR256RegClass.contains(Reg)) {
5914     // Use vxorps to clear the full ymm register.
5915     // It wants to read and write the xmm sub-register.
5916     Register XReg = TRI->getSubReg(Reg, X86::sub_xmm);
5917     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::VXORPSrr), XReg)
5918         .addReg(XReg, RegState::Undef)
5919         .addReg(XReg, RegState::Undef)
5920         .addReg(Reg, RegState::ImplicitDefine);
5921     MI.addRegisterKilled(Reg, TRI, true);
5922   } else if (X86::VR128XRegClass.contains(Reg)) {
5923     // Only handle VLX targets.
5924     if (!Subtarget.hasVLX())
5925       return;
5926     // Since vxorps requires AVX512DQ, vpxord should be the best choice.
5927     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::VPXORDZ128rr), Reg)
5928         .addReg(Reg, RegState::Undef)
5929         .addReg(Reg, RegState::Undef);
5930     MI.addRegisterKilled(Reg, TRI, true);
5931   } else if (X86::VR256XRegClass.contains(Reg) ||
5932              X86::VR512RegClass.contains(Reg)) {
5933     // Only handle VLX targets.
5934     if (!Subtarget.hasVLX())
5935       return;
5936     // Use vpxord to clear the full ymm/zmm register.
5937     // It wants to read and write the xmm sub-register.
5938     Register XReg = TRI->getSubReg(Reg, X86::sub_xmm);
5939     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::VPXORDZ128rr), XReg)
5940         .addReg(XReg, RegState::Undef)
5941         .addReg(XReg, RegState::Undef)
5942         .addReg(Reg, RegState::ImplicitDefine);
5943     MI.addRegisterKilled(Reg, TRI, true);
5944   } else if (X86::GR64RegClass.contains(Reg)) {
5945     // Using XOR32rr because it has shorter encoding and zeros up the upper bits
5946     // as well.
5947     Register XReg = TRI->getSubReg(Reg, X86::sub_32bit);
5948     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), XReg)
5949         .addReg(XReg, RegState::Undef)
5950         .addReg(XReg, RegState::Undef)
5951         .addReg(Reg, RegState::ImplicitDefine);
5952     MI.addRegisterKilled(Reg, TRI, true);
5953   } else if (X86::GR32RegClass.contains(Reg)) {
5954     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), Reg)
5955         .addReg(Reg, RegState::Undef)
5956         .addReg(Reg, RegState::Undef);
5957     MI.addRegisterKilled(Reg, TRI, true);
5958   }
5959 }
5960 
5961 static void addOperands(MachineInstrBuilder &MIB, ArrayRef<MachineOperand> MOs,
5962                         int PtrOffset = 0) {
5963   unsigned NumAddrOps = MOs.size();
5964 
5965   if (NumAddrOps < 4) {
5966     // FrameIndex only - add an immediate offset (whether its zero or not).
5967     for (unsigned i = 0; i != NumAddrOps; ++i)
5968       MIB.add(MOs[i]);
5969     addOffset(MIB, PtrOffset);
5970   } else {
5971     // General Memory Addressing - we need to add any offset to an existing
5972     // offset.
5973     assert(MOs.size() == 5 && "Unexpected memory operand list length");
5974     for (unsigned i = 0; i != NumAddrOps; ++i) {
5975       const MachineOperand &MO = MOs[i];
5976       if (i == 3 && PtrOffset != 0) {
5977         MIB.addDisp(MO, PtrOffset);
5978       } else {
5979         MIB.add(MO);
5980       }
5981     }
5982   }
5983 }
5984 
5985 static void updateOperandRegConstraints(MachineFunction &MF,
5986                                         MachineInstr &NewMI,
5987                                         const TargetInstrInfo &TII) {
5988   MachineRegisterInfo &MRI = MF.getRegInfo();
5989   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
5990 
5991   for (int Idx : llvm::seq<int>(0, NewMI.getNumOperands())) {
5992     MachineOperand &MO = NewMI.getOperand(Idx);
5993     // We only need to update constraints on virtual register operands.
5994     if (!MO.isReg())
5995       continue;
5996     Register Reg = MO.getReg();
5997     if (!Reg.isVirtual())
5998       continue;
5999 
6000     auto *NewRC = MRI.constrainRegClass(
6001         Reg, TII.getRegClass(NewMI.getDesc(), Idx, &TRI, MF));
6002     if (!NewRC) {
6003       LLVM_DEBUG(
6004           dbgs() << "WARNING: Unable to update register constraint for operand "
6005                  << Idx << " of instruction:\n";
6006           NewMI.dump(); dbgs() << "\n");
6007     }
6008   }
6009 }
6010 
6011 static MachineInstr *FuseTwoAddrInst(MachineFunction &MF, unsigned Opcode,
6012                                      ArrayRef<MachineOperand> MOs,
6013                                      MachineBasicBlock::iterator InsertPt,
6014                                      MachineInstr &MI,
6015                                      const TargetInstrInfo &TII) {
6016   // Create the base instruction with the memory operand as the first part.
6017   // Omit the implicit operands, something BuildMI can't do.
6018   MachineInstr *NewMI =
6019       MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
6020   MachineInstrBuilder MIB(MF, NewMI);
6021   addOperands(MIB, MOs);
6022 
6023   // Loop over the rest of the ri operands, converting them over.
6024   unsigned NumOps = MI.getDesc().getNumOperands() - 2;
6025   for (unsigned i = 0; i != NumOps; ++i) {
6026     MachineOperand &MO = MI.getOperand(i + 2);
6027     MIB.add(MO);
6028   }
6029   for (const MachineOperand &MO : llvm::drop_begin(MI.operands(), NumOps + 2))
6030     MIB.add(MO);
6031 
6032   updateOperandRegConstraints(MF, *NewMI, TII);
6033 
6034   MachineBasicBlock *MBB = InsertPt->getParent();
6035   MBB->insert(InsertPt, NewMI);
6036 
6037   return MIB;
6038 }
6039 
6040 static MachineInstr *FuseInst(MachineFunction &MF, unsigned Opcode,
6041                               unsigned OpNo, ArrayRef<MachineOperand> MOs,
6042                               MachineBasicBlock::iterator InsertPt,
6043                               MachineInstr &MI, const TargetInstrInfo &TII,
6044                               int PtrOffset = 0) {
6045   // Omit the implicit operands, something BuildMI can't do.
6046   MachineInstr *NewMI =
6047       MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
6048   MachineInstrBuilder MIB(MF, NewMI);
6049 
6050   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
6051     MachineOperand &MO = MI.getOperand(i);
6052     if (i == OpNo) {
6053       assert(MO.isReg() && "Expected to fold into reg operand!");
6054       addOperands(MIB, MOs, PtrOffset);
6055     } else {
6056       MIB.add(MO);
6057     }
6058   }
6059 
6060   updateOperandRegConstraints(MF, *NewMI, TII);
6061 
6062   // Copy the NoFPExcept flag from the instruction we're fusing.
6063   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
6064     NewMI->setFlag(MachineInstr::MIFlag::NoFPExcept);
6065 
6066   MachineBasicBlock *MBB = InsertPt->getParent();
6067   MBB->insert(InsertPt, NewMI);
6068 
6069   return MIB;
6070 }
6071 
6072 static MachineInstr *MakeM0Inst(const TargetInstrInfo &TII, unsigned Opcode,
6073                                 ArrayRef<MachineOperand> MOs,
6074                                 MachineBasicBlock::iterator InsertPt,
6075                                 MachineInstr &MI) {
6076   MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
6077                                     MI.getDebugLoc(), TII.get(Opcode));
6078   addOperands(MIB, MOs);
6079   return MIB.addImm(0);
6080 }
6081 
6082 MachineInstr *X86InstrInfo::foldMemoryOperandCustom(
6083     MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
6084     ArrayRef<MachineOperand> MOs, MachineBasicBlock::iterator InsertPt,
6085     unsigned Size, Align Alignment) const {
6086   switch (MI.getOpcode()) {
6087   case X86::INSERTPSrr:
6088   case X86::VINSERTPSrr:
6089   case X86::VINSERTPSZrr:
6090     // Attempt to convert the load of inserted vector into a fold load
6091     // of a single float.
6092     if (OpNum == 2) {
6093       unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm();
6094       unsigned ZMask = Imm & 15;
6095       unsigned DstIdx = (Imm >> 4) & 3;
6096       unsigned SrcIdx = (Imm >> 6) & 3;
6097 
6098       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6099       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
6100       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
6101       if ((Size == 0 || Size >= 16) && RCSize >= 16 && Alignment >= Align(4)) {
6102         int PtrOffset = SrcIdx * 4;
6103         unsigned NewImm = (DstIdx << 4) | ZMask;
6104         unsigned NewOpCode =
6105             (MI.getOpcode() == X86::VINSERTPSZrr) ? X86::VINSERTPSZrm :
6106             (MI.getOpcode() == X86::VINSERTPSrr)  ? X86::VINSERTPSrm  :
6107                                                     X86::INSERTPSrm;
6108         MachineInstr *NewMI =
6109             FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, PtrOffset);
6110         NewMI->getOperand(NewMI->getNumOperands() - 1).setImm(NewImm);
6111         return NewMI;
6112       }
6113     }
6114     break;
6115   case X86::MOVHLPSrr:
6116   case X86::VMOVHLPSrr:
6117   case X86::VMOVHLPSZrr:
6118     // Move the upper 64-bits of the second operand to the lower 64-bits.
6119     // To fold the load, adjust the pointer to the upper and use (V)MOVLPS.
6120     // TODO: In most cases AVX doesn't have a 8-byte alignment requirement.
6121     if (OpNum == 2) {
6122       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6123       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
6124       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
6125       if ((Size == 0 || Size >= 16) && RCSize >= 16 && Alignment >= Align(8)) {
6126         unsigned NewOpCode =
6127             (MI.getOpcode() == X86::VMOVHLPSZrr) ? X86::VMOVLPSZ128rm :
6128             (MI.getOpcode() == X86::VMOVHLPSrr)  ? X86::VMOVLPSrm     :
6129                                                    X86::MOVLPSrm;
6130         MachineInstr *NewMI =
6131             FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, 8);
6132         return NewMI;
6133       }
6134     }
6135     break;
6136   case X86::UNPCKLPDrr:
6137     // If we won't be able to fold this to the memory form of UNPCKL, use
6138     // MOVHPD instead. Done as custom because we can't have this in the load
6139     // table twice.
6140     if (OpNum == 2) {
6141       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6142       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
6143       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
6144       if ((Size == 0 || Size >= 16) && RCSize >= 16 && Alignment < Align(16)) {
6145         MachineInstr *NewMI =
6146             FuseInst(MF, X86::MOVHPDrm, OpNum, MOs, InsertPt, MI, *this);
6147         return NewMI;
6148       }
6149     }
6150     break;
6151   }
6152 
6153   return nullptr;
6154 }
6155 
6156 static bool shouldPreventUndefRegUpdateMemFold(MachineFunction &MF,
6157                                                MachineInstr &MI) {
6158   if (!hasUndefRegUpdate(MI.getOpcode(), 1, /*ForLoadFold*/true) ||
6159       !MI.getOperand(1).isReg())
6160     return false;
6161 
6162   // The are two cases we need to handle depending on where in the pipeline
6163   // the folding attempt is being made.
6164   // -Register has the undef flag set.
6165   // -Register is produced by the IMPLICIT_DEF instruction.
6166 
6167   if (MI.getOperand(1).isUndef())
6168     return true;
6169 
6170   MachineRegisterInfo &RegInfo = MF.getRegInfo();
6171   MachineInstr *VRegDef = RegInfo.getUniqueVRegDef(MI.getOperand(1).getReg());
6172   return VRegDef && VRegDef->isImplicitDef();
6173 }
6174 
6175 MachineInstr *X86InstrInfo::foldMemoryOperandImpl(
6176     MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
6177     ArrayRef<MachineOperand> MOs, MachineBasicBlock::iterator InsertPt,
6178     unsigned Size, Align Alignment, bool AllowCommute) const {
6179   bool isSlowTwoMemOps = Subtarget.slowTwoMemOps();
6180   bool isTwoAddrFold = false;
6181 
6182   // For CPUs that favor the register form of a call or push,
6183   // do not fold loads into calls or pushes, unless optimizing for size
6184   // aggressively.
6185   if (isSlowTwoMemOps && !MF.getFunction().hasMinSize() &&
6186       (MI.getOpcode() == X86::CALL32r || MI.getOpcode() == X86::CALL64r ||
6187        MI.getOpcode() == X86::PUSH16r || MI.getOpcode() == X86::PUSH32r ||
6188        MI.getOpcode() == X86::PUSH64r))
6189     return nullptr;
6190 
6191   // Avoid partial and undef register update stalls unless optimizing for size.
6192   if (!MF.getFunction().hasOptSize() &&
6193       (hasPartialRegUpdate(MI.getOpcode(), Subtarget, /*ForLoadFold*/true) ||
6194        shouldPreventUndefRegUpdateMemFold(MF, MI)))
6195     return nullptr;
6196 
6197   unsigned NumOps = MI.getDesc().getNumOperands();
6198   bool isTwoAddr =
6199       NumOps > 1 && MI.getDesc().getOperandConstraint(1, MCOI::TIED_TO) != -1;
6200 
6201   // FIXME: AsmPrinter doesn't know how to handle
6202   // X86II::MO_GOT_ABSOLUTE_ADDRESS after folding.
6203   if (MI.getOpcode() == X86::ADD32ri &&
6204       MI.getOperand(2).getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS)
6205     return nullptr;
6206 
6207   // GOTTPOFF relocation loads can only be folded into add instructions.
6208   // FIXME: Need to exclude other relocations that only support specific
6209   // instructions.
6210   if (MOs.size() == X86::AddrNumOperands &&
6211       MOs[X86::AddrDisp].getTargetFlags() == X86II::MO_GOTTPOFF &&
6212       MI.getOpcode() != X86::ADD64rr)
6213     return nullptr;
6214 
6215   // Don't fold loads into indirect calls that need a KCFI check as we'll
6216   // have to unfold these in X86TargetLowering::EmitKCFICheck anyway.
6217   if (MI.isCall() && MI.getCFIType())
6218     return nullptr;
6219 
6220   MachineInstr *NewMI = nullptr;
6221 
6222   // Attempt to fold any custom cases we have.
6223   if (MachineInstr *CustomMI = foldMemoryOperandCustom(
6224           MF, MI, OpNum, MOs, InsertPt, Size, Alignment))
6225     return CustomMI;
6226 
6227   const X86MemoryFoldTableEntry *I = nullptr;
6228 
6229   // Folding a memory location into the two-address part of a two-address
6230   // instruction is different than folding it other places.  It requires
6231   // replacing the *two* registers with the memory location.
6232   if (isTwoAddr && NumOps >= 2 && OpNum < 2 && MI.getOperand(0).isReg() &&
6233       MI.getOperand(1).isReg() &&
6234       MI.getOperand(0).getReg() == MI.getOperand(1).getReg()) {
6235     I = lookupTwoAddrFoldTable(MI.getOpcode());
6236     isTwoAddrFold = true;
6237   } else {
6238     if (OpNum == 0) {
6239       if (MI.getOpcode() == X86::MOV32r0) {
6240         NewMI = MakeM0Inst(*this, X86::MOV32mi, MOs, InsertPt, MI);
6241         if (NewMI)
6242           return NewMI;
6243       }
6244     }
6245 
6246     I = lookupFoldTable(MI.getOpcode(), OpNum);
6247   }
6248 
6249   if (I != nullptr) {
6250     unsigned Opcode = I->DstOp;
6251     bool FoldedLoad =
6252         isTwoAddrFold || (OpNum == 0 && I->Flags & TB_FOLDED_LOAD) || OpNum > 0;
6253     bool FoldedStore =
6254         isTwoAddrFold || (OpNum == 0 && I->Flags & TB_FOLDED_STORE);
6255     if (Alignment < Align(1ULL << ((I->Flags & TB_ALIGN_MASK) >> TB_ALIGN_SHIFT)))
6256       return nullptr;
6257     bool NarrowToMOV32rm = false;
6258     if (Size) {
6259       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6260       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum,
6261                                                   &RI, MF);
6262       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
6263       // Check if it's safe to fold the load. If the size of the object is
6264       // narrower than the load width, then it's not.
6265       // FIXME: Allow scalar intrinsic instructions like ADDSSrm_Int.
6266       if (FoldedLoad && Size < RCSize) {
6267         // If this is a 64-bit load, but the spill slot is 32, then we can do
6268         // a 32-bit load which is implicitly zero-extended. This likely is
6269         // due to live interval analysis remat'ing a load from stack slot.
6270         if (Opcode != X86::MOV64rm || RCSize != 8 || Size != 4)
6271           return nullptr;
6272         if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
6273           return nullptr;
6274         Opcode = X86::MOV32rm;
6275         NarrowToMOV32rm = true;
6276       }
6277       // For stores, make sure the size of the object is equal to the size of
6278       // the store. If the object is larger, the extra bits would be garbage. If
6279       // the object is smaller we might overwrite another object or fault.
6280       if (FoldedStore && Size != RCSize)
6281         return nullptr;
6282     }
6283 
6284     if (isTwoAddrFold)
6285       NewMI = FuseTwoAddrInst(MF, Opcode, MOs, InsertPt, MI, *this);
6286     else
6287       NewMI = FuseInst(MF, Opcode, OpNum, MOs, InsertPt, MI, *this);
6288 
6289     if (NarrowToMOV32rm) {
6290       // If this is the special case where we use a MOV32rm to load a 32-bit
6291       // value and zero-extend the top bits. Change the destination register
6292       // to a 32-bit one.
6293       Register DstReg = NewMI->getOperand(0).getReg();
6294       if (DstReg.isPhysical())
6295         NewMI->getOperand(0).setReg(RI.getSubReg(DstReg, X86::sub_32bit));
6296       else
6297         NewMI->getOperand(0).setSubReg(X86::sub_32bit);
6298     }
6299     return NewMI;
6300   }
6301 
6302   // If the instruction and target operand are commutable, commute the
6303   // instruction and try again.
6304   if (AllowCommute) {
6305     unsigned CommuteOpIdx1 = OpNum, CommuteOpIdx2 = CommuteAnyOperandIndex;
6306     if (findCommutedOpIndices(MI, CommuteOpIdx1, CommuteOpIdx2)) {
6307       bool HasDef = MI.getDesc().getNumDefs();
6308       Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register();
6309       Register Reg1 = MI.getOperand(CommuteOpIdx1).getReg();
6310       Register Reg2 = MI.getOperand(CommuteOpIdx2).getReg();
6311       bool Tied1 =
6312           0 == MI.getDesc().getOperandConstraint(CommuteOpIdx1, MCOI::TIED_TO);
6313       bool Tied2 =
6314           0 == MI.getDesc().getOperandConstraint(CommuteOpIdx2, MCOI::TIED_TO);
6315 
6316       // If either of the commutable operands are tied to the destination
6317       // then we can not commute + fold.
6318       if ((HasDef && Reg0 == Reg1 && Tied1) ||
6319           (HasDef && Reg0 == Reg2 && Tied2))
6320         return nullptr;
6321 
6322       MachineInstr *CommutedMI =
6323           commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
6324       if (!CommutedMI) {
6325         // Unable to commute.
6326         return nullptr;
6327       }
6328       if (CommutedMI != &MI) {
6329         // New instruction. We can't fold from this.
6330         CommutedMI->eraseFromParent();
6331         return nullptr;
6332       }
6333 
6334       // Attempt to fold with the commuted version of the instruction.
6335       NewMI = foldMemoryOperandImpl(MF, MI, CommuteOpIdx2, MOs, InsertPt, Size,
6336                                     Alignment, /*AllowCommute=*/false);
6337       if (NewMI)
6338         return NewMI;
6339 
6340       // Folding failed again - undo the commute before returning.
6341       MachineInstr *UncommutedMI =
6342           commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
6343       if (!UncommutedMI) {
6344         // Unable to commute.
6345         return nullptr;
6346       }
6347       if (UncommutedMI != &MI) {
6348         // New instruction. It doesn't need to be kept.
6349         UncommutedMI->eraseFromParent();
6350         return nullptr;
6351       }
6352 
6353       // Return here to prevent duplicate fuse failure report.
6354       return nullptr;
6355     }
6356   }
6357 
6358   // No fusion
6359   if (PrintFailedFusing && !MI.isCopy())
6360     dbgs() << "We failed to fuse operand " << OpNum << " in " << MI;
6361   return nullptr;
6362 }
6363 
6364 MachineInstr *
6365 X86InstrInfo::foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
6366                                     ArrayRef<unsigned> Ops,
6367                                     MachineBasicBlock::iterator InsertPt,
6368                                     int FrameIndex, LiveIntervals *LIS,
6369                                     VirtRegMap *VRM) const {
6370   // Check switch flag
6371   if (NoFusing)
6372     return nullptr;
6373 
6374   // Avoid partial and undef register update stalls unless optimizing for size.
6375   if (!MF.getFunction().hasOptSize() &&
6376       (hasPartialRegUpdate(MI.getOpcode(), Subtarget, /*ForLoadFold*/true) ||
6377        shouldPreventUndefRegUpdateMemFold(MF, MI)))
6378     return nullptr;
6379 
6380   // Don't fold subreg spills, or reloads that use a high subreg.
6381   for (auto Op : Ops) {
6382     MachineOperand &MO = MI.getOperand(Op);
6383     auto SubReg = MO.getSubReg();
6384     if (SubReg && (MO.isDef() || SubReg == X86::sub_8bit_hi))
6385       return nullptr;
6386   }
6387 
6388   const MachineFrameInfo &MFI = MF.getFrameInfo();
6389   unsigned Size = MFI.getObjectSize(FrameIndex);
6390   Align Alignment = MFI.getObjectAlign(FrameIndex);
6391   // If the function stack isn't realigned we don't want to fold instructions
6392   // that need increased alignment.
6393   if (!RI.hasStackRealignment(MF))
6394     Alignment =
6395         std::min(Alignment, Subtarget.getFrameLowering()->getStackAlign());
6396   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
6397     unsigned NewOpc = 0;
6398     unsigned RCSize = 0;
6399     switch (MI.getOpcode()) {
6400     default: return nullptr;
6401     case X86::TEST8rr:  NewOpc = X86::CMP8ri; RCSize = 1; break;
6402     case X86::TEST16rr: NewOpc = X86::CMP16ri; RCSize = 2; break;
6403     case X86::TEST32rr: NewOpc = X86::CMP32ri; RCSize = 4; break;
6404     case X86::TEST64rr: NewOpc = X86::CMP64ri32; RCSize = 8; break;
6405     }
6406     // Check if it's safe to fold the load. If the size of the object is
6407     // narrower than the load width, then it's not.
6408     if (Size < RCSize)
6409       return nullptr;
6410     // Change to CMPXXri r, 0 first.
6411     MI.setDesc(get(NewOpc));
6412     MI.getOperand(1).ChangeToImmediate(0);
6413   } else if (Ops.size() != 1)
6414     return nullptr;
6415 
6416   return foldMemoryOperandImpl(MF, MI, Ops[0],
6417                                MachineOperand::CreateFI(FrameIndex), InsertPt,
6418                                Size, Alignment, /*AllowCommute=*/true);
6419 }
6420 
6421 /// Check if \p LoadMI is a partial register load that we can't fold into \p MI
6422 /// because the latter uses contents that wouldn't be defined in the folded
6423 /// version.  For instance, this transformation isn't legal:
6424 ///   movss (%rdi), %xmm0
6425 ///   addps %xmm0, %xmm0
6426 /// ->
6427 ///   addps (%rdi), %xmm0
6428 ///
6429 /// But this one is:
6430 ///   movss (%rdi), %xmm0
6431 ///   addss %xmm0, %xmm0
6432 /// ->
6433 ///   addss (%rdi), %xmm0
6434 ///
6435 static bool isNonFoldablePartialRegisterLoad(const MachineInstr &LoadMI,
6436                                              const MachineInstr &UserMI,
6437                                              const MachineFunction &MF) {
6438   unsigned Opc = LoadMI.getOpcode();
6439   unsigned UserOpc = UserMI.getOpcode();
6440   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6441   const TargetRegisterClass *RC =
6442       MF.getRegInfo().getRegClass(LoadMI.getOperand(0).getReg());
6443   unsigned RegSize = TRI.getRegSizeInBits(*RC);
6444 
6445   if ((Opc == X86::MOVSSrm || Opc == X86::VMOVSSrm || Opc == X86::VMOVSSZrm ||
6446        Opc == X86::MOVSSrm_alt || Opc == X86::VMOVSSrm_alt ||
6447        Opc == X86::VMOVSSZrm_alt) &&
6448       RegSize > 32) {
6449     // These instructions only load 32 bits, we can't fold them if the
6450     // destination register is wider than 32 bits (4 bytes), and its user
6451     // instruction isn't scalar (SS).
6452     switch (UserOpc) {
6453     case X86::CVTSS2SDrr_Int:
6454     case X86::VCVTSS2SDrr_Int:
6455     case X86::VCVTSS2SDZrr_Int:
6456     case X86::VCVTSS2SDZrr_Intk:
6457     case X86::VCVTSS2SDZrr_Intkz:
6458     case X86::CVTSS2SIrr_Int:     case X86::CVTSS2SI64rr_Int:
6459     case X86::VCVTSS2SIrr_Int:    case X86::VCVTSS2SI64rr_Int:
6460     case X86::VCVTSS2SIZrr_Int:   case X86::VCVTSS2SI64Zrr_Int:
6461     case X86::CVTTSS2SIrr_Int:    case X86::CVTTSS2SI64rr_Int:
6462     case X86::VCVTTSS2SIrr_Int:   case X86::VCVTTSS2SI64rr_Int:
6463     case X86::VCVTTSS2SIZrr_Int:  case X86::VCVTTSS2SI64Zrr_Int:
6464     case X86::VCVTSS2USIZrr_Int:  case X86::VCVTSS2USI64Zrr_Int:
6465     case X86::VCVTTSS2USIZrr_Int: case X86::VCVTTSS2USI64Zrr_Int:
6466     case X86::RCPSSr_Int:   case X86::VRCPSSr_Int:
6467     case X86::RSQRTSSr_Int: case X86::VRSQRTSSr_Int:
6468     case X86::ROUNDSSr_Int: case X86::VROUNDSSr_Int:
6469     case X86::COMISSrr_Int: case X86::VCOMISSrr_Int: case X86::VCOMISSZrr_Int:
6470     case X86::UCOMISSrr_Int:case X86::VUCOMISSrr_Int:case X86::VUCOMISSZrr_Int:
6471     case X86::ADDSSrr_Int: case X86::VADDSSrr_Int: case X86::VADDSSZrr_Int:
6472     case X86::CMPSSrr_Int: case X86::VCMPSSrr_Int: case X86::VCMPSSZrr_Int:
6473     case X86::DIVSSrr_Int: case X86::VDIVSSrr_Int: case X86::VDIVSSZrr_Int:
6474     case X86::MAXSSrr_Int: case X86::VMAXSSrr_Int: case X86::VMAXSSZrr_Int:
6475     case X86::MINSSrr_Int: case X86::VMINSSrr_Int: case X86::VMINSSZrr_Int:
6476     case X86::MULSSrr_Int: case X86::VMULSSrr_Int: case X86::VMULSSZrr_Int:
6477     case X86::SQRTSSr_Int: case X86::VSQRTSSr_Int: case X86::VSQRTSSZr_Int:
6478     case X86::SUBSSrr_Int: case X86::VSUBSSrr_Int: case X86::VSUBSSZrr_Int:
6479     case X86::VADDSSZrr_Intk: case X86::VADDSSZrr_Intkz:
6480     case X86::VCMPSSZrr_Intk:
6481     case X86::VDIVSSZrr_Intk: case X86::VDIVSSZrr_Intkz:
6482     case X86::VMAXSSZrr_Intk: case X86::VMAXSSZrr_Intkz:
6483     case X86::VMINSSZrr_Intk: case X86::VMINSSZrr_Intkz:
6484     case X86::VMULSSZrr_Intk: case X86::VMULSSZrr_Intkz:
6485     case X86::VSQRTSSZr_Intk: case X86::VSQRTSSZr_Intkz:
6486     case X86::VSUBSSZrr_Intk: case X86::VSUBSSZrr_Intkz:
6487     case X86::VFMADDSS4rr_Int:   case X86::VFNMADDSS4rr_Int:
6488     case X86::VFMSUBSS4rr_Int:   case X86::VFNMSUBSS4rr_Int:
6489     case X86::VFMADD132SSr_Int:  case X86::VFNMADD132SSr_Int:
6490     case X86::VFMADD213SSr_Int:  case X86::VFNMADD213SSr_Int:
6491     case X86::VFMADD231SSr_Int:  case X86::VFNMADD231SSr_Int:
6492     case X86::VFMSUB132SSr_Int:  case X86::VFNMSUB132SSr_Int:
6493     case X86::VFMSUB213SSr_Int:  case X86::VFNMSUB213SSr_Int:
6494     case X86::VFMSUB231SSr_Int:  case X86::VFNMSUB231SSr_Int:
6495     case X86::VFMADD132SSZr_Int: case X86::VFNMADD132SSZr_Int:
6496     case X86::VFMADD213SSZr_Int: case X86::VFNMADD213SSZr_Int:
6497     case X86::VFMADD231SSZr_Int: case X86::VFNMADD231SSZr_Int:
6498     case X86::VFMSUB132SSZr_Int: case X86::VFNMSUB132SSZr_Int:
6499     case X86::VFMSUB213SSZr_Int: case X86::VFNMSUB213SSZr_Int:
6500     case X86::VFMSUB231SSZr_Int: case X86::VFNMSUB231SSZr_Int:
6501     case X86::VFMADD132SSZr_Intk: case X86::VFNMADD132SSZr_Intk:
6502     case X86::VFMADD213SSZr_Intk: case X86::VFNMADD213SSZr_Intk:
6503     case X86::VFMADD231SSZr_Intk: case X86::VFNMADD231SSZr_Intk:
6504     case X86::VFMSUB132SSZr_Intk: case X86::VFNMSUB132SSZr_Intk:
6505     case X86::VFMSUB213SSZr_Intk: case X86::VFNMSUB213SSZr_Intk:
6506     case X86::VFMSUB231SSZr_Intk: case X86::VFNMSUB231SSZr_Intk:
6507     case X86::VFMADD132SSZr_Intkz: case X86::VFNMADD132SSZr_Intkz:
6508     case X86::VFMADD213SSZr_Intkz: case X86::VFNMADD213SSZr_Intkz:
6509     case X86::VFMADD231SSZr_Intkz: case X86::VFNMADD231SSZr_Intkz:
6510     case X86::VFMSUB132SSZr_Intkz: case X86::VFNMSUB132SSZr_Intkz:
6511     case X86::VFMSUB213SSZr_Intkz: case X86::VFNMSUB213SSZr_Intkz:
6512     case X86::VFMSUB231SSZr_Intkz: case X86::VFNMSUB231SSZr_Intkz:
6513     case X86::VFIXUPIMMSSZrri:
6514     case X86::VFIXUPIMMSSZrrik:
6515     case X86::VFIXUPIMMSSZrrikz:
6516     case X86::VFPCLASSSSZrr:
6517     case X86::VFPCLASSSSZrrk:
6518     case X86::VGETEXPSSZr:
6519     case X86::VGETEXPSSZrk:
6520     case X86::VGETEXPSSZrkz:
6521     case X86::VGETMANTSSZrri:
6522     case X86::VGETMANTSSZrrik:
6523     case X86::VGETMANTSSZrrikz:
6524     case X86::VRANGESSZrri:
6525     case X86::VRANGESSZrrik:
6526     case X86::VRANGESSZrrikz:
6527     case X86::VRCP14SSZrr:
6528     case X86::VRCP14SSZrrk:
6529     case X86::VRCP14SSZrrkz:
6530     case X86::VRCP28SSZr:
6531     case X86::VRCP28SSZrk:
6532     case X86::VRCP28SSZrkz:
6533     case X86::VREDUCESSZrri:
6534     case X86::VREDUCESSZrrik:
6535     case X86::VREDUCESSZrrikz:
6536     case X86::VRNDSCALESSZr_Int:
6537     case X86::VRNDSCALESSZr_Intk:
6538     case X86::VRNDSCALESSZr_Intkz:
6539     case X86::VRSQRT14SSZrr:
6540     case X86::VRSQRT14SSZrrk:
6541     case X86::VRSQRT14SSZrrkz:
6542     case X86::VRSQRT28SSZr:
6543     case X86::VRSQRT28SSZrk:
6544     case X86::VRSQRT28SSZrkz:
6545     case X86::VSCALEFSSZrr:
6546     case X86::VSCALEFSSZrrk:
6547     case X86::VSCALEFSSZrrkz:
6548       return false;
6549     default:
6550       return true;
6551     }
6552   }
6553 
6554   if ((Opc == X86::MOVSDrm || Opc == X86::VMOVSDrm || Opc == X86::VMOVSDZrm ||
6555        Opc == X86::MOVSDrm_alt || Opc == X86::VMOVSDrm_alt ||
6556        Opc == X86::VMOVSDZrm_alt) &&
6557       RegSize > 64) {
6558     // These instructions only load 64 bits, we can't fold them if the
6559     // destination register is wider than 64 bits (8 bytes), and its user
6560     // instruction isn't scalar (SD).
6561     switch (UserOpc) {
6562     case X86::CVTSD2SSrr_Int:
6563     case X86::VCVTSD2SSrr_Int:
6564     case X86::VCVTSD2SSZrr_Int:
6565     case X86::VCVTSD2SSZrr_Intk:
6566     case X86::VCVTSD2SSZrr_Intkz:
6567     case X86::CVTSD2SIrr_Int:     case X86::CVTSD2SI64rr_Int:
6568     case X86::VCVTSD2SIrr_Int:    case X86::VCVTSD2SI64rr_Int:
6569     case X86::VCVTSD2SIZrr_Int:   case X86::VCVTSD2SI64Zrr_Int:
6570     case X86::CVTTSD2SIrr_Int:    case X86::CVTTSD2SI64rr_Int:
6571     case X86::VCVTTSD2SIrr_Int:   case X86::VCVTTSD2SI64rr_Int:
6572     case X86::VCVTTSD2SIZrr_Int:  case X86::VCVTTSD2SI64Zrr_Int:
6573     case X86::VCVTSD2USIZrr_Int:  case X86::VCVTSD2USI64Zrr_Int:
6574     case X86::VCVTTSD2USIZrr_Int: case X86::VCVTTSD2USI64Zrr_Int:
6575     case X86::ROUNDSDr_Int: case X86::VROUNDSDr_Int:
6576     case X86::COMISDrr_Int: case X86::VCOMISDrr_Int: case X86::VCOMISDZrr_Int:
6577     case X86::UCOMISDrr_Int:case X86::VUCOMISDrr_Int:case X86::VUCOMISDZrr_Int:
6578     case X86::ADDSDrr_Int: case X86::VADDSDrr_Int: case X86::VADDSDZrr_Int:
6579     case X86::CMPSDrr_Int: case X86::VCMPSDrr_Int: case X86::VCMPSDZrr_Int:
6580     case X86::DIVSDrr_Int: case X86::VDIVSDrr_Int: case X86::VDIVSDZrr_Int:
6581     case X86::MAXSDrr_Int: case X86::VMAXSDrr_Int: case X86::VMAXSDZrr_Int:
6582     case X86::MINSDrr_Int: case X86::VMINSDrr_Int: case X86::VMINSDZrr_Int:
6583     case X86::MULSDrr_Int: case X86::VMULSDrr_Int: case X86::VMULSDZrr_Int:
6584     case X86::SQRTSDr_Int: case X86::VSQRTSDr_Int: case X86::VSQRTSDZr_Int:
6585     case X86::SUBSDrr_Int: case X86::VSUBSDrr_Int: case X86::VSUBSDZrr_Int:
6586     case X86::VADDSDZrr_Intk: case X86::VADDSDZrr_Intkz:
6587     case X86::VCMPSDZrr_Intk:
6588     case X86::VDIVSDZrr_Intk: case X86::VDIVSDZrr_Intkz:
6589     case X86::VMAXSDZrr_Intk: case X86::VMAXSDZrr_Intkz:
6590     case X86::VMINSDZrr_Intk: case X86::VMINSDZrr_Intkz:
6591     case X86::VMULSDZrr_Intk: case X86::VMULSDZrr_Intkz:
6592     case X86::VSQRTSDZr_Intk: case X86::VSQRTSDZr_Intkz:
6593     case X86::VSUBSDZrr_Intk: case X86::VSUBSDZrr_Intkz:
6594     case X86::VFMADDSD4rr_Int:   case X86::VFNMADDSD4rr_Int:
6595     case X86::VFMSUBSD4rr_Int:   case X86::VFNMSUBSD4rr_Int:
6596     case X86::VFMADD132SDr_Int:  case X86::VFNMADD132SDr_Int:
6597     case X86::VFMADD213SDr_Int:  case X86::VFNMADD213SDr_Int:
6598     case X86::VFMADD231SDr_Int:  case X86::VFNMADD231SDr_Int:
6599     case X86::VFMSUB132SDr_Int:  case X86::VFNMSUB132SDr_Int:
6600     case X86::VFMSUB213SDr_Int:  case X86::VFNMSUB213SDr_Int:
6601     case X86::VFMSUB231SDr_Int:  case X86::VFNMSUB231SDr_Int:
6602     case X86::VFMADD132SDZr_Int: case X86::VFNMADD132SDZr_Int:
6603     case X86::VFMADD213SDZr_Int: case X86::VFNMADD213SDZr_Int:
6604     case X86::VFMADD231SDZr_Int: case X86::VFNMADD231SDZr_Int:
6605     case X86::VFMSUB132SDZr_Int: case X86::VFNMSUB132SDZr_Int:
6606     case X86::VFMSUB213SDZr_Int: case X86::VFNMSUB213SDZr_Int:
6607     case X86::VFMSUB231SDZr_Int: case X86::VFNMSUB231SDZr_Int:
6608     case X86::VFMADD132SDZr_Intk: case X86::VFNMADD132SDZr_Intk:
6609     case X86::VFMADD213SDZr_Intk: case X86::VFNMADD213SDZr_Intk:
6610     case X86::VFMADD231SDZr_Intk: case X86::VFNMADD231SDZr_Intk:
6611     case X86::VFMSUB132SDZr_Intk: case X86::VFNMSUB132SDZr_Intk:
6612     case X86::VFMSUB213SDZr_Intk: case X86::VFNMSUB213SDZr_Intk:
6613     case X86::VFMSUB231SDZr_Intk: case X86::VFNMSUB231SDZr_Intk:
6614     case X86::VFMADD132SDZr_Intkz: case X86::VFNMADD132SDZr_Intkz:
6615     case X86::VFMADD213SDZr_Intkz: case X86::VFNMADD213SDZr_Intkz:
6616     case X86::VFMADD231SDZr_Intkz: case X86::VFNMADD231SDZr_Intkz:
6617     case X86::VFMSUB132SDZr_Intkz: case X86::VFNMSUB132SDZr_Intkz:
6618     case X86::VFMSUB213SDZr_Intkz: case X86::VFNMSUB213SDZr_Intkz:
6619     case X86::VFMSUB231SDZr_Intkz: case X86::VFNMSUB231SDZr_Intkz:
6620     case X86::VFIXUPIMMSDZrri:
6621     case X86::VFIXUPIMMSDZrrik:
6622     case X86::VFIXUPIMMSDZrrikz:
6623     case X86::VFPCLASSSDZrr:
6624     case X86::VFPCLASSSDZrrk:
6625     case X86::VGETEXPSDZr:
6626     case X86::VGETEXPSDZrk:
6627     case X86::VGETEXPSDZrkz:
6628     case X86::VGETMANTSDZrri:
6629     case X86::VGETMANTSDZrrik:
6630     case X86::VGETMANTSDZrrikz:
6631     case X86::VRANGESDZrri:
6632     case X86::VRANGESDZrrik:
6633     case X86::VRANGESDZrrikz:
6634     case X86::VRCP14SDZrr:
6635     case X86::VRCP14SDZrrk:
6636     case X86::VRCP14SDZrrkz:
6637     case X86::VRCP28SDZr:
6638     case X86::VRCP28SDZrk:
6639     case X86::VRCP28SDZrkz:
6640     case X86::VREDUCESDZrri:
6641     case X86::VREDUCESDZrrik:
6642     case X86::VREDUCESDZrrikz:
6643     case X86::VRNDSCALESDZr_Int:
6644     case X86::VRNDSCALESDZr_Intk:
6645     case X86::VRNDSCALESDZr_Intkz:
6646     case X86::VRSQRT14SDZrr:
6647     case X86::VRSQRT14SDZrrk:
6648     case X86::VRSQRT14SDZrrkz:
6649     case X86::VRSQRT28SDZr:
6650     case X86::VRSQRT28SDZrk:
6651     case X86::VRSQRT28SDZrkz:
6652     case X86::VSCALEFSDZrr:
6653     case X86::VSCALEFSDZrrk:
6654     case X86::VSCALEFSDZrrkz:
6655       return false;
6656     default:
6657       return true;
6658     }
6659   }
6660 
6661   if ((Opc == X86::VMOVSHZrm || Opc == X86::VMOVSHZrm_alt) && RegSize > 16) {
6662     // These instructions only load 16 bits, we can't fold them if the
6663     // destination register is wider than 16 bits (2 bytes), and its user
6664     // instruction isn't scalar (SH).
6665     switch (UserOpc) {
6666     case X86::VADDSHZrr_Int:
6667     case X86::VCMPSHZrr_Int:
6668     case X86::VDIVSHZrr_Int:
6669     case X86::VMAXSHZrr_Int:
6670     case X86::VMINSHZrr_Int:
6671     case X86::VMULSHZrr_Int:
6672     case X86::VSUBSHZrr_Int:
6673     case X86::VADDSHZrr_Intk: case X86::VADDSHZrr_Intkz:
6674     case X86::VCMPSHZrr_Intk:
6675     case X86::VDIVSHZrr_Intk: case X86::VDIVSHZrr_Intkz:
6676     case X86::VMAXSHZrr_Intk: case X86::VMAXSHZrr_Intkz:
6677     case X86::VMINSHZrr_Intk: case X86::VMINSHZrr_Intkz:
6678     case X86::VMULSHZrr_Intk: case X86::VMULSHZrr_Intkz:
6679     case X86::VSUBSHZrr_Intk: case X86::VSUBSHZrr_Intkz:
6680     case X86::VFMADD132SHZr_Int: case X86::VFNMADD132SHZr_Int:
6681     case X86::VFMADD213SHZr_Int: case X86::VFNMADD213SHZr_Int:
6682     case X86::VFMADD231SHZr_Int: case X86::VFNMADD231SHZr_Int:
6683     case X86::VFMSUB132SHZr_Int: case X86::VFNMSUB132SHZr_Int:
6684     case X86::VFMSUB213SHZr_Int: case X86::VFNMSUB213SHZr_Int:
6685     case X86::VFMSUB231SHZr_Int: case X86::VFNMSUB231SHZr_Int:
6686     case X86::VFMADD132SHZr_Intk: case X86::VFNMADD132SHZr_Intk:
6687     case X86::VFMADD213SHZr_Intk: case X86::VFNMADD213SHZr_Intk:
6688     case X86::VFMADD231SHZr_Intk: case X86::VFNMADD231SHZr_Intk:
6689     case X86::VFMSUB132SHZr_Intk: case X86::VFNMSUB132SHZr_Intk:
6690     case X86::VFMSUB213SHZr_Intk: case X86::VFNMSUB213SHZr_Intk:
6691     case X86::VFMSUB231SHZr_Intk: case X86::VFNMSUB231SHZr_Intk:
6692     case X86::VFMADD132SHZr_Intkz: case X86::VFNMADD132SHZr_Intkz:
6693     case X86::VFMADD213SHZr_Intkz: case X86::VFNMADD213SHZr_Intkz:
6694     case X86::VFMADD231SHZr_Intkz: case X86::VFNMADD231SHZr_Intkz:
6695     case X86::VFMSUB132SHZr_Intkz: case X86::VFNMSUB132SHZr_Intkz:
6696     case X86::VFMSUB213SHZr_Intkz: case X86::VFNMSUB213SHZr_Intkz:
6697     case X86::VFMSUB231SHZr_Intkz: case X86::VFNMSUB231SHZr_Intkz:
6698       return false;
6699     default:
6700       return true;
6701     }
6702   }
6703 
6704   return false;
6705 }
6706 
6707 MachineInstr *X86InstrInfo::foldMemoryOperandImpl(
6708     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
6709     MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
6710     LiveIntervals *LIS) const {
6711 
6712   // TODO: Support the case where LoadMI loads a wide register, but MI
6713   // only uses a subreg.
6714   for (auto Op : Ops) {
6715     if (MI.getOperand(Op).getSubReg())
6716       return nullptr;
6717   }
6718 
6719   // If loading from a FrameIndex, fold directly from the FrameIndex.
6720   unsigned NumOps = LoadMI.getDesc().getNumOperands();
6721   int FrameIndex;
6722   if (isLoadFromStackSlot(LoadMI, FrameIndex)) {
6723     if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
6724       return nullptr;
6725     return foldMemoryOperandImpl(MF, MI, Ops, InsertPt, FrameIndex, LIS);
6726   }
6727 
6728   // Check switch flag
6729   if (NoFusing) return nullptr;
6730 
6731   // Avoid partial and undef register update stalls unless optimizing for size.
6732   if (!MF.getFunction().hasOptSize() &&
6733       (hasPartialRegUpdate(MI.getOpcode(), Subtarget, /*ForLoadFold*/true) ||
6734        shouldPreventUndefRegUpdateMemFold(MF, MI)))
6735     return nullptr;
6736 
6737   // Determine the alignment of the load.
6738   Align Alignment;
6739   if (LoadMI.hasOneMemOperand())
6740     Alignment = (*LoadMI.memoperands_begin())->getAlign();
6741   else
6742     switch (LoadMI.getOpcode()) {
6743     case X86::AVX512_512_SET0:
6744     case X86::AVX512_512_SETALLONES:
6745       Alignment = Align(64);
6746       break;
6747     case X86::AVX2_SETALLONES:
6748     case X86::AVX1_SETALLONES:
6749     case X86::AVX_SET0:
6750     case X86::AVX512_256_SET0:
6751       Alignment = Align(32);
6752       break;
6753     case X86::V_SET0:
6754     case X86::V_SETALLONES:
6755     case X86::AVX512_128_SET0:
6756     case X86::FsFLD0F128:
6757     case X86::AVX512_FsFLD0F128:
6758       Alignment = Align(16);
6759       break;
6760     case X86::MMX_SET0:
6761     case X86::FsFLD0SD:
6762     case X86::AVX512_FsFLD0SD:
6763       Alignment = Align(8);
6764       break;
6765     case X86::FsFLD0SS:
6766     case X86::AVX512_FsFLD0SS:
6767       Alignment = Align(4);
6768       break;
6769     case X86::FsFLD0SH:
6770     case X86::AVX512_FsFLD0SH:
6771       Alignment = Align(2);
6772       break;
6773     default:
6774       return nullptr;
6775     }
6776   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
6777     unsigned NewOpc = 0;
6778     switch (MI.getOpcode()) {
6779     default: return nullptr;
6780     case X86::TEST8rr:  NewOpc = X86::CMP8ri; break;
6781     case X86::TEST16rr: NewOpc = X86::CMP16ri; break;
6782     case X86::TEST32rr: NewOpc = X86::CMP32ri; break;
6783     case X86::TEST64rr: NewOpc = X86::CMP64ri32; break;
6784     }
6785     // Change to CMPXXri r, 0 first.
6786     MI.setDesc(get(NewOpc));
6787     MI.getOperand(1).ChangeToImmediate(0);
6788   } else if (Ops.size() != 1)
6789     return nullptr;
6790 
6791   // Make sure the subregisters match.
6792   // Otherwise we risk changing the size of the load.
6793   if (LoadMI.getOperand(0).getSubReg() != MI.getOperand(Ops[0]).getSubReg())
6794     return nullptr;
6795 
6796   SmallVector<MachineOperand,X86::AddrNumOperands> MOs;
6797   switch (LoadMI.getOpcode()) {
6798   case X86::MMX_SET0:
6799   case X86::V_SET0:
6800   case X86::V_SETALLONES:
6801   case X86::AVX2_SETALLONES:
6802   case X86::AVX1_SETALLONES:
6803   case X86::AVX_SET0:
6804   case X86::AVX512_128_SET0:
6805   case X86::AVX512_256_SET0:
6806   case X86::AVX512_512_SET0:
6807   case X86::AVX512_512_SETALLONES:
6808   case X86::FsFLD0SH:
6809   case X86::AVX512_FsFLD0SH:
6810   case X86::FsFLD0SD:
6811   case X86::AVX512_FsFLD0SD:
6812   case X86::FsFLD0SS:
6813   case X86::AVX512_FsFLD0SS:
6814   case X86::FsFLD0F128:
6815   case X86::AVX512_FsFLD0F128: {
6816     // Folding a V_SET0 or V_SETALLONES as a load, to ease register pressure.
6817     // Create a constant-pool entry and operands to load from it.
6818 
6819     // Medium and large mode can't fold loads this way.
6820     if (MF.getTarget().getCodeModel() != CodeModel::Small &&
6821         MF.getTarget().getCodeModel() != CodeModel::Kernel)
6822       return nullptr;
6823 
6824     // x86-32 PIC requires a PIC base register for constant pools.
6825     unsigned PICBase = 0;
6826     // Since we're using Small or Kernel code model, we can always use
6827     // RIP-relative addressing for a smaller encoding.
6828     if (Subtarget.is64Bit()) {
6829       PICBase = X86::RIP;
6830     } else if (MF.getTarget().isPositionIndependent()) {
6831       // FIXME: PICBase = getGlobalBaseReg(&MF);
6832       // This doesn't work for several reasons.
6833       // 1. GlobalBaseReg may have been spilled.
6834       // 2. It may not be live at MI.
6835       return nullptr;
6836     }
6837 
6838     // Create a constant-pool entry.
6839     MachineConstantPool &MCP = *MF.getConstantPool();
6840     Type *Ty;
6841     unsigned Opc = LoadMI.getOpcode();
6842     if (Opc == X86::FsFLD0SS || Opc == X86::AVX512_FsFLD0SS)
6843       Ty = Type::getFloatTy(MF.getFunction().getContext());
6844     else if (Opc == X86::FsFLD0SD || Opc == X86::AVX512_FsFLD0SD)
6845       Ty = Type::getDoubleTy(MF.getFunction().getContext());
6846     else if (Opc == X86::FsFLD0F128 || Opc == X86::AVX512_FsFLD0F128)
6847       Ty = Type::getFP128Ty(MF.getFunction().getContext());
6848     else if (Opc == X86::FsFLD0SH || Opc == X86::AVX512_FsFLD0SH)
6849       Ty = Type::getHalfTy(MF.getFunction().getContext());
6850     else if (Opc == X86::AVX512_512_SET0 || Opc == X86::AVX512_512_SETALLONES)
6851       Ty = FixedVectorType::get(Type::getInt32Ty(MF.getFunction().getContext()),
6852                                 16);
6853     else if (Opc == X86::AVX2_SETALLONES || Opc == X86::AVX_SET0 ||
6854              Opc == X86::AVX512_256_SET0 || Opc == X86::AVX1_SETALLONES)
6855       Ty = FixedVectorType::get(Type::getInt32Ty(MF.getFunction().getContext()),
6856                                 8);
6857     else if (Opc == X86::MMX_SET0)
6858       Ty = FixedVectorType::get(Type::getInt32Ty(MF.getFunction().getContext()),
6859                                 2);
6860     else
6861       Ty = FixedVectorType::get(Type::getInt32Ty(MF.getFunction().getContext()),
6862                                 4);
6863 
6864     bool IsAllOnes = (Opc == X86::V_SETALLONES || Opc == X86::AVX2_SETALLONES ||
6865                       Opc == X86::AVX512_512_SETALLONES ||
6866                       Opc == X86::AVX1_SETALLONES);
6867     const Constant *C = IsAllOnes ? Constant::getAllOnesValue(Ty) :
6868                                     Constant::getNullValue(Ty);
6869     unsigned CPI = MCP.getConstantPoolIndex(C, Alignment);
6870 
6871     // Create operands to load from the constant pool entry.
6872     MOs.push_back(MachineOperand::CreateReg(PICBase, false));
6873     MOs.push_back(MachineOperand::CreateImm(1));
6874     MOs.push_back(MachineOperand::CreateReg(0, false));
6875     MOs.push_back(MachineOperand::CreateCPI(CPI, 0));
6876     MOs.push_back(MachineOperand::CreateReg(0, false));
6877     break;
6878   }
6879   default: {
6880     if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
6881       return nullptr;
6882 
6883     // Folding a normal load. Just copy the load's address operands.
6884     MOs.append(LoadMI.operands_begin() + NumOps - X86::AddrNumOperands,
6885                LoadMI.operands_begin() + NumOps);
6886     break;
6887   }
6888   }
6889   return foldMemoryOperandImpl(MF, MI, Ops[0], MOs, InsertPt,
6890                                /*Size=*/0, Alignment, /*AllowCommute=*/true);
6891 }
6892 
6893 static SmallVector<MachineMemOperand *, 2>
6894 extractLoadMMOs(ArrayRef<MachineMemOperand *> MMOs, MachineFunction &MF) {
6895   SmallVector<MachineMemOperand *, 2> LoadMMOs;
6896 
6897   for (MachineMemOperand *MMO : MMOs) {
6898     if (!MMO->isLoad())
6899       continue;
6900 
6901     if (!MMO->isStore()) {
6902       // Reuse the MMO.
6903       LoadMMOs.push_back(MMO);
6904     } else {
6905       // Clone the MMO and unset the store flag.
6906       LoadMMOs.push_back(MF.getMachineMemOperand(
6907           MMO, MMO->getFlags() & ~MachineMemOperand::MOStore));
6908     }
6909   }
6910 
6911   return LoadMMOs;
6912 }
6913 
6914 static SmallVector<MachineMemOperand *, 2>
6915 extractStoreMMOs(ArrayRef<MachineMemOperand *> MMOs, MachineFunction &MF) {
6916   SmallVector<MachineMemOperand *, 2> StoreMMOs;
6917 
6918   for (MachineMemOperand *MMO : MMOs) {
6919     if (!MMO->isStore())
6920       continue;
6921 
6922     if (!MMO->isLoad()) {
6923       // Reuse the MMO.
6924       StoreMMOs.push_back(MMO);
6925     } else {
6926       // Clone the MMO and unset the load flag.
6927       StoreMMOs.push_back(MF.getMachineMemOperand(
6928           MMO, MMO->getFlags() & ~MachineMemOperand::MOLoad));
6929     }
6930   }
6931 
6932   return StoreMMOs;
6933 }
6934 
6935 static unsigned getBroadcastOpcode(const X86MemoryFoldTableEntry *I,
6936                                    const TargetRegisterClass *RC,
6937                                    const X86Subtarget &STI) {
6938   assert(STI.hasAVX512() && "Expected at least AVX512!");
6939   unsigned SpillSize = STI.getRegisterInfo()->getSpillSize(*RC);
6940   assert((SpillSize == 64 || STI.hasVLX()) &&
6941          "Can't broadcast less than 64 bytes without AVX512VL!");
6942 
6943   switch (I->Flags & TB_BCAST_MASK) {
6944   default: llvm_unreachable("Unexpected broadcast type!");
6945   case TB_BCAST_D:
6946     switch (SpillSize) {
6947     default: llvm_unreachable("Unknown spill size");
6948     case 16: return X86::VPBROADCASTDZ128rm;
6949     case 32: return X86::VPBROADCASTDZ256rm;
6950     case 64: return X86::VPBROADCASTDZrm;
6951     }
6952     break;
6953   case TB_BCAST_Q:
6954     switch (SpillSize) {
6955     default: llvm_unreachable("Unknown spill size");
6956     case 16: return X86::VPBROADCASTQZ128rm;
6957     case 32: return X86::VPBROADCASTQZ256rm;
6958     case 64: return X86::VPBROADCASTQZrm;
6959     }
6960     break;
6961   case TB_BCAST_SS:
6962     switch (SpillSize) {
6963     default: llvm_unreachable("Unknown spill size");
6964     case 16: return X86::VBROADCASTSSZ128rm;
6965     case 32: return X86::VBROADCASTSSZ256rm;
6966     case 64: return X86::VBROADCASTSSZrm;
6967     }
6968     break;
6969   case TB_BCAST_SD:
6970     switch (SpillSize) {
6971     default: llvm_unreachable("Unknown spill size");
6972     case 16: return X86::VMOVDDUPZ128rm;
6973     case 32: return X86::VBROADCASTSDZ256rm;
6974     case 64: return X86::VBROADCASTSDZrm;
6975     }
6976     break;
6977   }
6978 }
6979 
6980 bool X86InstrInfo::unfoldMemoryOperand(
6981     MachineFunction &MF, MachineInstr &MI, unsigned Reg, bool UnfoldLoad,
6982     bool UnfoldStore, SmallVectorImpl<MachineInstr *> &NewMIs) const {
6983   const X86MemoryFoldTableEntry *I = lookupUnfoldTable(MI.getOpcode());
6984   if (I == nullptr)
6985     return false;
6986   unsigned Opc = I->DstOp;
6987   unsigned Index = I->Flags & TB_INDEX_MASK;
6988   bool FoldedLoad = I->Flags & TB_FOLDED_LOAD;
6989   bool FoldedStore = I->Flags & TB_FOLDED_STORE;
6990   bool FoldedBCast = I->Flags & TB_FOLDED_BCAST;
6991   if (UnfoldLoad && !FoldedLoad)
6992     return false;
6993   UnfoldLoad &= FoldedLoad;
6994   if (UnfoldStore && !FoldedStore)
6995     return false;
6996   UnfoldStore &= FoldedStore;
6997 
6998   const MCInstrDesc &MCID = get(Opc);
6999 
7000   const TargetRegisterClass *RC = getRegClass(MCID, Index, &RI, MF);
7001   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7002   // TODO: Check if 32-byte or greater accesses are slow too?
7003   if (!MI.hasOneMemOperand() && RC == &X86::VR128RegClass &&
7004       Subtarget.isUnalignedMem16Slow())
7005     // Without memoperands, loadRegFromAddr and storeRegToStackSlot will
7006     // conservatively assume the address is unaligned. That's bad for
7007     // performance.
7008     return false;
7009   SmallVector<MachineOperand, X86::AddrNumOperands> AddrOps;
7010   SmallVector<MachineOperand,2> BeforeOps;
7011   SmallVector<MachineOperand,2> AfterOps;
7012   SmallVector<MachineOperand,4> ImpOps;
7013   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
7014     MachineOperand &Op = MI.getOperand(i);
7015     if (i >= Index && i < Index + X86::AddrNumOperands)
7016       AddrOps.push_back(Op);
7017     else if (Op.isReg() && Op.isImplicit())
7018       ImpOps.push_back(Op);
7019     else if (i < Index)
7020       BeforeOps.push_back(Op);
7021     else if (i > Index)
7022       AfterOps.push_back(Op);
7023   }
7024 
7025   // Emit the load or broadcast instruction.
7026   if (UnfoldLoad) {
7027     auto MMOs = extractLoadMMOs(MI.memoperands(), MF);
7028 
7029     unsigned Opc;
7030     if (FoldedBCast) {
7031       Opc = getBroadcastOpcode(I, RC, Subtarget);
7032     } else {
7033       unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
7034       bool isAligned = !MMOs.empty() && MMOs.front()->getAlign() >= Alignment;
7035       Opc = getLoadRegOpcode(Reg, RC, isAligned, Subtarget);
7036     }
7037 
7038     DebugLoc DL;
7039     MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc), Reg);
7040     for (unsigned i = 0, e = AddrOps.size(); i != e; ++i)
7041       MIB.add(AddrOps[i]);
7042     MIB.setMemRefs(MMOs);
7043     NewMIs.push_back(MIB);
7044 
7045     if (UnfoldStore) {
7046       // Address operands cannot be marked isKill.
7047       for (unsigned i = 1; i != 1 + X86::AddrNumOperands; ++i) {
7048         MachineOperand &MO = NewMIs[0]->getOperand(i);
7049         if (MO.isReg())
7050           MO.setIsKill(false);
7051       }
7052     }
7053   }
7054 
7055   // Emit the data processing instruction.
7056   MachineInstr *DataMI = MF.CreateMachineInstr(MCID, MI.getDebugLoc(), true);
7057   MachineInstrBuilder MIB(MF, DataMI);
7058 
7059   if (FoldedStore)
7060     MIB.addReg(Reg, RegState::Define);
7061   for (MachineOperand &BeforeOp : BeforeOps)
7062     MIB.add(BeforeOp);
7063   if (FoldedLoad)
7064     MIB.addReg(Reg);
7065   for (MachineOperand &AfterOp : AfterOps)
7066     MIB.add(AfterOp);
7067   for (MachineOperand &ImpOp : ImpOps) {
7068     MIB.addReg(ImpOp.getReg(),
7069                getDefRegState(ImpOp.isDef()) |
7070                RegState::Implicit |
7071                getKillRegState(ImpOp.isKill()) |
7072                getDeadRegState(ImpOp.isDead()) |
7073                getUndefRegState(ImpOp.isUndef()));
7074   }
7075   // Change CMP32ri r, 0 back to TEST32rr r, r, etc.
7076   switch (DataMI->getOpcode()) {
7077   default: break;
7078   case X86::CMP64ri32:
7079   case X86::CMP32ri:
7080   case X86::CMP16ri:
7081   case X86::CMP8ri: {
7082     MachineOperand &MO0 = DataMI->getOperand(0);
7083     MachineOperand &MO1 = DataMI->getOperand(1);
7084     if (MO1.isImm() && MO1.getImm() == 0) {
7085       unsigned NewOpc;
7086       switch (DataMI->getOpcode()) {
7087       default: llvm_unreachable("Unreachable!");
7088       case X86::CMP64ri32: NewOpc = X86::TEST64rr; break;
7089       case X86::CMP32ri:   NewOpc = X86::TEST32rr; break;
7090       case X86::CMP16ri:   NewOpc = X86::TEST16rr; break;
7091       case X86::CMP8ri:    NewOpc = X86::TEST8rr; break;
7092       }
7093       DataMI->setDesc(get(NewOpc));
7094       MO1.ChangeToRegister(MO0.getReg(), false);
7095     }
7096   }
7097   }
7098   NewMIs.push_back(DataMI);
7099 
7100   // Emit the store instruction.
7101   if (UnfoldStore) {
7102     const TargetRegisterClass *DstRC = getRegClass(MCID, 0, &RI, MF);
7103     auto MMOs = extractStoreMMOs(MI.memoperands(), MF);
7104     unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*DstRC), 16);
7105     bool isAligned = !MMOs.empty() && MMOs.front()->getAlign() >= Alignment;
7106     unsigned Opc = getStoreRegOpcode(Reg, DstRC, isAligned, Subtarget);
7107     DebugLoc DL;
7108     MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc));
7109     for (unsigned i = 0, e = AddrOps.size(); i != e; ++i)
7110       MIB.add(AddrOps[i]);
7111     MIB.addReg(Reg, RegState::Kill);
7112     MIB.setMemRefs(MMOs);
7113     NewMIs.push_back(MIB);
7114   }
7115 
7116   return true;
7117 }
7118 
7119 bool
7120 X86InstrInfo::unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
7121                                   SmallVectorImpl<SDNode*> &NewNodes) const {
7122   if (!N->isMachineOpcode())
7123     return false;
7124 
7125   const X86MemoryFoldTableEntry *I = lookupUnfoldTable(N->getMachineOpcode());
7126   if (I == nullptr)
7127     return false;
7128   unsigned Opc = I->DstOp;
7129   unsigned Index = I->Flags & TB_INDEX_MASK;
7130   bool FoldedLoad = I->Flags & TB_FOLDED_LOAD;
7131   bool FoldedStore = I->Flags & TB_FOLDED_STORE;
7132   bool FoldedBCast = I->Flags & TB_FOLDED_BCAST;
7133   const MCInstrDesc &MCID = get(Opc);
7134   MachineFunction &MF = DAG.getMachineFunction();
7135   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7136   const TargetRegisterClass *RC = getRegClass(MCID, Index, &RI, MF);
7137   unsigned NumDefs = MCID.NumDefs;
7138   std::vector<SDValue> AddrOps;
7139   std::vector<SDValue> BeforeOps;
7140   std::vector<SDValue> AfterOps;
7141   SDLoc dl(N);
7142   unsigned NumOps = N->getNumOperands();
7143   for (unsigned i = 0; i != NumOps-1; ++i) {
7144     SDValue Op = N->getOperand(i);
7145     if (i >= Index-NumDefs && i < Index-NumDefs + X86::AddrNumOperands)
7146       AddrOps.push_back(Op);
7147     else if (i < Index-NumDefs)
7148       BeforeOps.push_back(Op);
7149     else if (i > Index-NumDefs)
7150       AfterOps.push_back(Op);
7151   }
7152   SDValue Chain = N->getOperand(NumOps-1);
7153   AddrOps.push_back(Chain);
7154 
7155   // Emit the load instruction.
7156   SDNode *Load = nullptr;
7157   if (FoldedLoad) {
7158     EVT VT = *TRI.legalclasstypes_begin(*RC);
7159     auto MMOs = extractLoadMMOs(cast<MachineSDNode>(N)->memoperands(), MF);
7160     if (MMOs.empty() && RC == &X86::VR128RegClass &&
7161         Subtarget.isUnalignedMem16Slow())
7162       // Do not introduce a slow unaligned load.
7163       return false;
7164     // FIXME: If a VR128 can have size 32, we should be checking if a 32-byte
7165     // memory access is slow above.
7166 
7167     unsigned Opc;
7168     if (FoldedBCast) {
7169       Opc = getBroadcastOpcode(I, RC, Subtarget);
7170     } else {
7171       unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
7172       bool isAligned = !MMOs.empty() && MMOs.front()->getAlign() >= Alignment;
7173       Opc = getLoadRegOpcode(0, RC, isAligned, Subtarget);
7174     }
7175 
7176     Load = DAG.getMachineNode(Opc, dl, VT, MVT::Other, AddrOps);
7177     NewNodes.push_back(Load);
7178 
7179     // Preserve memory reference information.
7180     DAG.setNodeMemRefs(cast<MachineSDNode>(Load), MMOs);
7181   }
7182 
7183   // Emit the data processing instruction.
7184   std::vector<EVT> VTs;
7185   const TargetRegisterClass *DstRC = nullptr;
7186   if (MCID.getNumDefs() > 0) {
7187     DstRC = getRegClass(MCID, 0, &RI, MF);
7188     VTs.push_back(*TRI.legalclasstypes_begin(*DstRC));
7189   }
7190   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
7191     EVT VT = N->getValueType(i);
7192     if (VT != MVT::Other && i >= (unsigned)MCID.getNumDefs())
7193       VTs.push_back(VT);
7194   }
7195   if (Load)
7196     BeforeOps.push_back(SDValue(Load, 0));
7197   llvm::append_range(BeforeOps, AfterOps);
7198   // Change CMP32ri r, 0 back to TEST32rr r, r, etc.
7199   switch (Opc) {
7200     default: break;
7201     case X86::CMP64ri32:
7202     case X86::CMP32ri:
7203     case X86::CMP16ri:
7204     case X86::CMP8ri:
7205       if (isNullConstant(BeforeOps[1])) {
7206         switch (Opc) {
7207           default: llvm_unreachable("Unreachable!");
7208           case X86::CMP64ri32: Opc = X86::TEST64rr; break;
7209           case X86::CMP32ri:   Opc = X86::TEST32rr; break;
7210           case X86::CMP16ri:   Opc = X86::TEST16rr; break;
7211           case X86::CMP8ri:    Opc = X86::TEST8rr; break;
7212         }
7213         BeforeOps[1] = BeforeOps[0];
7214       }
7215   }
7216   SDNode *NewNode= DAG.getMachineNode(Opc, dl, VTs, BeforeOps);
7217   NewNodes.push_back(NewNode);
7218 
7219   // Emit the store instruction.
7220   if (FoldedStore) {
7221     AddrOps.pop_back();
7222     AddrOps.push_back(SDValue(NewNode, 0));
7223     AddrOps.push_back(Chain);
7224     auto MMOs = extractStoreMMOs(cast<MachineSDNode>(N)->memoperands(), MF);
7225     if (MMOs.empty() && RC == &X86::VR128RegClass &&
7226         Subtarget.isUnalignedMem16Slow())
7227       // Do not introduce a slow unaligned store.
7228       return false;
7229     // FIXME: If a VR128 can have size 32, we should be checking if a 32-byte
7230     // memory access is slow above.
7231     unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
7232     bool isAligned = !MMOs.empty() && MMOs.front()->getAlign() >= Alignment;
7233     SDNode *Store =
7234         DAG.getMachineNode(getStoreRegOpcode(0, DstRC, isAligned, Subtarget),
7235                            dl, MVT::Other, AddrOps);
7236     NewNodes.push_back(Store);
7237 
7238     // Preserve memory reference information.
7239     DAG.setNodeMemRefs(cast<MachineSDNode>(Store), MMOs);
7240   }
7241 
7242   return true;
7243 }
7244 
7245 unsigned X86InstrInfo::getOpcodeAfterMemoryUnfold(unsigned Opc,
7246                                       bool UnfoldLoad, bool UnfoldStore,
7247                                       unsigned *LoadRegIndex) const {
7248   const X86MemoryFoldTableEntry *I = lookupUnfoldTable(Opc);
7249   if (I == nullptr)
7250     return 0;
7251   bool FoldedLoad = I->Flags & TB_FOLDED_LOAD;
7252   bool FoldedStore = I->Flags & TB_FOLDED_STORE;
7253   if (UnfoldLoad && !FoldedLoad)
7254     return 0;
7255   if (UnfoldStore && !FoldedStore)
7256     return 0;
7257   if (LoadRegIndex)
7258     *LoadRegIndex = I->Flags & TB_INDEX_MASK;
7259   return I->DstOp;
7260 }
7261 
7262 bool
7263 X86InstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
7264                                      int64_t &Offset1, int64_t &Offset2) const {
7265   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
7266     return false;
7267   unsigned Opc1 = Load1->getMachineOpcode();
7268   unsigned Opc2 = Load2->getMachineOpcode();
7269   switch (Opc1) {
7270   default: return false;
7271   case X86::MOV8rm:
7272   case X86::MOV16rm:
7273   case X86::MOV32rm:
7274   case X86::MOV64rm:
7275   case X86::LD_Fp32m:
7276   case X86::LD_Fp64m:
7277   case X86::LD_Fp80m:
7278   case X86::MOVSSrm:
7279   case X86::MOVSSrm_alt:
7280   case X86::MOVSDrm:
7281   case X86::MOVSDrm_alt:
7282   case X86::MMX_MOVD64rm:
7283   case X86::MMX_MOVQ64rm:
7284   case X86::MOVAPSrm:
7285   case X86::MOVUPSrm:
7286   case X86::MOVAPDrm:
7287   case X86::MOVUPDrm:
7288   case X86::MOVDQArm:
7289   case X86::MOVDQUrm:
7290   // AVX load instructions
7291   case X86::VMOVSSrm:
7292   case X86::VMOVSSrm_alt:
7293   case X86::VMOVSDrm:
7294   case X86::VMOVSDrm_alt:
7295   case X86::VMOVAPSrm:
7296   case X86::VMOVUPSrm:
7297   case X86::VMOVAPDrm:
7298   case X86::VMOVUPDrm:
7299   case X86::VMOVDQArm:
7300   case X86::VMOVDQUrm:
7301   case X86::VMOVAPSYrm:
7302   case X86::VMOVUPSYrm:
7303   case X86::VMOVAPDYrm:
7304   case X86::VMOVUPDYrm:
7305   case X86::VMOVDQAYrm:
7306   case X86::VMOVDQUYrm:
7307   // AVX512 load instructions
7308   case X86::VMOVSSZrm:
7309   case X86::VMOVSSZrm_alt:
7310   case X86::VMOVSDZrm:
7311   case X86::VMOVSDZrm_alt:
7312   case X86::VMOVAPSZ128rm:
7313   case X86::VMOVUPSZ128rm:
7314   case X86::VMOVAPSZ128rm_NOVLX:
7315   case X86::VMOVUPSZ128rm_NOVLX:
7316   case X86::VMOVAPDZ128rm:
7317   case X86::VMOVUPDZ128rm:
7318   case X86::VMOVDQU8Z128rm:
7319   case X86::VMOVDQU16Z128rm:
7320   case X86::VMOVDQA32Z128rm:
7321   case X86::VMOVDQU32Z128rm:
7322   case X86::VMOVDQA64Z128rm:
7323   case X86::VMOVDQU64Z128rm:
7324   case X86::VMOVAPSZ256rm:
7325   case X86::VMOVUPSZ256rm:
7326   case X86::VMOVAPSZ256rm_NOVLX:
7327   case X86::VMOVUPSZ256rm_NOVLX:
7328   case X86::VMOVAPDZ256rm:
7329   case X86::VMOVUPDZ256rm:
7330   case X86::VMOVDQU8Z256rm:
7331   case X86::VMOVDQU16Z256rm:
7332   case X86::VMOVDQA32Z256rm:
7333   case X86::VMOVDQU32Z256rm:
7334   case X86::VMOVDQA64Z256rm:
7335   case X86::VMOVDQU64Z256rm:
7336   case X86::VMOVAPSZrm:
7337   case X86::VMOVUPSZrm:
7338   case X86::VMOVAPDZrm:
7339   case X86::VMOVUPDZrm:
7340   case X86::VMOVDQU8Zrm:
7341   case X86::VMOVDQU16Zrm:
7342   case X86::VMOVDQA32Zrm:
7343   case X86::VMOVDQU32Zrm:
7344   case X86::VMOVDQA64Zrm:
7345   case X86::VMOVDQU64Zrm:
7346   case X86::KMOVBkm:
7347   case X86::KMOVWkm:
7348   case X86::KMOVDkm:
7349   case X86::KMOVQkm:
7350     break;
7351   }
7352   switch (Opc2) {
7353   default: return false;
7354   case X86::MOV8rm:
7355   case X86::MOV16rm:
7356   case X86::MOV32rm:
7357   case X86::MOV64rm:
7358   case X86::LD_Fp32m:
7359   case X86::LD_Fp64m:
7360   case X86::LD_Fp80m:
7361   case X86::MOVSSrm:
7362   case X86::MOVSSrm_alt:
7363   case X86::MOVSDrm:
7364   case X86::MOVSDrm_alt:
7365   case X86::MMX_MOVD64rm:
7366   case X86::MMX_MOVQ64rm:
7367   case X86::MOVAPSrm:
7368   case X86::MOVUPSrm:
7369   case X86::MOVAPDrm:
7370   case X86::MOVUPDrm:
7371   case X86::MOVDQArm:
7372   case X86::MOVDQUrm:
7373   // AVX load instructions
7374   case X86::VMOVSSrm:
7375   case X86::VMOVSSrm_alt:
7376   case X86::VMOVSDrm:
7377   case X86::VMOVSDrm_alt:
7378   case X86::VMOVAPSrm:
7379   case X86::VMOVUPSrm:
7380   case X86::VMOVAPDrm:
7381   case X86::VMOVUPDrm:
7382   case X86::VMOVDQArm:
7383   case X86::VMOVDQUrm:
7384   case X86::VMOVAPSYrm:
7385   case X86::VMOVUPSYrm:
7386   case X86::VMOVAPDYrm:
7387   case X86::VMOVUPDYrm:
7388   case X86::VMOVDQAYrm:
7389   case X86::VMOVDQUYrm:
7390   // AVX512 load instructions
7391   case X86::VMOVSSZrm:
7392   case X86::VMOVSSZrm_alt:
7393   case X86::VMOVSDZrm:
7394   case X86::VMOVSDZrm_alt:
7395   case X86::VMOVAPSZ128rm:
7396   case X86::VMOVUPSZ128rm:
7397   case X86::VMOVAPSZ128rm_NOVLX:
7398   case X86::VMOVUPSZ128rm_NOVLX:
7399   case X86::VMOVAPDZ128rm:
7400   case X86::VMOVUPDZ128rm:
7401   case X86::VMOVDQU8Z128rm:
7402   case X86::VMOVDQU16Z128rm:
7403   case X86::VMOVDQA32Z128rm:
7404   case X86::VMOVDQU32Z128rm:
7405   case X86::VMOVDQA64Z128rm:
7406   case X86::VMOVDQU64Z128rm:
7407   case X86::VMOVAPSZ256rm:
7408   case X86::VMOVUPSZ256rm:
7409   case X86::VMOVAPSZ256rm_NOVLX:
7410   case X86::VMOVUPSZ256rm_NOVLX:
7411   case X86::VMOVAPDZ256rm:
7412   case X86::VMOVUPDZ256rm:
7413   case X86::VMOVDQU8Z256rm:
7414   case X86::VMOVDQU16Z256rm:
7415   case X86::VMOVDQA32Z256rm:
7416   case X86::VMOVDQU32Z256rm:
7417   case X86::VMOVDQA64Z256rm:
7418   case X86::VMOVDQU64Z256rm:
7419   case X86::VMOVAPSZrm:
7420   case X86::VMOVUPSZrm:
7421   case X86::VMOVAPDZrm:
7422   case X86::VMOVUPDZrm:
7423   case X86::VMOVDQU8Zrm:
7424   case X86::VMOVDQU16Zrm:
7425   case X86::VMOVDQA32Zrm:
7426   case X86::VMOVDQU32Zrm:
7427   case X86::VMOVDQA64Zrm:
7428   case X86::VMOVDQU64Zrm:
7429   case X86::KMOVBkm:
7430   case X86::KMOVWkm:
7431   case X86::KMOVDkm:
7432   case X86::KMOVQkm:
7433     break;
7434   }
7435 
7436   // Lambda to check if both the loads have the same value for an operand index.
7437   auto HasSameOp = [&](int I) {
7438     return Load1->getOperand(I) == Load2->getOperand(I);
7439   };
7440 
7441   // All operands except the displacement should match.
7442   if (!HasSameOp(X86::AddrBaseReg) || !HasSameOp(X86::AddrScaleAmt) ||
7443       !HasSameOp(X86::AddrIndexReg) || !HasSameOp(X86::AddrSegmentReg))
7444     return false;
7445 
7446   // Chain Operand must be the same.
7447   if (!HasSameOp(5))
7448     return false;
7449 
7450   // Now let's examine if the displacements are constants.
7451   auto Disp1 = dyn_cast<ConstantSDNode>(Load1->getOperand(X86::AddrDisp));
7452   auto Disp2 = dyn_cast<ConstantSDNode>(Load2->getOperand(X86::AddrDisp));
7453   if (!Disp1 || !Disp2)
7454     return false;
7455 
7456   Offset1 = Disp1->getSExtValue();
7457   Offset2 = Disp2->getSExtValue();
7458   return true;
7459 }
7460 
7461 bool X86InstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
7462                                            int64_t Offset1, int64_t Offset2,
7463                                            unsigned NumLoads) const {
7464   assert(Offset2 > Offset1);
7465   if ((Offset2 - Offset1) / 8 > 64)
7466     return false;
7467 
7468   unsigned Opc1 = Load1->getMachineOpcode();
7469   unsigned Opc2 = Load2->getMachineOpcode();
7470   if (Opc1 != Opc2)
7471     return false;  // FIXME: overly conservative?
7472 
7473   switch (Opc1) {
7474   default: break;
7475   case X86::LD_Fp32m:
7476   case X86::LD_Fp64m:
7477   case X86::LD_Fp80m:
7478   case X86::MMX_MOVD64rm:
7479   case X86::MMX_MOVQ64rm:
7480     return false;
7481   }
7482 
7483   EVT VT = Load1->getValueType(0);
7484   switch (VT.getSimpleVT().SimpleTy) {
7485   default:
7486     // XMM registers. In 64-bit mode we can be a bit more aggressive since we
7487     // have 16 of them to play with.
7488     if (Subtarget.is64Bit()) {
7489       if (NumLoads >= 3)
7490         return false;
7491     } else if (NumLoads) {
7492       return false;
7493     }
7494     break;
7495   case MVT::i8:
7496   case MVT::i16:
7497   case MVT::i32:
7498   case MVT::i64:
7499   case MVT::f32:
7500   case MVT::f64:
7501     if (NumLoads)
7502       return false;
7503     break;
7504   }
7505 
7506   return true;
7507 }
7508 
7509 bool X86InstrInfo::isSchedulingBoundary(const MachineInstr &MI,
7510                                         const MachineBasicBlock *MBB,
7511                                         const MachineFunction &MF) const {
7512 
7513   // ENDBR instructions should not be scheduled around.
7514   unsigned Opcode = MI.getOpcode();
7515   if (Opcode == X86::ENDBR64 || Opcode == X86::ENDBR32 ||
7516       Opcode == X86::PLDTILECFGV)
7517     return true;
7518 
7519   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF);
7520 }
7521 
7522 bool X86InstrInfo::
7523 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
7524   assert(Cond.size() == 1 && "Invalid X86 branch condition!");
7525   X86::CondCode CC = static_cast<X86::CondCode>(Cond[0].getImm());
7526   Cond[0].setImm(GetOppositeBranchCondition(CC));
7527   return false;
7528 }
7529 
7530 bool X86InstrInfo::
7531 isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
7532   // FIXME: Return false for x87 stack register classes for now. We can't
7533   // allow any loads of these registers before FpGet_ST0_80.
7534   return !(RC == &X86::CCRRegClass || RC == &X86::DFCCRRegClass ||
7535            RC == &X86::RFP32RegClass || RC == &X86::RFP64RegClass ||
7536            RC == &X86::RFP80RegClass);
7537 }
7538 
7539 /// Return a virtual register initialized with the
7540 /// the global base register value. Output instructions required to
7541 /// initialize the register in the function entry block, if necessary.
7542 ///
7543 /// TODO: Eliminate this and move the code to X86MachineFunctionInfo.
7544 ///
7545 unsigned X86InstrInfo::getGlobalBaseReg(MachineFunction *MF) const {
7546   assert((!Subtarget.is64Bit() ||
7547           MF->getTarget().getCodeModel() == CodeModel::Medium ||
7548           MF->getTarget().getCodeModel() == CodeModel::Large) &&
7549          "X86-64 PIC uses RIP relative addressing");
7550 
7551   X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
7552   Register GlobalBaseReg = X86FI->getGlobalBaseReg();
7553   if (GlobalBaseReg != 0)
7554     return GlobalBaseReg;
7555 
7556   // Create the register. The code to initialize it is inserted
7557   // later, by the CGBR pass (below).
7558   MachineRegisterInfo &RegInfo = MF->getRegInfo();
7559   GlobalBaseReg = RegInfo.createVirtualRegister(
7560       Subtarget.is64Bit() ? &X86::GR64_NOSPRegClass : &X86::GR32_NOSPRegClass);
7561   X86FI->setGlobalBaseReg(GlobalBaseReg);
7562   return GlobalBaseReg;
7563 }
7564 
7565 // These are the replaceable SSE instructions. Some of these have Int variants
7566 // that we don't include here. We don't want to replace instructions selected
7567 // by intrinsics.
7568 static const uint16_t ReplaceableInstrs[][3] = {
7569   //PackedSingle     PackedDouble    PackedInt
7570   { X86::MOVAPSmr,   X86::MOVAPDmr,  X86::MOVDQAmr  },
7571   { X86::MOVAPSrm,   X86::MOVAPDrm,  X86::MOVDQArm  },
7572   { X86::MOVAPSrr,   X86::MOVAPDrr,  X86::MOVDQArr  },
7573   { X86::MOVUPSmr,   X86::MOVUPDmr,  X86::MOVDQUmr  },
7574   { X86::MOVUPSrm,   X86::MOVUPDrm,  X86::MOVDQUrm  },
7575   { X86::MOVLPSmr,   X86::MOVLPDmr,  X86::MOVPQI2QImr },
7576   { X86::MOVSDmr,    X86::MOVSDmr,   X86::MOVPQI2QImr },
7577   { X86::MOVSSmr,    X86::MOVSSmr,   X86::MOVPDI2DImr },
7578   { X86::MOVSDrm,    X86::MOVSDrm,   X86::MOVQI2PQIrm },
7579   { X86::MOVSDrm_alt,X86::MOVSDrm_alt,X86::MOVQI2PQIrm },
7580   { X86::MOVSSrm,    X86::MOVSSrm,   X86::MOVDI2PDIrm },
7581   { X86::MOVSSrm_alt,X86::MOVSSrm_alt,X86::MOVDI2PDIrm },
7582   { X86::MOVNTPSmr,  X86::MOVNTPDmr, X86::MOVNTDQmr },
7583   { X86::ANDNPSrm,   X86::ANDNPDrm,  X86::PANDNrm   },
7584   { X86::ANDNPSrr,   X86::ANDNPDrr,  X86::PANDNrr   },
7585   { X86::ANDPSrm,    X86::ANDPDrm,   X86::PANDrm    },
7586   { X86::ANDPSrr,    X86::ANDPDrr,   X86::PANDrr    },
7587   { X86::ORPSrm,     X86::ORPDrm,    X86::PORrm     },
7588   { X86::ORPSrr,     X86::ORPDrr,    X86::PORrr     },
7589   { X86::XORPSrm,    X86::XORPDrm,   X86::PXORrm    },
7590   { X86::XORPSrr,    X86::XORPDrr,   X86::PXORrr    },
7591   { X86::UNPCKLPDrm, X86::UNPCKLPDrm, X86::PUNPCKLQDQrm },
7592   { X86::MOVLHPSrr,  X86::UNPCKLPDrr, X86::PUNPCKLQDQrr },
7593   { X86::UNPCKHPDrm, X86::UNPCKHPDrm, X86::PUNPCKHQDQrm },
7594   { X86::UNPCKHPDrr, X86::UNPCKHPDrr, X86::PUNPCKHQDQrr },
7595   { X86::UNPCKLPSrm, X86::UNPCKLPSrm, X86::PUNPCKLDQrm },
7596   { X86::UNPCKLPSrr, X86::UNPCKLPSrr, X86::PUNPCKLDQrr },
7597   { X86::UNPCKHPSrm, X86::UNPCKHPSrm, X86::PUNPCKHDQrm },
7598   { X86::UNPCKHPSrr, X86::UNPCKHPSrr, X86::PUNPCKHDQrr },
7599   { X86::EXTRACTPSmr, X86::EXTRACTPSmr, X86::PEXTRDmr },
7600   { X86::EXTRACTPSrr, X86::EXTRACTPSrr, X86::PEXTRDrr },
7601   // AVX 128-bit support
7602   { X86::VMOVAPSmr,  X86::VMOVAPDmr,  X86::VMOVDQAmr  },
7603   { X86::VMOVAPSrm,  X86::VMOVAPDrm,  X86::VMOVDQArm  },
7604   { X86::VMOVAPSrr,  X86::VMOVAPDrr,  X86::VMOVDQArr  },
7605   { X86::VMOVUPSmr,  X86::VMOVUPDmr,  X86::VMOVDQUmr  },
7606   { X86::VMOVUPSrm,  X86::VMOVUPDrm,  X86::VMOVDQUrm  },
7607   { X86::VMOVLPSmr,  X86::VMOVLPDmr,  X86::VMOVPQI2QImr },
7608   { X86::VMOVSDmr,   X86::VMOVSDmr,   X86::VMOVPQI2QImr },
7609   { X86::VMOVSSmr,   X86::VMOVSSmr,   X86::VMOVPDI2DImr },
7610   { X86::VMOVSDrm,   X86::VMOVSDrm,   X86::VMOVQI2PQIrm },
7611   { X86::VMOVSDrm_alt,X86::VMOVSDrm_alt,X86::VMOVQI2PQIrm },
7612   { X86::VMOVSSrm,   X86::VMOVSSrm,   X86::VMOVDI2PDIrm },
7613   { X86::VMOVSSrm_alt,X86::VMOVSSrm_alt,X86::VMOVDI2PDIrm },
7614   { X86::VMOVNTPSmr, X86::VMOVNTPDmr, X86::VMOVNTDQmr },
7615   { X86::VANDNPSrm,  X86::VANDNPDrm,  X86::VPANDNrm   },
7616   { X86::VANDNPSrr,  X86::VANDNPDrr,  X86::VPANDNrr   },
7617   { X86::VANDPSrm,   X86::VANDPDrm,   X86::VPANDrm    },
7618   { X86::VANDPSrr,   X86::VANDPDrr,   X86::VPANDrr    },
7619   { X86::VORPSrm,    X86::VORPDrm,    X86::VPORrm     },
7620   { X86::VORPSrr,    X86::VORPDrr,    X86::VPORrr     },
7621   { X86::VXORPSrm,   X86::VXORPDrm,   X86::VPXORrm    },
7622   { X86::VXORPSrr,   X86::VXORPDrr,   X86::VPXORrr    },
7623   { X86::VUNPCKLPDrm, X86::VUNPCKLPDrm, X86::VPUNPCKLQDQrm },
7624   { X86::VMOVLHPSrr,  X86::VUNPCKLPDrr, X86::VPUNPCKLQDQrr },
7625   { X86::VUNPCKHPDrm, X86::VUNPCKHPDrm, X86::VPUNPCKHQDQrm },
7626   { X86::VUNPCKHPDrr, X86::VUNPCKHPDrr, X86::VPUNPCKHQDQrr },
7627   { X86::VUNPCKLPSrm, X86::VUNPCKLPSrm, X86::VPUNPCKLDQrm },
7628   { X86::VUNPCKLPSrr, X86::VUNPCKLPSrr, X86::VPUNPCKLDQrr },
7629   { X86::VUNPCKHPSrm, X86::VUNPCKHPSrm, X86::VPUNPCKHDQrm },
7630   { X86::VUNPCKHPSrr, X86::VUNPCKHPSrr, X86::VPUNPCKHDQrr },
7631   { X86::VEXTRACTPSmr, X86::VEXTRACTPSmr, X86::VPEXTRDmr },
7632   { X86::VEXTRACTPSrr, X86::VEXTRACTPSrr, X86::VPEXTRDrr },
7633   // AVX 256-bit support
7634   { X86::VMOVAPSYmr,   X86::VMOVAPDYmr,   X86::VMOVDQAYmr  },
7635   { X86::VMOVAPSYrm,   X86::VMOVAPDYrm,   X86::VMOVDQAYrm  },
7636   { X86::VMOVAPSYrr,   X86::VMOVAPDYrr,   X86::VMOVDQAYrr  },
7637   { X86::VMOVUPSYmr,   X86::VMOVUPDYmr,   X86::VMOVDQUYmr  },
7638   { X86::VMOVUPSYrm,   X86::VMOVUPDYrm,   X86::VMOVDQUYrm  },
7639   { X86::VMOVNTPSYmr,  X86::VMOVNTPDYmr,  X86::VMOVNTDQYmr },
7640   { X86::VPERMPSYrm,   X86::VPERMPSYrm,   X86::VPERMDYrm },
7641   { X86::VPERMPSYrr,   X86::VPERMPSYrr,   X86::VPERMDYrr },
7642   { X86::VPERMPDYmi,   X86::VPERMPDYmi,   X86::VPERMQYmi },
7643   { X86::VPERMPDYri,   X86::VPERMPDYri,   X86::VPERMQYri },
7644   // AVX512 support
7645   { X86::VMOVLPSZ128mr,  X86::VMOVLPDZ128mr,  X86::VMOVPQI2QIZmr  },
7646   { X86::VMOVNTPSZ128mr, X86::VMOVNTPDZ128mr, X86::VMOVNTDQZ128mr },
7647   { X86::VMOVNTPSZ256mr, X86::VMOVNTPDZ256mr, X86::VMOVNTDQZ256mr },
7648   { X86::VMOVNTPSZmr,    X86::VMOVNTPDZmr,    X86::VMOVNTDQZmr    },
7649   { X86::VMOVSDZmr,      X86::VMOVSDZmr,      X86::VMOVPQI2QIZmr  },
7650   { X86::VMOVSSZmr,      X86::VMOVSSZmr,      X86::VMOVPDI2DIZmr  },
7651   { X86::VMOVSDZrm,      X86::VMOVSDZrm,      X86::VMOVQI2PQIZrm  },
7652   { X86::VMOVSDZrm_alt,  X86::VMOVSDZrm_alt,  X86::VMOVQI2PQIZrm  },
7653   { X86::VMOVSSZrm,      X86::VMOVSSZrm,      X86::VMOVDI2PDIZrm  },
7654   { X86::VMOVSSZrm_alt,  X86::VMOVSSZrm_alt,  X86::VMOVDI2PDIZrm  },
7655   { X86::VBROADCASTSSZ128rr,X86::VBROADCASTSSZ128rr,X86::VPBROADCASTDZ128rr },
7656   { X86::VBROADCASTSSZ128rm,X86::VBROADCASTSSZ128rm,X86::VPBROADCASTDZ128rm },
7657   { X86::VBROADCASTSSZ256rr,X86::VBROADCASTSSZ256rr,X86::VPBROADCASTDZ256rr },
7658   { X86::VBROADCASTSSZ256rm,X86::VBROADCASTSSZ256rm,X86::VPBROADCASTDZ256rm },
7659   { X86::VBROADCASTSSZrr,   X86::VBROADCASTSSZrr,   X86::VPBROADCASTDZrr },
7660   { X86::VBROADCASTSSZrm,   X86::VBROADCASTSSZrm,   X86::VPBROADCASTDZrm },
7661   { X86::VMOVDDUPZ128rr,    X86::VMOVDDUPZ128rr,    X86::VPBROADCASTQZ128rr },
7662   { X86::VMOVDDUPZ128rm,    X86::VMOVDDUPZ128rm,    X86::VPBROADCASTQZ128rm },
7663   { X86::VBROADCASTSDZ256rr,X86::VBROADCASTSDZ256rr,X86::VPBROADCASTQZ256rr },
7664   { X86::VBROADCASTSDZ256rm,X86::VBROADCASTSDZ256rm,X86::VPBROADCASTQZ256rm },
7665   { X86::VBROADCASTSDZrr,   X86::VBROADCASTSDZrr,   X86::VPBROADCASTQZrr },
7666   { X86::VBROADCASTSDZrm,   X86::VBROADCASTSDZrm,   X86::VPBROADCASTQZrm },
7667   { X86::VINSERTF32x4Zrr,   X86::VINSERTF32x4Zrr,   X86::VINSERTI32x4Zrr },
7668   { X86::VINSERTF32x4Zrm,   X86::VINSERTF32x4Zrm,   X86::VINSERTI32x4Zrm },
7669   { X86::VINSERTF32x8Zrr,   X86::VINSERTF32x8Zrr,   X86::VINSERTI32x8Zrr },
7670   { X86::VINSERTF32x8Zrm,   X86::VINSERTF32x8Zrm,   X86::VINSERTI32x8Zrm },
7671   { X86::VINSERTF64x2Zrr,   X86::VINSERTF64x2Zrr,   X86::VINSERTI64x2Zrr },
7672   { X86::VINSERTF64x2Zrm,   X86::VINSERTF64x2Zrm,   X86::VINSERTI64x2Zrm },
7673   { X86::VINSERTF64x4Zrr,   X86::VINSERTF64x4Zrr,   X86::VINSERTI64x4Zrr },
7674   { X86::VINSERTF64x4Zrm,   X86::VINSERTF64x4Zrm,   X86::VINSERTI64x4Zrm },
7675   { X86::VINSERTF32x4Z256rr,X86::VINSERTF32x4Z256rr,X86::VINSERTI32x4Z256rr },
7676   { X86::VINSERTF32x4Z256rm,X86::VINSERTF32x4Z256rm,X86::VINSERTI32x4Z256rm },
7677   { X86::VINSERTF64x2Z256rr,X86::VINSERTF64x2Z256rr,X86::VINSERTI64x2Z256rr },
7678   { X86::VINSERTF64x2Z256rm,X86::VINSERTF64x2Z256rm,X86::VINSERTI64x2Z256rm },
7679   { X86::VEXTRACTF32x4Zrr,   X86::VEXTRACTF32x4Zrr,   X86::VEXTRACTI32x4Zrr },
7680   { X86::VEXTRACTF32x4Zmr,   X86::VEXTRACTF32x4Zmr,   X86::VEXTRACTI32x4Zmr },
7681   { X86::VEXTRACTF32x8Zrr,   X86::VEXTRACTF32x8Zrr,   X86::VEXTRACTI32x8Zrr },
7682   { X86::VEXTRACTF32x8Zmr,   X86::VEXTRACTF32x8Zmr,   X86::VEXTRACTI32x8Zmr },
7683   { X86::VEXTRACTF64x2Zrr,   X86::VEXTRACTF64x2Zrr,   X86::VEXTRACTI64x2Zrr },
7684   { X86::VEXTRACTF64x2Zmr,   X86::VEXTRACTF64x2Zmr,   X86::VEXTRACTI64x2Zmr },
7685   { X86::VEXTRACTF64x4Zrr,   X86::VEXTRACTF64x4Zrr,   X86::VEXTRACTI64x4Zrr },
7686   { X86::VEXTRACTF64x4Zmr,   X86::VEXTRACTF64x4Zmr,   X86::VEXTRACTI64x4Zmr },
7687   { X86::VEXTRACTF32x4Z256rr,X86::VEXTRACTF32x4Z256rr,X86::VEXTRACTI32x4Z256rr },
7688   { X86::VEXTRACTF32x4Z256mr,X86::VEXTRACTF32x4Z256mr,X86::VEXTRACTI32x4Z256mr },
7689   { X86::VEXTRACTF64x2Z256rr,X86::VEXTRACTF64x2Z256rr,X86::VEXTRACTI64x2Z256rr },
7690   { X86::VEXTRACTF64x2Z256mr,X86::VEXTRACTF64x2Z256mr,X86::VEXTRACTI64x2Z256mr },
7691   { X86::VPERMILPSmi,        X86::VPERMILPSmi,        X86::VPSHUFDmi },
7692   { X86::VPERMILPSri,        X86::VPERMILPSri,        X86::VPSHUFDri },
7693   { X86::VPERMILPSZ128mi,    X86::VPERMILPSZ128mi,    X86::VPSHUFDZ128mi },
7694   { X86::VPERMILPSZ128ri,    X86::VPERMILPSZ128ri,    X86::VPSHUFDZ128ri },
7695   { X86::VPERMILPSZ256mi,    X86::VPERMILPSZ256mi,    X86::VPSHUFDZ256mi },
7696   { X86::VPERMILPSZ256ri,    X86::VPERMILPSZ256ri,    X86::VPSHUFDZ256ri },
7697   { X86::VPERMILPSZmi,       X86::VPERMILPSZmi,       X86::VPSHUFDZmi },
7698   { X86::VPERMILPSZri,       X86::VPERMILPSZri,       X86::VPSHUFDZri },
7699   { X86::VPERMPSZ256rm,      X86::VPERMPSZ256rm,      X86::VPERMDZ256rm },
7700   { X86::VPERMPSZ256rr,      X86::VPERMPSZ256rr,      X86::VPERMDZ256rr },
7701   { X86::VPERMPDZ256mi,      X86::VPERMPDZ256mi,      X86::VPERMQZ256mi },
7702   { X86::VPERMPDZ256ri,      X86::VPERMPDZ256ri,      X86::VPERMQZ256ri },
7703   { X86::VPERMPDZ256rm,      X86::VPERMPDZ256rm,      X86::VPERMQZ256rm },
7704   { X86::VPERMPDZ256rr,      X86::VPERMPDZ256rr,      X86::VPERMQZ256rr },
7705   { X86::VPERMPSZrm,         X86::VPERMPSZrm,         X86::VPERMDZrm },
7706   { X86::VPERMPSZrr,         X86::VPERMPSZrr,         X86::VPERMDZrr },
7707   { X86::VPERMPDZmi,         X86::VPERMPDZmi,         X86::VPERMQZmi },
7708   { X86::VPERMPDZri,         X86::VPERMPDZri,         X86::VPERMQZri },
7709   { X86::VPERMPDZrm,         X86::VPERMPDZrm,         X86::VPERMQZrm },
7710   { X86::VPERMPDZrr,         X86::VPERMPDZrr,         X86::VPERMQZrr },
7711   { X86::VUNPCKLPDZ256rm,    X86::VUNPCKLPDZ256rm,    X86::VPUNPCKLQDQZ256rm },
7712   { X86::VUNPCKLPDZ256rr,    X86::VUNPCKLPDZ256rr,    X86::VPUNPCKLQDQZ256rr },
7713   { X86::VUNPCKHPDZ256rm,    X86::VUNPCKHPDZ256rm,    X86::VPUNPCKHQDQZ256rm },
7714   { X86::VUNPCKHPDZ256rr,    X86::VUNPCKHPDZ256rr,    X86::VPUNPCKHQDQZ256rr },
7715   { X86::VUNPCKLPSZ256rm,    X86::VUNPCKLPSZ256rm,    X86::VPUNPCKLDQZ256rm },
7716   { X86::VUNPCKLPSZ256rr,    X86::VUNPCKLPSZ256rr,    X86::VPUNPCKLDQZ256rr },
7717   { X86::VUNPCKHPSZ256rm,    X86::VUNPCKHPSZ256rm,    X86::VPUNPCKHDQZ256rm },
7718   { X86::VUNPCKHPSZ256rr,    X86::VUNPCKHPSZ256rr,    X86::VPUNPCKHDQZ256rr },
7719   { X86::VUNPCKLPDZ128rm,    X86::VUNPCKLPDZ128rm,    X86::VPUNPCKLQDQZ128rm },
7720   { X86::VMOVLHPSZrr,        X86::VUNPCKLPDZ128rr,    X86::VPUNPCKLQDQZ128rr },
7721   { X86::VUNPCKHPDZ128rm,    X86::VUNPCKHPDZ128rm,    X86::VPUNPCKHQDQZ128rm },
7722   { X86::VUNPCKHPDZ128rr,    X86::VUNPCKHPDZ128rr,    X86::VPUNPCKHQDQZ128rr },
7723   { X86::VUNPCKLPSZ128rm,    X86::VUNPCKLPSZ128rm,    X86::VPUNPCKLDQZ128rm },
7724   { X86::VUNPCKLPSZ128rr,    X86::VUNPCKLPSZ128rr,    X86::VPUNPCKLDQZ128rr },
7725   { X86::VUNPCKHPSZ128rm,    X86::VUNPCKHPSZ128rm,    X86::VPUNPCKHDQZ128rm },
7726   { X86::VUNPCKHPSZ128rr,    X86::VUNPCKHPSZ128rr,    X86::VPUNPCKHDQZ128rr },
7727   { X86::VUNPCKLPDZrm,       X86::VUNPCKLPDZrm,       X86::VPUNPCKLQDQZrm },
7728   { X86::VUNPCKLPDZrr,       X86::VUNPCKLPDZrr,       X86::VPUNPCKLQDQZrr },
7729   { X86::VUNPCKHPDZrm,       X86::VUNPCKHPDZrm,       X86::VPUNPCKHQDQZrm },
7730   { X86::VUNPCKHPDZrr,       X86::VUNPCKHPDZrr,       X86::VPUNPCKHQDQZrr },
7731   { X86::VUNPCKLPSZrm,       X86::VUNPCKLPSZrm,       X86::VPUNPCKLDQZrm },
7732   { X86::VUNPCKLPSZrr,       X86::VUNPCKLPSZrr,       X86::VPUNPCKLDQZrr },
7733   { X86::VUNPCKHPSZrm,       X86::VUNPCKHPSZrm,       X86::VPUNPCKHDQZrm },
7734   { X86::VUNPCKHPSZrr,       X86::VUNPCKHPSZrr,       X86::VPUNPCKHDQZrr },
7735   { X86::VEXTRACTPSZmr,      X86::VEXTRACTPSZmr,      X86::VPEXTRDZmr },
7736   { X86::VEXTRACTPSZrr,      X86::VEXTRACTPSZrr,      X86::VPEXTRDZrr },
7737 };
7738 
7739 static const uint16_t ReplaceableInstrsAVX2[][3] = {
7740   //PackedSingle       PackedDouble       PackedInt
7741   { X86::VANDNPSYrm,   X86::VANDNPDYrm,   X86::VPANDNYrm   },
7742   { X86::VANDNPSYrr,   X86::VANDNPDYrr,   X86::VPANDNYrr   },
7743   { X86::VANDPSYrm,    X86::VANDPDYrm,    X86::VPANDYrm    },
7744   { X86::VANDPSYrr,    X86::VANDPDYrr,    X86::VPANDYrr    },
7745   { X86::VORPSYrm,     X86::VORPDYrm,     X86::VPORYrm     },
7746   { X86::VORPSYrr,     X86::VORPDYrr,     X86::VPORYrr     },
7747   { X86::VXORPSYrm,    X86::VXORPDYrm,    X86::VPXORYrm    },
7748   { X86::VXORPSYrr,    X86::VXORPDYrr,    X86::VPXORYrr    },
7749   { X86::VPERM2F128rm,   X86::VPERM2F128rm,   X86::VPERM2I128rm },
7750   { X86::VPERM2F128rr,   X86::VPERM2F128rr,   X86::VPERM2I128rr },
7751   { X86::VBROADCASTSSrm, X86::VBROADCASTSSrm, X86::VPBROADCASTDrm},
7752   { X86::VBROADCASTSSrr, X86::VBROADCASTSSrr, X86::VPBROADCASTDrr},
7753   { X86::VMOVDDUPrm,     X86::VMOVDDUPrm,     X86::VPBROADCASTQrm},
7754   { X86::VMOVDDUPrr,     X86::VMOVDDUPrr,     X86::VPBROADCASTQrr},
7755   { X86::VBROADCASTSSYrr, X86::VBROADCASTSSYrr, X86::VPBROADCASTDYrr},
7756   { X86::VBROADCASTSSYrm, X86::VBROADCASTSSYrm, X86::VPBROADCASTDYrm},
7757   { X86::VBROADCASTSDYrr, X86::VBROADCASTSDYrr, X86::VPBROADCASTQYrr},
7758   { X86::VBROADCASTSDYrm, X86::VBROADCASTSDYrm, X86::VPBROADCASTQYrm},
7759   { X86::VBROADCASTF128,  X86::VBROADCASTF128,  X86::VBROADCASTI128 },
7760   { X86::VBLENDPSYrri,    X86::VBLENDPSYrri,    X86::VPBLENDDYrri },
7761   { X86::VBLENDPSYrmi,    X86::VBLENDPSYrmi,    X86::VPBLENDDYrmi },
7762   { X86::VPERMILPSYmi,    X86::VPERMILPSYmi,    X86::VPSHUFDYmi },
7763   { X86::VPERMILPSYri,    X86::VPERMILPSYri,    X86::VPSHUFDYri },
7764   { X86::VUNPCKLPDYrm,    X86::VUNPCKLPDYrm,    X86::VPUNPCKLQDQYrm },
7765   { X86::VUNPCKLPDYrr,    X86::VUNPCKLPDYrr,    X86::VPUNPCKLQDQYrr },
7766   { X86::VUNPCKHPDYrm,    X86::VUNPCKHPDYrm,    X86::VPUNPCKHQDQYrm },
7767   { X86::VUNPCKHPDYrr,    X86::VUNPCKHPDYrr,    X86::VPUNPCKHQDQYrr },
7768   { X86::VUNPCKLPSYrm,    X86::VUNPCKLPSYrm,    X86::VPUNPCKLDQYrm },
7769   { X86::VUNPCKLPSYrr,    X86::VUNPCKLPSYrr,    X86::VPUNPCKLDQYrr },
7770   { X86::VUNPCKHPSYrm,    X86::VUNPCKHPSYrm,    X86::VPUNPCKHDQYrm },
7771   { X86::VUNPCKHPSYrr,    X86::VUNPCKHPSYrr,    X86::VPUNPCKHDQYrr },
7772 };
7773 
7774 static const uint16_t ReplaceableInstrsFP[][3] = {
7775   //PackedSingle         PackedDouble
7776   { X86::MOVLPSrm,       X86::MOVLPDrm,      X86::INSTRUCTION_LIST_END },
7777   { X86::MOVHPSrm,       X86::MOVHPDrm,      X86::INSTRUCTION_LIST_END },
7778   { X86::MOVHPSmr,       X86::MOVHPDmr,      X86::INSTRUCTION_LIST_END },
7779   { X86::VMOVLPSrm,      X86::VMOVLPDrm,     X86::INSTRUCTION_LIST_END },
7780   { X86::VMOVHPSrm,      X86::VMOVHPDrm,     X86::INSTRUCTION_LIST_END },
7781   { X86::VMOVHPSmr,      X86::VMOVHPDmr,     X86::INSTRUCTION_LIST_END },
7782   { X86::VMOVLPSZ128rm,  X86::VMOVLPDZ128rm, X86::INSTRUCTION_LIST_END },
7783   { X86::VMOVHPSZ128rm,  X86::VMOVHPDZ128rm, X86::INSTRUCTION_LIST_END },
7784   { X86::VMOVHPSZ128mr,  X86::VMOVHPDZ128mr, X86::INSTRUCTION_LIST_END },
7785 };
7786 
7787 static const uint16_t ReplaceableInstrsAVX2InsertExtract[][3] = {
7788   //PackedSingle       PackedDouble       PackedInt
7789   { X86::VEXTRACTF128mr, X86::VEXTRACTF128mr, X86::VEXTRACTI128mr },
7790   { X86::VEXTRACTF128rr, X86::VEXTRACTF128rr, X86::VEXTRACTI128rr },
7791   { X86::VINSERTF128rm,  X86::VINSERTF128rm,  X86::VINSERTI128rm },
7792   { X86::VINSERTF128rr,  X86::VINSERTF128rr,  X86::VINSERTI128rr },
7793 };
7794 
7795 static const uint16_t ReplaceableInstrsAVX512[][4] = {
7796   // Two integer columns for 64-bit and 32-bit elements.
7797   //PackedSingle        PackedDouble        PackedInt             PackedInt
7798   { X86::VMOVAPSZ128mr, X86::VMOVAPDZ128mr, X86::VMOVDQA64Z128mr, X86::VMOVDQA32Z128mr  },
7799   { X86::VMOVAPSZ128rm, X86::VMOVAPDZ128rm, X86::VMOVDQA64Z128rm, X86::VMOVDQA32Z128rm  },
7800   { X86::VMOVAPSZ128rr, X86::VMOVAPDZ128rr, X86::VMOVDQA64Z128rr, X86::VMOVDQA32Z128rr  },
7801   { X86::VMOVUPSZ128mr, X86::VMOVUPDZ128mr, X86::VMOVDQU64Z128mr, X86::VMOVDQU32Z128mr  },
7802   { X86::VMOVUPSZ128rm, X86::VMOVUPDZ128rm, X86::VMOVDQU64Z128rm, X86::VMOVDQU32Z128rm  },
7803   { X86::VMOVAPSZ256mr, X86::VMOVAPDZ256mr, X86::VMOVDQA64Z256mr, X86::VMOVDQA32Z256mr  },
7804   { X86::VMOVAPSZ256rm, X86::VMOVAPDZ256rm, X86::VMOVDQA64Z256rm, X86::VMOVDQA32Z256rm  },
7805   { X86::VMOVAPSZ256rr, X86::VMOVAPDZ256rr, X86::VMOVDQA64Z256rr, X86::VMOVDQA32Z256rr  },
7806   { X86::VMOVUPSZ256mr, X86::VMOVUPDZ256mr, X86::VMOVDQU64Z256mr, X86::VMOVDQU32Z256mr  },
7807   { X86::VMOVUPSZ256rm, X86::VMOVUPDZ256rm, X86::VMOVDQU64Z256rm, X86::VMOVDQU32Z256rm  },
7808   { X86::VMOVAPSZmr,    X86::VMOVAPDZmr,    X86::VMOVDQA64Zmr,    X86::VMOVDQA32Zmr     },
7809   { X86::VMOVAPSZrm,    X86::VMOVAPDZrm,    X86::VMOVDQA64Zrm,    X86::VMOVDQA32Zrm     },
7810   { X86::VMOVAPSZrr,    X86::VMOVAPDZrr,    X86::VMOVDQA64Zrr,    X86::VMOVDQA32Zrr     },
7811   { X86::VMOVUPSZmr,    X86::VMOVUPDZmr,    X86::VMOVDQU64Zmr,    X86::VMOVDQU32Zmr     },
7812   { X86::VMOVUPSZrm,    X86::VMOVUPDZrm,    X86::VMOVDQU64Zrm,    X86::VMOVDQU32Zrm     },
7813 };
7814 
7815 static const uint16_t ReplaceableInstrsAVX512DQ[][4] = {
7816   // Two integer columns for 64-bit and 32-bit elements.
7817   //PackedSingle        PackedDouble        PackedInt           PackedInt
7818   { X86::VANDNPSZ128rm, X86::VANDNPDZ128rm, X86::VPANDNQZ128rm, X86::VPANDNDZ128rm },
7819   { X86::VANDNPSZ128rr, X86::VANDNPDZ128rr, X86::VPANDNQZ128rr, X86::VPANDNDZ128rr },
7820   { X86::VANDPSZ128rm,  X86::VANDPDZ128rm,  X86::VPANDQZ128rm,  X86::VPANDDZ128rm  },
7821   { X86::VANDPSZ128rr,  X86::VANDPDZ128rr,  X86::VPANDQZ128rr,  X86::VPANDDZ128rr  },
7822   { X86::VORPSZ128rm,   X86::VORPDZ128rm,   X86::VPORQZ128rm,   X86::VPORDZ128rm   },
7823   { X86::VORPSZ128rr,   X86::VORPDZ128rr,   X86::VPORQZ128rr,   X86::VPORDZ128rr   },
7824   { X86::VXORPSZ128rm,  X86::VXORPDZ128rm,  X86::VPXORQZ128rm,  X86::VPXORDZ128rm  },
7825   { X86::VXORPSZ128rr,  X86::VXORPDZ128rr,  X86::VPXORQZ128rr,  X86::VPXORDZ128rr  },
7826   { X86::VANDNPSZ256rm, X86::VANDNPDZ256rm, X86::VPANDNQZ256rm, X86::VPANDNDZ256rm },
7827   { X86::VANDNPSZ256rr, X86::VANDNPDZ256rr, X86::VPANDNQZ256rr, X86::VPANDNDZ256rr },
7828   { X86::VANDPSZ256rm,  X86::VANDPDZ256rm,  X86::VPANDQZ256rm,  X86::VPANDDZ256rm  },
7829   { X86::VANDPSZ256rr,  X86::VANDPDZ256rr,  X86::VPANDQZ256rr,  X86::VPANDDZ256rr  },
7830   { X86::VORPSZ256rm,   X86::VORPDZ256rm,   X86::VPORQZ256rm,   X86::VPORDZ256rm   },
7831   { X86::VORPSZ256rr,   X86::VORPDZ256rr,   X86::VPORQZ256rr,   X86::VPORDZ256rr   },
7832   { X86::VXORPSZ256rm,  X86::VXORPDZ256rm,  X86::VPXORQZ256rm,  X86::VPXORDZ256rm  },
7833   { X86::VXORPSZ256rr,  X86::VXORPDZ256rr,  X86::VPXORQZ256rr,  X86::VPXORDZ256rr  },
7834   { X86::VANDNPSZrm,    X86::VANDNPDZrm,    X86::VPANDNQZrm,    X86::VPANDNDZrm    },
7835   { X86::VANDNPSZrr,    X86::VANDNPDZrr,    X86::VPANDNQZrr,    X86::VPANDNDZrr    },
7836   { X86::VANDPSZrm,     X86::VANDPDZrm,     X86::VPANDQZrm,     X86::VPANDDZrm     },
7837   { X86::VANDPSZrr,     X86::VANDPDZrr,     X86::VPANDQZrr,     X86::VPANDDZrr     },
7838   { X86::VORPSZrm,      X86::VORPDZrm,      X86::VPORQZrm,      X86::VPORDZrm      },
7839   { X86::VORPSZrr,      X86::VORPDZrr,      X86::VPORQZrr,      X86::VPORDZrr      },
7840   { X86::VXORPSZrm,     X86::VXORPDZrm,     X86::VPXORQZrm,     X86::VPXORDZrm     },
7841   { X86::VXORPSZrr,     X86::VXORPDZrr,     X86::VPXORQZrr,     X86::VPXORDZrr     },
7842 };
7843 
7844 static const uint16_t ReplaceableInstrsAVX512DQMasked[][4] = {
7845   // Two integer columns for 64-bit and 32-bit elements.
7846   //PackedSingle          PackedDouble
7847   //PackedInt             PackedInt
7848   { X86::VANDNPSZ128rmk,  X86::VANDNPDZ128rmk,
7849     X86::VPANDNQZ128rmk,  X86::VPANDNDZ128rmk  },
7850   { X86::VANDNPSZ128rmkz, X86::VANDNPDZ128rmkz,
7851     X86::VPANDNQZ128rmkz, X86::VPANDNDZ128rmkz },
7852   { X86::VANDNPSZ128rrk,  X86::VANDNPDZ128rrk,
7853     X86::VPANDNQZ128rrk,  X86::VPANDNDZ128rrk  },
7854   { X86::VANDNPSZ128rrkz, X86::VANDNPDZ128rrkz,
7855     X86::VPANDNQZ128rrkz, X86::VPANDNDZ128rrkz },
7856   { X86::VANDPSZ128rmk,   X86::VANDPDZ128rmk,
7857     X86::VPANDQZ128rmk,   X86::VPANDDZ128rmk   },
7858   { X86::VANDPSZ128rmkz,  X86::VANDPDZ128rmkz,
7859     X86::VPANDQZ128rmkz,  X86::VPANDDZ128rmkz  },
7860   { X86::VANDPSZ128rrk,   X86::VANDPDZ128rrk,
7861     X86::VPANDQZ128rrk,   X86::VPANDDZ128rrk   },
7862   { X86::VANDPSZ128rrkz,  X86::VANDPDZ128rrkz,
7863     X86::VPANDQZ128rrkz,  X86::VPANDDZ128rrkz  },
7864   { X86::VORPSZ128rmk,    X86::VORPDZ128rmk,
7865     X86::VPORQZ128rmk,    X86::VPORDZ128rmk    },
7866   { X86::VORPSZ128rmkz,   X86::VORPDZ128rmkz,
7867     X86::VPORQZ128rmkz,   X86::VPORDZ128rmkz   },
7868   { X86::VORPSZ128rrk,    X86::VORPDZ128rrk,
7869     X86::VPORQZ128rrk,    X86::VPORDZ128rrk    },
7870   { X86::VORPSZ128rrkz,   X86::VORPDZ128rrkz,
7871     X86::VPORQZ128rrkz,   X86::VPORDZ128rrkz   },
7872   { X86::VXORPSZ128rmk,   X86::VXORPDZ128rmk,
7873     X86::VPXORQZ128rmk,   X86::VPXORDZ128rmk   },
7874   { X86::VXORPSZ128rmkz,  X86::VXORPDZ128rmkz,
7875     X86::VPXORQZ128rmkz,  X86::VPXORDZ128rmkz  },
7876   { X86::VXORPSZ128rrk,   X86::VXORPDZ128rrk,
7877     X86::VPXORQZ128rrk,   X86::VPXORDZ128rrk   },
7878   { X86::VXORPSZ128rrkz,  X86::VXORPDZ128rrkz,
7879     X86::VPXORQZ128rrkz,  X86::VPXORDZ128rrkz  },
7880   { X86::VANDNPSZ256rmk,  X86::VANDNPDZ256rmk,
7881     X86::VPANDNQZ256rmk,  X86::VPANDNDZ256rmk  },
7882   { X86::VANDNPSZ256rmkz, X86::VANDNPDZ256rmkz,
7883     X86::VPANDNQZ256rmkz, X86::VPANDNDZ256rmkz },
7884   { X86::VANDNPSZ256rrk,  X86::VANDNPDZ256rrk,
7885     X86::VPANDNQZ256rrk,  X86::VPANDNDZ256rrk  },
7886   { X86::VANDNPSZ256rrkz, X86::VANDNPDZ256rrkz,
7887     X86::VPANDNQZ256rrkz, X86::VPANDNDZ256rrkz },
7888   { X86::VANDPSZ256rmk,   X86::VANDPDZ256rmk,
7889     X86::VPANDQZ256rmk,   X86::VPANDDZ256rmk   },
7890   { X86::VANDPSZ256rmkz,  X86::VANDPDZ256rmkz,
7891     X86::VPANDQZ256rmkz,  X86::VPANDDZ256rmkz  },
7892   { X86::VANDPSZ256rrk,   X86::VANDPDZ256rrk,
7893     X86::VPANDQZ256rrk,   X86::VPANDDZ256rrk   },
7894   { X86::VANDPSZ256rrkz,  X86::VANDPDZ256rrkz,
7895     X86::VPANDQZ256rrkz,  X86::VPANDDZ256rrkz  },
7896   { X86::VORPSZ256rmk,    X86::VORPDZ256rmk,
7897     X86::VPORQZ256rmk,    X86::VPORDZ256rmk    },
7898   { X86::VORPSZ256rmkz,   X86::VORPDZ256rmkz,
7899     X86::VPORQZ256rmkz,   X86::VPORDZ256rmkz   },
7900   { X86::VORPSZ256rrk,    X86::VORPDZ256rrk,
7901     X86::VPORQZ256rrk,    X86::VPORDZ256rrk    },
7902   { X86::VORPSZ256rrkz,   X86::VORPDZ256rrkz,
7903     X86::VPORQZ256rrkz,   X86::VPORDZ256rrkz   },
7904   { X86::VXORPSZ256rmk,   X86::VXORPDZ256rmk,
7905     X86::VPXORQZ256rmk,   X86::VPXORDZ256rmk   },
7906   { X86::VXORPSZ256rmkz,  X86::VXORPDZ256rmkz,
7907     X86::VPXORQZ256rmkz,  X86::VPXORDZ256rmkz  },
7908   { X86::VXORPSZ256rrk,   X86::VXORPDZ256rrk,
7909     X86::VPXORQZ256rrk,   X86::VPXORDZ256rrk   },
7910   { X86::VXORPSZ256rrkz,  X86::VXORPDZ256rrkz,
7911     X86::VPXORQZ256rrkz,  X86::VPXORDZ256rrkz  },
7912   { X86::VANDNPSZrmk,     X86::VANDNPDZrmk,
7913     X86::VPANDNQZrmk,     X86::VPANDNDZrmk     },
7914   { X86::VANDNPSZrmkz,    X86::VANDNPDZrmkz,
7915     X86::VPANDNQZrmkz,    X86::VPANDNDZrmkz    },
7916   { X86::VANDNPSZrrk,     X86::VANDNPDZrrk,
7917     X86::VPANDNQZrrk,     X86::VPANDNDZrrk     },
7918   { X86::VANDNPSZrrkz,    X86::VANDNPDZrrkz,
7919     X86::VPANDNQZrrkz,    X86::VPANDNDZrrkz    },
7920   { X86::VANDPSZrmk,      X86::VANDPDZrmk,
7921     X86::VPANDQZrmk,      X86::VPANDDZrmk      },
7922   { X86::VANDPSZrmkz,     X86::VANDPDZrmkz,
7923     X86::VPANDQZrmkz,     X86::VPANDDZrmkz     },
7924   { X86::VANDPSZrrk,      X86::VANDPDZrrk,
7925     X86::VPANDQZrrk,      X86::VPANDDZrrk      },
7926   { X86::VANDPSZrrkz,     X86::VANDPDZrrkz,
7927     X86::VPANDQZrrkz,     X86::VPANDDZrrkz     },
7928   { X86::VORPSZrmk,       X86::VORPDZrmk,
7929     X86::VPORQZrmk,       X86::VPORDZrmk       },
7930   { X86::VORPSZrmkz,      X86::VORPDZrmkz,
7931     X86::VPORQZrmkz,      X86::VPORDZrmkz      },
7932   { X86::VORPSZrrk,       X86::VORPDZrrk,
7933     X86::VPORQZrrk,       X86::VPORDZrrk       },
7934   { X86::VORPSZrrkz,      X86::VORPDZrrkz,
7935     X86::VPORQZrrkz,      X86::VPORDZrrkz      },
7936   { X86::VXORPSZrmk,      X86::VXORPDZrmk,
7937     X86::VPXORQZrmk,      X86::VPXORDZrmk      },
7938   { X86::VXORPSZrmkz,     X86::VXORPDZrmkz,
7939     X86::VPXORQZrmkz,     X86::VPXORDZrmkz     },
7940   { X86::VXORPSZrrk,      X86::VXORPDZrrk,
7941     X86::VPXORQZrrk,      X86::VPXORDZrrk      },
7942   { X86::VXORPSZrrkz,     X86::VXORPDZrrkz,
7943     X86::VPXORQZrrkz,     X86::VPXORDZrrkz     },
7944   // Broadcast loads can be handled the same as masked operations to avoid
7945   // changing element size.
7946   { X86::VANDNPSZ128rmb,  X86::VANDNPDZ128rmb,
7947     X86::VPANDNQZ128rmb,  X86::VPANDNDZ128rmb  },
7948   { X86::VANDPSZ128rmb,   X86::VANDPDZ128rmb,
7949     X86::VPANDQZ128rmb,   X86::VPANDDZ128rmb   },
7950   { X86::VORPSZ128rmb,    X86::VORPDZ128rmb,
7951     X86::VPORQZ128rmb,    X86::VPORDZ128rmb    },
7952   { X86::VXORPSZ128rmb,   X86::VXORPDZ128rmb,
7953     X86::VPXORQZ128rmb,   X86::VPXORDZ128rmb   },
7954   { X86::VANDNPSZ256rmb,  X86::VANDNPDZ256rmb,
7955     X86::VPANDNQZ256rmb,  X86::VPANDNDZ256rmb  },
7956   { X86::VANDPSZ256rmb,   X86::VANDPDZ256rmb,
7957     X86::VPANDQZ256rmb,   X86::VPANDDZ256rmb   },
7958   { X86::VORPSZ256rmb,    X86::VORPDZ256rmb,
7959     X86::VPORQZ256rmb,    X86::VPORDZ256rmb    },
7960   { X86::VXORPSZ256rmb,   X86::VXORPDZ256rmb,
7961     X86::VPXORQZ256rmb,   X86::VPXORDZ256rmb   },
7962   { X86::VANDNPSZrmb,     X86::VANDNPDZrmb,
7963     X86::VPANDNQZrmb,     X86::VPANDNDZrmb     },
7964   { X86::VANDPSZrmb,      X86::VANDPDZrmb,
7965     X86::VPANDQZrmb,      X86::VPANDDZrmb      },
7966   { X86::VANDPSZrmb,      X86::VANDPDZrmb,
7967     X86::VPANDQZrmb,      X86::VPANDDZrmb      },
7968   { X86::VORPSZrmb,       X86::VORPDZrmb,
7969     X86::VPORQZrmb,       X86::VPORDZrmb       },
7970   { X86::VXORPSZrmb,      X86::VXORPDZrmb,
7971     X86::VPXORQZrmb,      X86::VPXORDZrmb      },
7972   { X86::VANDNPSZ128rmbk, X86::VANDNPDZ128rmbk,
7973     X86::VPANDNQZ128rmbk, X86::VPANDNDZ128rmbk },
7974   { X86::VANDPSZ128rmbk,  X86::VANDPDZ128rmbk,
7975     X86::VPANDQZ128rmbk,  X86::VPANDDZ128rmbk  },
7976   { X86::VORPSZ128rmbk,   X86::VORPDZ128rmbk,
7977     X86::VPORQZ128rmbk,   X86::VPORDZ128rmbk   },
7978   { X86::VXORPSZ128rmbk,  X86::VXORPDZ128rmbk,
7979     X86::VPXORQZ128rmbk,  X86::VPXORDZ128rmbk  },
7980   { X86::VANDNPSZ256rmbk, X86::VANDNPDZ256rmbk,
7981     X86::VPANDNQZ256rmbk, X86::VPANDNDZ256rmbk },
7982   { X86::VANDPSZ256rmbk,  X86::VANDPDZ256rmbk,
7983     X86::VPANDQZ256rmbk,  X86::VPANDDZ256rmbk  },
7984   { X86::VORPSZ256rmbk,   X86::VORPDZ256rmbk,
7985     X86::VPORQZ256rmbk,   X86::VPORDZ256rmbk   },
7986   { X86::VXORPSZ256rmbk,  X86::VXORPDZ256rmbk,
7987     X86::VPXORQZ256rmbk,  X86::VPXORDZ256rmbk  },
7988   { X86::VANDNPSZrmbk,    X86::VANDNPDZrmbk,
7989     X86::VPANDNQZrmbk,    X86::VPANDNDZrmbk    },
7990   { X86::VANDPSZrmbk,     X86::VANDPDZrmbk,
7991     X86::VPANDQZrmbk,     X86::VPANDDZrmbk     },
7992   { X86::VANDPSZrmbk,     X86::VANDPDZrmbk,
7993     X86::VPANDQZrmbk,     X86::VPANDDZrmbk     },
7994   { X86::VORPSZrmbk,      X86::VORPDZrmbk,
7995     X86::VPORQZrmbk,      X86::VPORDZrmbk      },
7996   { X86::VXORPSZrmbk,     X86::VXORPDZrmbk,
7997     X86::VPXORQZrmbk,     X86::VPXORDZrmbk     },
7998   { X86::VANDNPSZ128rmbkz,X86::VANDNPDZ128rmbkz,
7999     X86::VPANDNQZ128rmbkz,X86::VPANDNDZ128rmbkz},
8000   { X86::VANDPSZ128rmbkz, X86::VANDPDZ128rmbkz,
8001     X86::VPANDQZ128rmbkz, X86::VPANDDZ128rmbkz },
8002   { X86::VORPSZ128rmbkz,  X86::VORPDZ128rmbkz,
8003     X86::VPORQZ128rmbkz,  X86::VPORDZ128rmbkz  },
8004   { X86::VXORPSZ128rmbkz, X86::VXORPDZ128rmbkz,
8005     X86::VPXORQZ128rmbkz, X86::VPXORDZ128rmbkz },
8006   { X86::VANDNPSZ256rmbkz,X86::VANDNPDZ256rmbkz,
8007     X86::VPANDNQZ256rmbkz,X86::VPANDNDZ256rmbkz},
8008   { X86::VANDPSZ256rmbkz, X86::VANDPDZ256rmbkz,
8009     X86::VPANDQZ256rmbkz, X86::VPANDDZ256rmbkz },
8010   { X86::VORPSZ256rmbkz,  X86::VORPDZ256rmbkz,
8011     X86::VPORQZ256rmbkz,  X86::VPORDZ256rmbkz  },
8012   { X86::VXORPSZ256rmbkz, X86::VXORPDZ256rmbkz,
8013     X86::VPXORQZ256rmbkz, X86::VPXORDZ256rmbkz },
8014   { X86::VANDNPSZrmbkz,   X86::VANDNPDZrmbkz,
8015     X86::VPANDNQZrmbkz,   X86::VPANDNDZrmbkz   },
8016   { X86::VANDPSZrmbkz,    X86::VANDPDZrmbkz,
8017     X86::VPANDQZrmbkz,    X86::VPANDDZrmbkz    },
8018   { X86::VANDPSZrmbkz,    X86::VANDPDZrmbkz,
8019     X86::VPANDQZrmbkz,    X86::VPANDDZrmbkz    },
8020   { X86::VORPSZrmbkz,     X86::VORPDZrmbkz,
8021     X86::VPORQZrmbkz,     X86::VPORDZrmbkz     },
8022   { X86::VXORPSZrmbkz,    X86::VXORPDZrmbkz,
8023     X86::VPXORQZrmbkz,    X86::VPXORDZrmbkz    },
8024 };
8025 
8026 // NOTE: These should only be used by the custom domain methods.
8027 static const uint16_t ReplaceableBlendInstrs[][3] = {
8028   //PackedSingle             PackedDouble             PackedInt
8029   { X86::BLENDPSrmi,         X86::BLENDPDrmi,         X86::PBLENDWrmi   },
8030   { X86::BLENDPSrri,         X86::BLENDPDrri,         X86::PBLENDWrri   },
8031   { X86::VBLENDPSrmi,        X86::VBLENDPDrmi,        X86::VPBLENDWrmi  },
8032   { X86::VBLENDPSrri,        X86::VBLENDPDrri,        X86::VPBLENDWrri  },
8033   { X86::VBLENDPSYrmi,       X86::VBLENDPDYrmi,       X86::VPBLENDWYrmi },
8034   { X86::VBLENDPSYrri,       X86::VBLENDPDYrri,       X86::VPBLENDWYrri },
8035 };
8036 static const uint16_t ReplaceableBlendAVX2Instrs[][3] = {
8037   //PackedSingle             PackedDouble             PackedInt
8038   { X86::VBLENDPSrmi,        X86::VBLENDPDrmi,        X86::VPBLENDDrmi  },
8039   { X86::VBLENDPSrri,        X86::VBLENDPDrri,        X86::VPBLENDDrri  },
8040   { X86::VBLENDPSYrmi,       X86::VBLENDPDYrmi,       X86::VPBLENDDYrmi },
8041   { X86::VBLENDPSYrri,       X86::VBLENDPDYrri,       X86::VPBLENDDYrri },
8042 };
8043 
8044 // Special table for changing EVEX logic instructions to VEX.
8045 // TODO: Should we run EVEX->VEX earlier?
8046 static const uint16_t ReplaceableCustomAVX512LogicInstrs[][4] = {
8047   // Two integer columns for 64-bit and 32-bit elements.
8048   //PackedSingle     PackedDouble     PackedInt           PackedInt
8049   { X86::VANDNPSrm,  X86::VANDNPDrm,  X86::VPANDNQZ128rm, X86::VPANDNDZ128rm },
8050   { X86::VANDNPSrr,  X86::VANDNPDrr,  X86::VPANDNQZ128rr, X86::VPANDNDZ128rr },
8051   { X86::VANDPSrm,   X86::VANDPDrm,   X86::VPANDQZ128rm,  X86::VPANDDZ128rm  },
8052   { X86::VANDPSrr,   X86::VANDPDrr,   X86::VPANDQZ128rr,  X86::VPANDDZ128rr  },
8053   { X86::VORPSrm,    X86::VORPDrm,    X86::VPORQZ128rm,   X86::VPORDZ128rm   },
8054   { X86::VORPSrr,    X86::VORPDrr,    X86::VPORQZ128rr,   X86::VPORDZ128rr   },
8055   { X86::VXORPSrm,   X86::VXORPDrm,   X86::VPXORQZ128rm,  X86::VPXORDZ128rm  },
8056   { X86::VXORPSrr,   X86::VXORPDrr,   X86::VPXORQZ128rr,  X86::VPXORDZ128rr  },
8057   { X86::VANDNPSYrm, X86::VANDNPDYrm, X86::VPANDNQZ256rm, X86::VPANDNDZ256rm },
8058   { X86::VANDNPSYrr, X86::VANDNPDYrr, X86::VPANDNQZ256rr, X86::VPANDNDZ256rr },
8059   { X86::VANDPSYrm,  X86::VANDPDYrm,  X86::VPANDQZ256rm,  X86::VPANDDZ256rm  },
8060   { X86::VANDPSYrr,  X86::VANDPDYrr,  X86::VPANDQZ256rr,  X86::VPANDDZ256rr  },
8061   { X86::VORPSYrm,   X86::VORPDYrm,   X86::VPORQZ256rm,   X86::VPORDZ256rm   },
8062   { X86::VORPSYrr,   X86::VORPDYrr,   X86::VPORQZ256rr,   X86::VPORDZ256rr   },
8063   { X86::VXORPSYrm,  X86::VXORPDYrm,  X86::VPXORQZ256rm,  X86::VPXORDZ256rm  },
8064   { X86::VXORPSYrr,  X86::VXORPDYrr,  X86::VPXORQZ256rr,  X86::VPXORDZ256rr  },
8065 };
8066 
8067 // FIXME: Some shuffle and unpack instructions have equivalents in different
8068 // domains, but they require a bit more work than just switching opcodes.
8069 
8070 static const uint16_t *lookup(unsigned opcode, unsigned domain,
8071                               ArrayRef<uint16_t[3]> Table) {
8072   for (const uint16_t (&Row)[3] : Table)
8073     if (Row[domain-1] == opcode)
8074       return Row;
8075   return nullptr;
8076 }
8077 
8078 static const uint16_t *lookupAVX512(unsigned opcode, unsigned domain,
8079                                     ArrayRef<uint16_t[4]> Table) {
8080   // If this is the integer domain make sure to check both integer columns.
8081   for (const uint16_t (&Row)[4] : Table)
8082     if (Row[domain-1] == opcode || (domain == 3 && Row[3] == opcode))
8083       return Row;
8084   return nullptr;
8085 }
8086 
8087 // Helper to attempt to widen/narrow blend masks.
8088 static bool AdjustBlendMask(unsigned OldMask, unsigned OldWidth,
8089                             unsigned NewWidth, unsigned *pNewMask = nullptr) {
8090   assert(((OldWidth % NewWidth) == 0 || (NewWidth % OldWidth) == 0) &&
8091          "Illegal blend mask scale");
8092   unsigned NewMask = 0;
8093 
8094   if ((OldWidth % NewWidth) == 0) {
8095     unsigned Scale = OldWidth / NewWidth;
8096     unsigned SubMask = (1u << Scale) - 1;
8097     for (unsigned i = 0; i != NewWidth; ++i) {
8098       unsigned Sub = (OldMask >> (i * Scale)) & SubMask;
8099       if (Sub == SubMask)
8100         NewMask |= (1u << i);
8101       else if (Sub != 0x0)
8102         return false;
8103     }
8104   } else {
8105     unsigned Scale = NewWidth / OldWidth;
8106     unsigned SubMask = (1u << Scale) - 1;
8107     for (unsigned i = 0; i != OldWidth; ++i) {
8108       if (OldMask & (1 << i)) {
8109         NewMask |= (SubMask << (i * Scale));
8110       }
8111     }
8112   }
8113 
8114   if (pNewMask)
8115     *pNewMask = NewMask;
8116   return true;
8117 }
8118 
8119 uint16_t X86InstrInfo::getExecutionDomainCustom(const MachineInstr &MI) const {
8120   unsigned Opcode = MI.getOpcode();
8121   unsigned NumOperands = MI.getDesc().getNumOperands();
8122 
8123   auto GetBlendDomains = [&](unsigned ImmWidth, bool Is256) {
8124     uint16_t validDomains = 0;
8125     if (MI.getOperand(NumOperands - 1).isImm()) {
8126       unsigned Imm = MI.getOperand(NumOperands - 1).getImm();
8127       if (AdjustBlendMask(Imm, ImmWidth, Is256 ? 8 : 4))
8128         validDomains |= 0x2; // PackedSingle
8129       if (AdjustBlendMask(Imm, ImmWidth, Is256 ? 4 : 2))
8130         validDomains |= 0x4; // PackedDouble
8131       if (!Is256 || Subtarget.hasAVX2())
8132         validDomains |= 0x8; // PackedInt
8133     }
8134     return validDomains;
8135   };
8136 
8137   switch (Opcode) {
8138   case X86::BLENDPDrmi:
8139   case X86::BLENDPDrri:
8140   case X86::VBLENDPDrmi:
8141   case X86::VBLENDPDrri:
8142     return GetBlendDomains(2, false);
8143   case X86::VBLENDPDYrmi:
8144   case X86::VBLENDPDYrri:
8145     return GetBlendDomains(4, true);
8146   case X86::BLENDPSrmi:
8147   case X86::BLENDPSrri:
8148   case X86::VBLENDPSrmi:
8149   case X86::VBLENDPSrri:
8150   case X86::VPBLENDDrmi:
8151   case X86::VPBLENDDrri:
8152     return GetBlendDomains(4, false);
8153   case X86::VBLENDPSYrmi:
8154   case X86::VBLENDPSYrri:
8155   case X86::VPBLENDDYrmi:
8156   case X86::VPBLENDDYrri:
8157     return GetBlendDomains(8, true);
8158   case X86::PBLENDWrmi:
8159   case X86::PBLENDWrri:
8160   case X86::VPBLENDWrmi:
8161   case X86::VPBLENDWrri:
8162   // Treat VPBLENDWY as a 128-bit vector as it repeats the lo/hi masks.
8163   case X86::VPBLENDWYrmi:
8164   case X86::VPBLENDWYrri:
8165     return GetBlendDomains(8, false);
8166   case X86::VPANDDZ128rr:  case X86::VPANDDZ128rm:
8167   case X86::VPANDDZ256rr:  case X86::VPANDDZ256rm:
8168   case X86::VPANDQZ128rr:  case X86::VPANDQZ128rm:
8169   case X86::VPANDQZ256rr:  case X86::VPANDQZ256rm:
8170   case X86::VPANDNDZ128rr: case X86::VPANDNDZ128rm:
8171   case X86::VPANDNDZ256rr: case X86::VPANDNDZ256rm:
8172   case X86::VPANDNQZ128rr: case X86::VPANDNQZ128rm:
8173   case X86::VPANDNQZ256rr: case X86::VPANDNQZ256rm:
8174   case X86::VPORDZ128rr:   case X86::VPORDZ128rm:
8175   case X86::VPORDZ256rr:   case X86::VPORDZ256rm:
8176   case X86::VPORQZ128rr:   case X86::VPORQZ128rm:
8177   case X86::VPORQZ256rr:   case X86::VPORQZ256rm:
8178   case X86::VPXORDZ128rr:  case X86::VPXORDZ128rm:
8179   case X86::VPXORDZ256rr:  case X86::VPXORDZ256rm:
8180   case X86::VPXORQZ128rr:  case X86::VPXORQZ128rm:
8181   case X86::VPXORQZ256rr:  case X86::VPXORQZ256rm:
8182     // If we don't have DQI see if we can still switch from an EVEX integer
8183     // instruction to a VEX floating point instruction.
8184     if (Subtarget.hasDQI())
8185       return 0;
8186 
8187     if (RI.getEncodingValue(MI.getOperand(0).getReg()) >= 16)
8188       return 0;
8189     if (RI.getEncodingValue(MI.getOperand(1).getReg()) >= 16)
8190       return 0;
8191     // Register forms will have 3 operands. Memory form will have more.
8192     if (NumOperands == 3 &&
8193         RI.getEncodingValue(MI.getOperand(2).getReg()) >= 16)
8194       return 0;
8195 
8196     // All domains are valid.
8197     return 0xe;
8198   case X86::MOVHLPSrr:
8199     // We can swap domains when both inputs are the same register.
8200     // FIXME: This doesn't catch all the cases we would like. If the input
8201     // register isn't KILLed by the instruction, the two address instruction
8202     // pass puts a COPY on one input. The other input uses the original
8203     // register. This prevents the same physical register from being used by
8204     // both inputs.
8205     if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg() &&
8206         MI.getOperand(0).getSubReg() == 0 &&
8207         MI.getOperand(1).getSubReg() == 0 &&
8208         MI.getOperand(2).getSubReg() == 0)
8209       return 0x6;
8210     return 0;
8211   case X86::SHUFPDrri:
8212     return 0x6;
8213   }
8214   return 0;
8215 }
8216 
8217 bool X86InstrInfo::setExecutionDomainCustom(MachineInstr &MI,
8218                                             unsigned Domain) const {
8219   assert(Domain > 0 && Domain < 4 && "Invalid execution domain");
8220   uint16_t dom = (MI.getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
8221   assert(dom && "Not an SSE instruction");
8222 
8223   unsigned Opcode = MI.getOpcode();
8224   unsigned NumOperands = MI.getDesc().getNumOperands();
8225 
8226   auto SetBlendDomain = [&](unsigned ImmWidth, bool Is256) {
8227     if (MI.getOperand(NumOperands - 1).isImm()) {
8228       unsigned Imm = MI.getOperand(NumOperands - 1).getImm() & 255;
8229       Imm = (ImmWidth == 16 ? ((Imm << 8) | Imm) : Imm);
8230       unsigned NewImm = Imm;
8231 
8232       const uint16_t *table = lookup(Opcode, dom, ReplaceableBlendInstrs);
8233       if (!table)
8234         table = lookup(Opcode, dom, ReplaceableBlendAVX2Instrs);
8235 
8236       if (Domain == 1) { // PackedSingle
8237         AdjustBlendMask(Imm, ImmWidth, Is256 ? 8 : 4, &NewImm);
8238       } else if (Domain == 2) { // PackedDouble
8239         AdjustBlendMask(Imm, ImmWidth, Is256 ? 4 : 2, &NewImm);
8240       } else if (Domain == 3) { // PackedInt
8241         if (Subtarget.hasAVX2()) {
8242           // If we are already VPBLENDW use that, else use VPBLENDD.
8243           if ((ImmWidth / (Is256 ? 2 : 1)) != 8) {
8244             table = lookup(Opcode, dom, ReplaceableBlendAVX2Instrs);
8245             AdjustBlendMask(Imm, ImmWidth, Is256 ? 8 : 4, &NewImm);
8246           }
8247         } else {
8248           assert(!Is256 && "128-bit vector expected");
8249           AdjustBlendMask(Imm, ImmWidth, 8, &NewImm);
8250         }
8251       }
8252 
8253       assert(table && table[Domain - 1] && "Unknown domain op");
8254       MI.setDesc(get(table[Domain - 1]));
8255       MI.getOperand(NumOperands - 1).setImm(NewImm & 255);
8256     }
8257     return true;
8258   };
8259 
8260   switch (Opcode) {
8261   case X86::BLENDPDrmi:
8262   case X86::BLENDPDrri:
8263   case X86::VBLENDPDrmi:
8264   case X86::VBLENDPDrri:
8265     return SetBlendDomain(2, false);
8266   case X86::VBLENDPDYrmi:
8267   case X86::VBLENDPDYrri:
8268     return SetBlendDomain(4, true);
8269   case X86::BLENDPSrmi:
8270   case X86::BLENDPSrri:
8271   case X86::VBLENDPSrmi:
8272   case X86::VBLENDPSrri:
8273   case X86::VPBLENDDrmi:
8274   case X86::VPBLENDDrri:
8275     return SetBlendDomain(4, false);
8276   case X86::VBLENDPSYrmi:
8277   case X86::VBLENDPSYrri:
8278   case X86::VPBLENDDYrmi:
8279   case X86::VPBLENDDYrri:
8280     return SetBlendDomain(8, true);
8281   case X86::PBLENDWrmi:
8282   case X86::PBLENDWrri:
8283   case X86::VPBLENDWrmi:
8284   case X86::VPBLENDWrri:
8285     return SetBlendDomain(8, false);
8286   case X86::VPBLENDWYrmi:
8287   case X86::VPBLENDWYrri:
8288     return SetBlendDomain(16, true);
8289   case X86::VPANDDZ128rr:  case X86::VPANDDZ128rm:
8290   case X86::VPANDDZ256rr:  case X86::VPANDDZ256rm:
8291   case X86::VPANDQZ128rr:  case X86::VPANDQZ128rm:
8292   case X86::VPANDQZ256rr:  case X86::VPANDQZ256rm:
8293   case X86::VPANDNDZ128rr: case X86::VPANDNDZ128rm:
8294   case X86::VPANDNDZ256rr: case X86::VPANDNDZ256rm:
8295   case X86::VPANDNQZ128rr: case X86::VPANDNQZ128rm:
8296   case X86::VPANDNQZ256rr: case X86::VPANDNQZ256rm:
8297   case X86::VPORDZ128rr:   case X86::VPORDZ128rm:
8298   case X86::VPORDZ256rr:   case X86::VPORDZ256rm:
8299   case X86::VPORQZ128rr:   case X86::VPORQZ128rm:
8300   case X86::VPORQZ256rr:   case X86::VPORQZ256rm:
8301   case X86::VPXORDZ128rr:  case X86::VPXORDZ128rm:
8302   case X86::VPXORDZ256rr:  case X86::VPXORDZ256rm:
8303   case X86::VPXORQZ128rr:  case X86::VPXORQZ128rm:
8304   case X86::VPXORQZ256rr:  case X86::VPXORQZ256rm: {
8305     // Without DQI, convert EVEX instructions to VEX instructions.
8306     if (Subtarget.hasDQI())
8307       return false;
8308 
8309     const uint16_t *table = lookupAVX512(MI.getOpcode(), dom,
8310                                          ReplaceableCustomAVX512LogicInstrs);
8311     assert(table && "Instruction not found in table?");
8312     // Don't change integer Q instructions to D instructions and
8313     // use D intructions if we started with a PS instruction.
8314     if (Domain == 3 && (dom == 1 || table[3] == MI.getOpcode()))
8315       Domain = 4;
8316     MI.setDesc(get(table[Domain - 1]));
8317     return true;
8318   }
8319   case X86::UNPCKHPDrr:
8320   case X86::MOVHLPSrr:
8321     // We just need to commute the instruction which will switch the domains.
8322     if (Domain != dom && Domain != 3 &&
8323         MI.getOperand(1).getReg() == MI.getOperand(2).getReg() &&
8324         MI.getOperand(0).getSubReg() == 0 &&
8325         MI.getOperand(1).getSubReg() == 0 &&
8326         MI.getOperand(2).getSubReg() == 0) {
8327       commuteInstruction(MI, false);
8328       return true;
8329     }
8330     // We must always return true for MOVHLPSrr.
8331     if (Opcode == X86::MOVHLPSrr)
8332       return true;
8333     break;
8334   case X86::SHUFPDrri: {
8335     if (Domain == 1) {
8336       unsigned Imm = MI.getOperand(3).getImm();
8337       unsigned NewImm = 0x44;
8338       if (Imm & 1) NewImm |= 0x0a;
8339       if (Imm & 2) NewImm |= 0xa0;
8340       MI.getOperand(3).setImm(NewImm);
8341       MI.setDesc(get(X86::SHUFPSrri));
8342     }
8343     return true;
8344   }
8345   }
8346   return false;
8347 }
8348 
8349 std::pair<uint16_t, uint16_t>
8350 X86InstrInfo::getExecutionDomain(const MachineInstr &MI) const {
8351   uint16_t domain = (MI.getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
8352   unsigned opcode = MI.getOpcode();
8353   uint16_t validDomains = 0;
8354   if (domain) {
8355     // Attempt to match for custom instructions.
8356     validDomains = getExecutionDomainCustom(MI);
8357     if (validDomains)
8358       return std::make_pair(domain, validDomains);
8359 
8360     if (lookup(opcode, domain, ReplaceableInstrs)) {
8361       validDomains = 0xe;
8362     } else if (lookup(opcode, domain, ReplaceableInstrsAVX2)) {
8363       validDomains = Subtarget.hasAVX2() ? 0xe : 0x6;
8364     } else if (lookup(opcode, domain, ReplaceableInstrsFP)) {
8365       validDomains = 0x6;
8366     } else if (lookup(opcode, domain, ReplaceableInstrsAVX2InsertExtract)) {
8367       // Insert/extract instructions should only effect domain if AVX2
8368       // is enabled.
8369       if (!Subtarget.hasAVX2())
8370         return std::make_pair(0, 0);
8371       validDomains = 0xe;
8372     } else if (lookupAVX512(opcode, domain, ReplaceableInstrsAVX512)) {
8373       validDomains = 0xe;
8374     } else if (Subtarget.hasDQI() && lookupAVX512(opcode, domain,
8375                                                   ReplaceableInstrsAVX512DQ)) {
8376       validDomains = 0xe;
8377     } else if (Subtarget.hasDQI()) {
8378       if (const uint16_t *table = lookupAVX512(opcode, domain,
8379                                              ReplaceableInstrsAVX512DQMasked)) {
8380         if (domain == 1 || (domain == 3 && table[3] == opcode))
8381           validDomains = 0xa;
8382         else
8383           validDomains = 0xc;
8384       }
8385     }
8386   }
8387   return std::make_pair(domain, validDomains);
8388 }
8389 
8390 void X86InstrInfo::setExecutionDomain(MachineInstr &MI, unsigned Domain) const {
8391   assert(Domain>0 && Domain<4 && "Invalid execution domain");
8392   uint16_t dom = (MI.getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
8393   assert(dom && "Not an SSE instruction");
8394 
8395   // Attempt to match for custom instructions.
8396   if (setExecutionDomainCustom(MI, Domain))
8397     return;
8398 
8399   const uint16_t *table = lookup(MI.getOpcode(), dom, ReplaceableInstrs);
8400   if (!table) { // try the other table
8401     assert((Subtarget.hasAVX2() || Domain < 3) &&
8402            "256-bit vector operations only available in AVX2");
8403     table = lookup(MI.getOpcode(), dom, ReplaceableInstrsAVX2);
8404   }
8405   if (!table) { // try the FP table
8406     table = lookup(MI.getOpcode(), dom, ReplaceableInstrsFP);
8407     assert((!table || Domain < 3) &&
8408            "Can only select PackedSingle or PackedDouble");
8409   }
8410   if (!table) { // try the other table
8411     assert(Subtarget.hasAVX2() &&
8412            "256-bit insert/extract only available in AVX2");
8413     table = lookup(MI.getOpcode(), dom, ReplaceableInstrsAVX2InsertExtract);
8414   }
8415   if (!table) { // try the AVX512 table
8416     assert(Subtarget.hasAVX512() && "Requires AVX-512");
8417     table = lookupAVX512(MI.getOpcode(), dom, ReplaceableInstrsAVX512);
8418     // Don't change integer Q instructions to D instructions.
8419     if (table && Domain == 3 && table[3] == MI.getOpcode())
8420       Domain = 4;
8421   }
8422   if (!table) { // try the AVX512DQ table
8423     assert((Subtarget.hasDQI() || Domain >= 3) && "Requires AVX-512DQ");
8424     table = lookupAVX512(MI.getOpcode(), dom, ReplaceableInstrsAVX512DQ);
8425     // Don't change integer Q instructions to D instructions and
8426     // use D instructions if we started with a PS instruction.
8427     if (table && Domain == 3 && (dom == 1 || table[3] == MI.getOpcode()))
8428       Domain = 4;
8429   }
8430   if (!table) { // try the AVX512DQMasked table
8431     assert((Subtarget.hasDQI() || Domain >= 3) && "Requires AVX-512DQ");
8432     table = lookupAVX512(MI.getOpcode(), dom, ReplaceableInstrsAVX512DQMasked);
8433     if (table && Domain == 3 && (dom == 1 || table[3] == MI.getOpcode()))
8434       Domain = 4;
8435   }
8436   assert(table && "Cannot change domain");
8437   MI.setDesc(get(table[Domain - 1]));
8438 }
8439 
8440 /// Return the noop instruction to use for a noop.
8441 MCInst X86InstrInfo::getNop() const {
8442   MCInst Nop;
8443   Nop.setOpcode(X86::NOOP);
8444   return Nop;
8445 }
8446 
8447 bool X86InstrInfo::isHighLatencyDef(int opc) const {
8448   switch (opc) {
8449   default: return false;
8450   case X86::DIVPDrm:
8451   case X86::DIVPDrr:
8452   case X86::DIVPSrm:
8453   case X86::DIVPSrr:
8454   case X86::DIVSDrm:
8455   case X86::DIVSDrm_Int:
8456   case X86::DIVSDrr:
8457   case X86::DIVSDrr_Int:
8458   case X86::DIVSSrm:
8459   case X86::DIVSSrm_Int:
8460   case X86::DIVSSrr:
8461   case X86::DIVSSrr_Int:
8462   case X86::SQRTPDm:
8463   case X86::SQRTPDr:
8464   case X86::SQRTPSm:
8465   case X86::SQRTPSr:
8466   case X86::SQRTSDm:
8467   case X86::SQRTSDm_Int:
8468   case X86::SQRTSDr:
8469   case X86::SQRTSDr_Int:
8470   case X86::SQRTSSm:
8471   case X86::SQRTSSm_Int:
8472   case X86::SQRTSSr:
8473   case X86::SQRTSSr_Int:
8474   // AVX instructions with high latency
8475   case X86::VDIVPDrm:
8476   case X86::VDIVPDrr:
8477   case X86::VDIVPDYrm:
8478   case X86::VDIVPDYrr:
8479   case X86::VDIVPSrm:
8480   case X86::VDIVPSrr:
8481   case X86::VDIVPSYrm:
8482   case X86::VDIVPSYrr:
8483   case X86::VDIVSDrm:
8484   case X86::VDIVSDrm_Int:
8485   case X86::VDIVSDrr:
8486   case X86::VDIVSDrr_Int:
8487   case X86::VDIVSSrm:
8488   case X86::VDIVSSrm_Int:
8489   case X86::VDIVSSrr:
8490   case X86::VDIVSSrr_Int:
8491   case X86::VSQRTPDm:
8492   case X86::VSQRTPDr:
8493   case X86::VSQRTPDYm:
8494   case X86::VSQRTPDYr:
8495   case X86::VSQRTPSm:
8496   case X86::VSQRTPSr:
8497   case X86::VSQRTPSYm:
8498   case X86::VSQRTPSYr:
8499   case X86::VSQRTSDm:
8500   case X86::VSQRTSDm_Int:
8501   case X86::VSQRTSDr:
8502   case X86::VSQRTSDr_Int:
8503   case X86::VSQRTSSm:
8504   case X86::VSQRTSSm_Int:
8505   case X86::VSQRTSSr:
8506   case X86::VSQRTSSr_Int:
8507   // AVX512 instructions with high latency
8508   case X86::VDIVPDZ128rm:
8509   case X86::VDIVPDZ128rmb:
8510   case X86::VDIVPDZ128rmbk:
8511   case X86::VDIVPDZ128rmbkz:
8512   case X86::VDIVPDZ128rmk:
8513   case X86::VDIVPDZ128rmkz:
8514   case X86::VDIVPDZ128rr:
8515   case X86::VDIVPDZ128rrk:
8516   case X86::VDIVPDZ128rrkz:
8517   case X86::VDIVPDZ256rm:
8518   case X86::VDIVPDZ256rmb:
8519   case X86::VDIVPDZ256rmbk:
8520   case X86::VDIVPDZ256rmbkz:
8521   case X86::VDIVPDZ256rmk:
8522   case X86::VDIVPDZ256rmkz:
8523   case X86::VDIVPDZ256rr:
8524   case X86::VDIVPDZ256rrk:
8525   case X86::VDIVPDZ256rrkz:
8526   case X86::VDIVPDZrrb:
8527   case X86::VDIVPDZrrbk:
8528   case X86::VDIVPDZrrbkz:
8529   case X86::VDIVPDZrm:
8530   case X86::VDIVPDZrmb:
8531   case X86::VDIVPDZrmbk:
8532   case X86::VDIVPDZrmbkz:
8533   case X86::VDIVPDZrmk:
8534   case X86::VDIVPDZrmkz:
8535   case X86::VDIVPDZrr:
8536   case X86::VDIVPDZrrk:
8537   case X86::VDIVPDZrrkz:
8538   case X86::VDIVPSZ128rm:
8539   case X86::VDIVPSZ128rmb:
8540   case X86::VDIVPSZ128rmbk:
8541   case X86::VDIVPSZ128rmbkz:
8542   case X86::VDIVPSZ128rmk:
8543   case X86::VDIVPSZ128rmkz:
8544   case X86::VDIVPSZ128rr:
8545   case X86::VDIVPSZ128rrk:
8546   case X86::VDIVPSZ128rrkz:
8547   case X86::VDIVPSZ256rm:
8548   case X86::VDIVPSZ256rmb:
8549   case X86::VDIVPSZ256rmbk:
8550   case X86::VDIVPSZ256rmbkz:
8551   case X86::VDIVPSZ256rmk:
8552   case X86::VDIVPSZ256rmkz:
8553   case X86::VDIVPSZ256rr:
8554   case X86::VDIVPSZ256rrk:
8555   case X86::VDIVPSZ256rrkz:
8556   case X86::VDIVPSZrrb:
8557   case X86::VDIVPSZrrbk:
8558   case X86::VDIVPSZrrbkz:
8559   case X86::VDIVPSZrm:
8560   case X86::VDIVPSZrmb:
8561   case X86::VDIVPSZrmbk:
8562   case X86::VDIVPSZrmbkz:
8563   case X86::VDIVPSZrmk:
8564   case X86::VDIVPSZrmkz:
8565   case X86::VDIVPSZrr:
8566   case X86::VDIVPSZrrk:
8567   case X86::VDIVPSZrrkz:
8568   case X86::VDIVSDZrm:
8569   case X86::VDIVSDZrr:
8570   case X86::VDIVSDZrm_Int:
8571   case X86::VDIVSDZrm_Intk:
8572   case X86::VDIVSDZrm_Intkz:
8573   case X86::VDIVSDZrr_Int:
8574   case X86::VDIVSDZrr_Intk:
8575   case X86::VDIVSDZrr_Intkz:
8576   case X86::VDIVSDZrrb_Int:
8577   case X86::VDIVSDZrrb_Intk:
8578   case X86::VDIVSDZrrb_Intkz:
8579   case X86::VDIVSSZrm:
8580   case X86::VDIVSSZrr:
8581   case X86::VDIVSSZrm_Int:
8582   case X86::VDIVSSZrm_Intk:
8583   case X86::VDIVSSZrm_Intkz:
8584   case X86::VDIVSSZrr_Int:
8585   case X86::VDIVSSZrr_Intk:
8586   case X86::VDIVSSZrr_Intkz:
8587   case X86::VDIVSSZrrb_Int:
8588   case X86::VDIVSSZrrb_Intk:
8589   case X86::VDIVSSZrrb_Intkz:
8590   case X86::VSQRTPDZ128m:
8591   case X86::VSQRTPDZ128mb:
8592   case X86::VSQRTPDZ128mbk:
8593   case X86::VSQRTPDZ128mbkz:
8594   case X86::VSQRTPDZ128mk:
8595   case X86::VSQRTPDZ128mkz:
8596   case X86::VSQRTPDZ128r:
8597   case X86::VSQRTPDZ128rk:
8598   case X86::VSQRTPDZ128rkz:
8599   case X86::VSQRTPDZ256m:
8600   case X86::VSQRTPDZ256mb:
8601   case X86::VSQRTPDZ256mbk:
8602   case X86::VSQRTPDZ256mbkz:
8603   case X86::VSQRTPDZ256mk:
8604   case X86::VSQRTPDZ256mkz:
8605   case X86::VSQRTPDZ256r:
8606   case X86::VSQRTPDZ256rk:
8607   case X86::VSQRTPDZ256rkz:
8608   case X86::VSQRTPDZm:
8609   case X86::VSQRTPDZmb:
8610   case X86::VSQRTPDZmbk:
8611   case X86::VSQRTPDZmbkz:
8612   case X86::VSQRTPDZmk:
8613   case X86::VSQRTPDZmkz:
8614   case X86::VSQRTPDZr:
8615   case X86::VSQRTPDZrb:
8616   case X86::VSQRTPDZrbk:
8617   case X86::VSQRTPDZrbkz:
8618   case X86::VSQRTPDZrk:
8619   case X86::VSQRTPDZrkz:
8620   case X86::VSQRTPSZ128m:
8621   case X86::VSQRTPSZ128mb:
8622   case X86::VSQRTPSZ128mbk:
8623   case X86::VSQRTPSZ128mbkz:
8624   case X86::VSQRTPSZ128mk:
8625   case X86::VSQRTPSZ128mkz:
8626   case X86::VSQRTPSZ128r:
8627   case X86::VSQRTPSZ128rk:
8628   case X86::VSQRTPSZ128rkz:
8629   case X86::VSQRTPSZ256m:
8630   case X86::VSQRTPSZ256mb:
8631   case X86::VSQRTPSZ256mbk:
8632   case X86::VSQRTPSZ256mbkz:
8633   case X86::VSQRTPSZ256mk:
8634   case X86::VSQRTPSZ256mkz:
8635   case X86::VSQRTPSZ256r:
8636   case X86::VSQRTPSZ256rk:
8637   case X86::VSQRTPSZ256rkz:
8638   case X86::VSQRTPSZm:
8639   case X86::VSQRTPSZmb:
8640   case X86::VSQRTPSZmbk:
8641   case X86::VSQRTPSZmbkz:
8642   case X86::VSQRTPSZmk:
8643   case X86::VSQRTPSZmkz:
8644   case X86::VSQRTPSZr:
8645   case X86::VSQRTPSZrb:
8646   case X86::VSQRTPSZrbk:
8647   case X86::VSQRTPSZrbkz:
8648   case X86::VSQRTPSZrk:
8649   case X86::VSQRTPSZrkz:
8650   case X86::VSQRTSDZm:
8651   case X86::VSQRTSDZm_Int:
8652   case X86::VSQRTSDZm_Intk:
8653   case X86::VSQRTSDZm_Intkz:
8654   case X86::VSQRTSDZr:
8655   case X86::VSQRTSDZr_Int:
8656   case X86::VSQRTSDZr_Intk:
8657   case X86::VSQRTSDZr_Intkz:
8658   case X86::VSQRTSDZrb_Int:
8659   case X86::VSQRTSDZrb_Intk:
8660   case X86::VSQRTSDZrb_Intkz:
8661   case X86::VSQRTSSZm:
8662   case X86::VSQRTSSZm_Int:
8663   case X86::VSQRTSSZm_Intk:
8664   case X86::VSQRTSSZm_Intkz:
8665   case X86::VSQRTSSZr:
8666   case X86::VSQRTSSZr_Int:
8667   case X86::VSQRTSSZr_Intk:
8668   case X86::VSQRTSSZr_Intkz:
8669   case X86::VSQRTSSZrb_Int:
8670   case X86::VSQRTSSZrb_Intk:
8671   case X86::VSQRTSSZrb_Intkz:
8672 
8673   case X86::VGATHERDPDYrm:
8674   case X86::VGATHERDPDZ128rm:
8675   case X86::VGATHERDPDZ256rm:
8676   case X86::VGATHERDPDZrm:
8677   case X86::VGATHERDPDrm:
8678   case X86::VGATHERDPSYrm:
8679   case X86::VGATHERDPSZ128rm:
8680   case X86::VGATHERDPSZ256rm:
8681   case X86::VGATHERDPSZrm:
8682   case X86::VGATHERDPSrm:
8683   case X86::VGATHERPF0DPDm:
8684   case X86::VGATHERPF0DPSm:
8685   case X86::VGATHERPF0QPDm:
8686   case X86::VGATHERPF0QPSm:
8687   case X86::VGATHERPF1DPDm:
8688   case X86::VGATHERPF1DPSm:
8689   case X86::VGATHERPF1QPDm:
8690   case X86::VGATHERPF1QPSm:
8691   case X86::VGATHERQPDYrm:
8692   case X86::VGATHERQPDZ128rm:
8693   case X86::VGATHERQPDZ256rm:
8694   case X86::VGATHERQPDZrm:
8695   case X86::VGATHERQPDrm:
8696   case X86::VGATHERQPSYrm:
8697   case X86::VGATHERQPSZ128rm:
8698   case X86::VGATHERQPSZ256rm:
8699   case X86::VGATHERQPSZrm:
8700   case X86::VGATHERQPSrm:
8701   case X86::VPGATHERDDYrm:
8702   case X86::VPGATHERDDZ128rm:
8703   case X86::VPGATHERDDZ256rm:
8704   case X86::VPGATHERDDZrm:
8705   case X86::VPGATHERDDrm:
8706   case X86::VPGATHERDQYrm:
8707   case X86::VPGATHERDQZ128rm:
8708   case X86::VPGATHERDQZ256rm:
8709   case X86::VPGATHERDQZrm:
8710   case X86::VPGATHERDQrm:
8711   case X86::VPGATHERQDYrm:
8712   case X86::VPGATHERQDZ128rm:
8713   case X86::VPGATHERQDZ256rm:
8714   case X86::VPGATHERQDZrm:
8715   case X86::VPGATHERQDrm:
8716   case X86::VPGATHERQQYrm:
8717   case X86::VPGATHERQQZ128rm:
8718   case X86::VPGATHERQQZ256rm:
8719   case X86::VPGATHERQQZrm:
8720   case X86::VPGATHERQQrm:
8721   case X86::VSCATTERDPDZ128mr:
8722   case X86::VSCATTERDPDZ256mr:
8723   case X86::VSCATTERDPDZmr:
8724   case X86::VSCATTERDPSZ128mr:
8725   case X86::VSCATTERDPSZ256mr:
8726   case X86::VSCATTERDPSZmr:
8727   case X86::VSCATTERPF0DPDm:
8728   case X86::VSCATTERPF0DPSm:
8729   case X86::VSCATTERPF0QPDm:
8730   case X86::VSCATTERPF0QPSm:
8731   case X86::VSCATTERPF1DPDm:
8732   case X86::VSCATTERPF1DPSm:
8733   case X86::VSCATTERPF1QPDm:
8734   case X86::VSCATTERPF1QPSm:
8735   case X86::VSCATTERQPDZ128mr:
8736   case X86::VSCATTERQPDZ256mr:
8737   case X86::VSCATTERQPDZmr:
8738   case X86::VSCATTERQPSZ128mr:
8739   case X86::VSCATTERQPSZ256mr:
8740   case X86::VSCATTERQPSZmr:
8741   case X86::VPSCATTERDDZ128mr:
8742   case X86::VPSCATTERDDZ256mr:
8743   case X86::VPSCATTERDDZmr:
8744   case X86::VPSCATTERDQZ128mr:
8745   case X86::VPSCATTERDQZ256mr:
8746   case X86::VPSCATTERDQZmr:
8747   case X86::VPSCATTERQDZ128mr:
8748   case X86::VPSCATTERQDZ256mr:
8749   case X86::VPSCATTERQDZmr:
8750   case X86::VPSCATTERQQZ128mr:
8751   case X86::VPSCATTERQQZ256mr:
8752   case X86::VPSCATTERQQZmr:
8753     return true;
8754   }
8755 }
8756 
8757 bool X86InstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
8758                                          const MachineRegisterInfo *MRI,
8759                                          const MachineInstr &DefMI,
8760                                          unsigned DefIdx,
8761                                          const MachineInstr &UseMI,
8762                                          unsigned UseIdx) const {
8763   return isHighLatencyDef(DefMI.getOpcode());
8764 }
8765 
8766 bool X86InstrInfo::hasReassociableOperands(const MachineInstr &Inst,
8767                                            const MachineBasicBlock *MBB) const {
8768   assert(Inst.getNumExplicitOperands() == 3 && Inst.getNumExplicitDefs() == 1 &&
8769          Inst.getNumDefs() <= 2 && "Reassociation needs binary operators");
8770 
8771   // Integer binary math/logic instructions have a third source operand:
8772   // the EFLAGS register. That operand must be both defined here and never
8773   // used; ie, it must be dead. If the EFLAGS operand is live, then we can
8774   // not change anything because rearranging the operands could affect other
8775   // instructions that depend on the exact status flags (zero, sign, etc.)
8776   // that are set by using these particular operands with this operation.
8777   const MachineOperand *FlagDef = Inst.findRegisterDefOperand(X86::EFLAGS);
8778   assert((Inst.getNumDefs() == 1 || FlagDef) &&
8779          "Implicit def isn't flags?");
8780   if (FlagDef && !FlagDef->isDead())
8781     return false;
8782 
8783   return TargetInstrInfo::hasReassociableOperands(Inst, MBB);
8784 }
8785 
8786 // TODO: There are many more machine instruction opcodes to match:
8787 //       1. Other data types (integer, vectors)
8788 //       2. Other math / logic operations (xor, or)
8789 //       3. Other forms of the same operation (intrinsics and other variants)
8790 bool X86InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
8791                                                bool Invert) const {
8792   if (Invert)
8793     return false;
8794   switch (Inst.getOpcode()) {
8795   case X86::ADD8rr:
8796   case X86::ADD16rr:
8797   case X86::ADD32rr:
8798   case X86::ADD64rr:
8799   case X86::AND8rr:
8800   case X86::AND16rr:
8801   case X86::AND32rr:
8802   case X86::AND64rr:
8803   case X86::OR8rr:
8804   case X86::OR16rr:
8805   case X86::OR32rr:
8806   case X86::OR64rr:
8807   case X86::XOR8rr:
8808   case X86::XOR16rr:
8809   case X86::XOR32rr:
8810   case X86::XOR64rr:
8811   case X86::IMUL16rr:
8812   case X86::IMUL32rr:
8813   case X86::IMUL64rr:
8814   case X86::PANDrr:
8815   case X86::PORrr:
8816   case X86::PXORrr:
8817   case X86::ANDPDrr:
8818   case X86::ANDPSrr:
8819   case X86::ORPDrr:
8820   case X86::ORPSrr:
8821   case X86::XORPDrr:
8822   case X86::XORPSrr:
8823   case X86::PADDBrr:
8824   case X86::PADDWrr:
8825   case X86::PADDDrr:
8826   case X86::PADDQrr:
8827   case X86::PMULLWrr:
8828   case X86::PMULLDrr:
8829   case X86::PMAXSBrr:
8830   case X86::PMAXSDrr:
8831   case X86::PMAXSWrr:
8832   case X86::PMAXUBrr:
8833   case X86::PMAXUDrr:
8834   case X86::PMAXUWrr:
8835   case X86::PMINSBrr:
8836   case X86::PMINSDrr:
8837   case X86::PMINSWrr:
8838   case X86::PMINUBrr:
8839   case X86::PMINUDrr:
8840   case X86::PMINUWrr:
8841   case X86::VPANDrr:
8842   case X86::VPANDYrr:
8843   case X86::VPANDDZ128rr:
8844   case X86::VPANDDZ256rr:
8845   case X86::VPANDDZrr:
8846   case X86::VPANDQZ128rr:
8847   case X86::VPANDQZ256rr:
8848   case X86::VPANDQZrr:
8849   case X86::VPORrr:
8850   case X86::VPORYrr:
8851   case X86::VPORDZ128rr:
8852   case X86::VPORDZ256rr:
8853   case X86::VPORDZrr:
8854   case X86::VPORQZ128rr:
8855   case X86::VPORQZ256rr:
8856   case X86::VPORQZrr:
8857   case X86::VPXORrr:
8858   case X86::VPXORYrr:
8859   case X86::VPXORDZ128rr:
8860   case X86::VPXORDZ256rr:
8861   case X86::VPXORDZrr:
8862   case X86::VPXORQZ128rr:
8863   case X86::VPXORQZ256rr:
8864   case X86::VPXORQZrr:
8865   case X86::VANDPDrr:
8866   case X86::VANDPSrr:
8867   case X86::VANDPDYrr:
8868   case X86::VANDPSYrr:
8869   case X86::VANDPDZ128rr:
8870   case X86::VANDPSZ128rr:
8871   case X86::VANDPDZ256rr:
8872   case X86::VANDPSZ256rr:
8873   case X86::VANDPDZrr:
8874   case X86::VANDPSZrr:
8875   case X86::VORPDrr:
8876   case X86::VORPSrr:
8877   case X86::VORPDYrr:
8878   case X86::VORPSYrr:
8879   case X86::VORPDZ128rr:
8880   case X86::VORPSZ128rr:
8881   case X86::VORPDZ256rr:
8882   case X86::VORPSZ256rr:
8883   case X86::VORPDZrr:
8884   case X86::VORPSZrr:
8885   case X86::VXORPDrr:
8886   case X86::VXORPSrr:
8887   case X86::VXORPDYrr:
8888   case X86::VXORPSYrr:
8889   case X86::VXORPDZ128rr:
8890   case X86::VXORPSZ128rr:
8891   case X86::VXORPDZ256rr:
8892   case X86::VXORPSZ256rr:
8893   case X86::VXORPDZrr:
8894   case X86::VXORPSZrr:
8895   case X86::KADDBrr:
8896   case X86::KADDWrr:
8897   case X86::KADDDrr:
8898   case X86::KADDQrr:
8899   case X86::KANDBrr:
8900   case X86::KANDWrr:
8901   case X86::KANDDrr:
8902   case X86::KANDQrr:
8903   case X86::KORBrr:
8904   case X86::KORWrr:
8905   case X86::KORDrr:
8906   case X86::KORQrr:
8907   case X86::KXORBrr:
8908   case X86::KXORWrr:
8909   case X86::KXORDrr:
8910   case X86::KXORQrr:
8911   case X86::VPADDBrr:
8912   case X86::VPADDWrr:
8913   case X86::VPADDDrr:
8914   case X86::VPADDQrr:
8915   case X86::VPADDBYrr:
8916   case X86::VPADDWYrr:
8917   case X86::VPADDDYrr:
8918   case X86::VPADDQYrr:
8919   case X86::VPADDBZ128rr:
8920   case X86::VPADDWZ128rr:
8921   case X86::VPADDDZ128rr:
8922   case X86::VPADDQZ128rr:
8923   case X86::VPADDBZ256rr:
8924   case X86::VPADDWZ256rr:
8925   case X86::VPADDDZ256rr:
8926   case X86::VPADDQZ256rr:
8927   case X86::VPADDBZrr:
8928   case X86::VPADDWZrr:
8929   case X86::VPADDDZrr:
8930   case X86::VPADDQZrr:
8931   case X86::VPMULLWrr:
8932   case X86::VPMULLWYrr:
8933   case X86::VPMULLWZ128rr:
8934   case X86::VPMULLWZ256rr:
8935   case X86::VPMULLWZrr:
8936   case X86::VPMULLDrr:
8937   case X86::VPMULLDYrr:
8938   case X86::VPMULLDZ128rr:
8939   case X86::VPMULLDZ256rr:
8940   case X86::VPMULLDZrr:
8941   case X86::VPMULLQZ128rr:
8942   case X86::VPMULLQZ256rr:
8943   case X86::VPMULLQZrr:
8944   case X86::VPMAXSBrr:
8945   case X86::VPMAXSBYrr:
8946   case X86::VPMAXSBZ128rr:
8947   case X86::VPMAXSBZ256rr:
8948   case X86::VPMAXSBZrr:
8949   case X86::VPMAXSDrr:
8950   case X86::VPMAXSDYrr:
8951   case X86::VPMAXSDZ128rr:
8952   case X86::VPMAXSDZ256rr:
8953   case X86::VPMAXSDZrr:
8954   case X86::VPMAXSQZ128rr:
8955   case X86::VPMAXSQZ256rr:
8956   case X86::VPMAXSQZrr:
8957   case X86::VPMAXSWrr:
8958   case X86::VPMAXSWYrr:
8959   case X86::VPMAXSWZ128rr:
8960   case X86::VPMAXSWZ256rr:
8961   case X86::VPMAXSWZrr:
8962   case X86::VPMAXUBrr:
8963   case X86::VPMAXUBYrr:
8964   case X86::VPMAXUBZ128rr:
8965   case X86::VPMAXUBZ256rr:
8966   case X86::VPMAXUBZrr:
8967   case X86::VPMAXUDrr:
8968   case X86::VPMAXUDYrr:
8969   case X86::VPMAXUDZ128rr:
8970   case X86::VPMAXUDZ256rr:
8971   case X86::VPMAXUDZrr:
8972   case X86::VPMAXUQZ128rr:
8973   case X86::VPMAXUQZ256rr:
8974   case X86::VPMAXUQZrr:
8975   case X86::VPMAXUWrr:
8976   case X86::VPMAXUWYrr:
8977   case X86::VPMAXUWZ128rr:
8978   case X86::VPMAXUWZ256rr:
8979   case X86::VPMAXUWZrr:
8980   case X86::VPMINSBrr:
8981   case X86::VPMINSBYrr:
8982   case X86::VPMINSBZ128rr:
8983   case X86::VPMINSBZ256rr:
8984   case X86::VPMINSBZrr:
8985   case X86::VPMINSDrr:
8986   case X86::VPMINSDYrr:
8987   case X86::VPMINSDZ128rr:
8988   case X86::VPMINSDZ256rr:
8989   case X86::VPMINSDZrr:
8990   case X86::VPMINSQZ128rr:
8991   case X86::VPMINSQZ256rr:
8992   case X86::VPMINSQZrr:
8993   case X86::VPMINSWrr:
8994   case X86::VPMINSWYrr:
8995   case X86::VPMINSWZ128rr:
8996   case X86::VPMINSWZ256rr:
8997   case X86::VPMINSWZrr:
8998   case X86::VPMINUBrr:
8999   case X86::VPMINUBYrr:
9000   case X86::VPMINUBZ128rr:
9001   case X86::VPMINUBZ256rr:
9002   case X86::VPMINUBZrr:
9003   case X86::VPMINUDrr:
9004   case X86::VPMINUDYrr:
9005   case X86::VPMINUDZ128rr:
9006   case X86::VPMINUDZ256rr:
9007   case X86::VPMINUDZrr:
9008   case X86::VPMINUQZ128rr:
9009   case X86::VPMINUQZ256rr:
9010   case X86::VPMINUQZrr:
9011   case X86::VPMINUWrr:
9012   case X86::VPMINUWYrr:
9013   case X86::VPMINUWZ128rr:
9014   case X86::VPMINUWZ256rr:
9015   case X86::VPMINUWZrr:
9016   // Normal min/max instructions are not commutative because of NaN and signed
9017   // zero semantics, but these are. Thus, there's no need to check for global
9018   // relaxed math; the instructions themselves have the properties we need.
9019   case X86::MAXCPDrr:
9020   case X86::MAXCPSrr:
9021   case X86::MAXCSDrr:
9022   case X86::MAXCSSrr:
9023   case X86::MINCPDrr:
9024   case X86::MINCPSrr:
9025   case X86::MINCSDrr:
9026   case X86::MINCSSrr:
9027   case X86::VMAXCPDrr:
9028   case X86::VMAXCPSrr:
9029   case X86::VMAXCPDYrr:
9030   case X86::VMAXCPSYrr:
9031   case X86::VMAXCPDZ128rr:
9032   case X86::VMAXCPSZ128rr:
9033   case X86::VMAXCPDZ256rr:
9034   case X86::VMAXCPSZ256rr:
9035   case X86::VMAXCPDZrr:
9036   case X86::VMAXCPSZrr:
9037   case X86::VMAXCSDrr:
9038   case X86::VMAXCSSrr:
9039   case X86::VMAXCSDZrr:
9040   case X86::VMAXCSSZrr:
9041   case X86::VMINCPDrr:
9042   case X86::VMINCPSrr:
9043   case X86::VMINCPDYrr:
9044   case X86::VMINCPSYrr:
9045   case X86::VMINCPDZ128rr:
9046   case X86::VMINCPSZ128rr:
9047   case X86::VMINCPDZ256rr:
9048   case X86::VMINCPSZ256rr:
9049   case X86::VMINCPDZrr:
9050   case X86::VMINCPSZrr:
9051   case X86::VMINCSDrr:
9052   case X86::VMINCSSrr:
9053   case X86::VMINCSDZrr:
9054   case X86::VMINCSSZrr:
9055   case X86::VMAXCPHZ128rr:
9056   case X86::VMAXCPHZ256rr:
9057   case X86::VMAXCPHZrr:
9058   case X86::VMAXCSHZrr:
9059   case X86::VMINCPHZ128rr:
9060   case X86::VMINCPHZ256rr:
9061   case X86::VMINCPHZrr:
9062   case X86::VMINCSHZrr:
9063     return true;
9064   case X86::ADDPDrr:
9065   case X86::ADDPSrr:
9066   case X86::ADDSDrr:
9067   case X86::ADDSSrr:
9068   case X86::MULPDrr:
9069   case X86::MULPSrr:
9070   case X86::MULSDrr:
9071   case X86::MULSSrr:
9072   case X86::VADDPDrr:
9073   case X86::VADDPSrr:
9074   case X86::VADDPDYrr:
9075   case X86::VADDPSYrr:
9076   case X86::VADDPDZ128rr:
9077   case X86::VADDPSZ128rr:
9078   case X86::VADDPDZ256rr:
9079   case X86::VADDPSZ256rr:
9080   case X86::VADDPDZrr:
9081   case X86::VADDPSZrr:
9082   case X86::VADDSDrr:
9083   case X86::VADDSSrr:
9084   case X86::VADDSDZrr:
9085   case X86::VADDSSZrr:
9086   case X86::VMULPDrr:
9087   case X86::VMULPSrr:
9088   case X86::VMULPDYrr:
9089   case X86::VMULPSYrr:
9090   case X86::VMULPDZ128rr:
9091   case X86::VMULPSZ128rr:
9092   case X86::VMULPDZ256rr:
9093   case X86::VMULPSZ256rr:
9094   case X86::VMULPDZrr:
9095   case X86::VMULPSZrr:
9096   case X86::VMULSDrr:
9097   case X86::VMULSSrr:
9098   case X86::VMULSDZrr:
9099   case X86::VMULSSZrr:
9100   case X86::VADDPHZ128rr:
9101   case X86::VADDPHZ256rr:
9102   case X86::VADDPHZrr:
9103   case X86::VADDSHZrr:
9104   case X86::VMULPHZ128rr:
9105   case X86::VMULPHZ256rr:
9106   case X86::VMULPHZrr:
9107   case X86::VMULSHZrr:
9108     return Inst.getFlag(MachineInstr::MIFlag::FmReassoc) &&
9109            Inst.getFlag(MachineInstr::MIFlag::FmNsz);
9110   default:
9111     return false;
9112   }
9113 }
9114 
9115 /// If \p DescribedReg overlaps with the MOVrr instruction's destination
9116 /// register then, if possible, describe the value in terms of the source
9117 /// register.
9118 static std::optional<ParamLoadedValue>
9119 describeMOVrrLoadedValue(const MachineInstr &MI, Register DescribedReg,
9120                          const TargetRegisterInfo *TRI) {
9121   Register DestReg = MI.getOperand(0).getReg();
9122   Register SrcReg = MI.getOperand(1).getReg();
9123 
9124   auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
9125 
9126   // If the described register is the destination, just return the source.
9127   if (DestReg == DescribedReg)
9128     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
9129 
9130   // If the described register is a sub-register of the destination register,
9131   // then pick out the source register's corresponding sub-register.
9132   if (unsigned SubRegIdx = TRI->getSubRegIndex(DestReg, DescribedReg)) {
9133     Register SrcSubReg = TRI->getSubReg(SrcReg, SubRegIdx);
9134     return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
9135   }
9136 
9137   // The remaining case to consider is when the described register is a
9138   // super-register of the destination register. MOV8rr and MOV16rr does not
9139   // write to any of the other bytes in the register, meaning that we'd have to
9140   // describe the value using a combination of the source register and the
9141   // non-overlapping bits in the described register, which is not currently
9142   // possible.
9143   if (MI.getOpcode() == X86::MOV8rr || MI.getOpcode() == X86::MOV16rr ||
9144       !TRI->isSuperRegister(DestReg, DescribedReg))
9145     return std::nullopt;
9146 
9147   assert(MI.getOpcode() == X86::MOV32rr && "Unexpected super-register case");
9148   return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
9149 }
9150 
9151 std::optional<ParamLoadedValue>
9152 X86InstrInfo::describeLoadedValue(const MachineInstr &MI, Register Reg) const {
9153   const MachineOperand *Op = nullptr;
9154   DIExpression *Expr = nullptr;
9155 
9156   const TargetRegisterInfo *TRI = &getRegisterInfo();
9157 
9158   switch (MI.getOpcode()) {
9159   case X86::LEA32r:
9160   case X86::LEA64r:
9161   case X86::LEA64_32r: {
9162     // We may need to describe a 64-bit parameter with a 32-bit LEA.
9163     if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
9164       return std::nullopt;
9165 
9166     // Operand 4 could be global address. For now we do not support
9167     // such situation.
9168     if (!MI.getOperand(4).isImm() || !MI.getOperand(2).isImm())
9169       return std::nullopt;
9170 
9171     const MachineOperand &Op1 = MI.getOperand(1);
9172     const MachineOperand &Op2 = MI.getOperand(3);
9173     assert(Op2.isReg() &&
9174            (Op2.getReg() == X86::NoRegister || Op2.getReg().isPhysical()));
9175 
9176     // Omit situations like:
9177     // %rsi = lea %rsi, 4, ...
9178     if ((Op1.isReg() && Op1.getReg() == MI.getOperand(0).getReg()) ||
9179         Op2.getReg() == MI.getOperand(0).getReg())
9180       return std::nullopt;
9181     else if ((Op1.isReg() && Op1.getReg() != X86::NoRegister &&
9182               TRI->regsOverlap(Op1.getReg(), MI.getOperand(0).getReg())) ||
9183              (Op2.getReg() != X86::NoRegister &&
9184               TRI->regsOverlap(Op2.getReg(), MI.getOperand(0).getReg())))
9185       return std::nullopt;
9186 
9187     int64_t Coef = MI.getOperand(2).getImm();
9188     int64_t Offset = MI.getOperand(4).getImm();
9189     SmallVector<uint64_t, 8> Ops;
9190 
9191     if ((Op1.isReg() && Op1.getReg() != X86::NoRegister)) {
9192       Op = &Op1;
9193     } else if (Op1.isFI())
9194       Op = &Op1;
9195 
9196     if (Op && Op->isReg() && Op->getReg() == Op2.getReg() && Coef > 0) {
9197       Ops.push_back(dwarf::DW_OP_constu);
9198       Ops.push_back(Coef + 1);
9199       Ops.push_back(dwarf::DW_OP_mul);
9200     } else {
9201       if (Op && Op2.getReg() != X86::NoRegister) {
9202         int dwarfReg = TRI->getDwarfRegNum(Op2.getReg(), false);
9203         if (dwarfReg < 0)
9204           return std::nullopt;
9205         else if (dwarfReg < 32) {
9206           Ops.push_back(dwarf::DW_OP_breg0 + dwarfReg);
9207           Ops.push_back(0);
9208         } else {
9209           Ops.push_back(dwarf::DW_OP_bregx);
9210           Ops.push_back(dwarfReg);
9211           Ops.push_back(0);
9212         }
9213       } else if (!Op) {
9214         assert(Op2.getReg() != X86::NoRegister);
9215         Op = &Op2;
9216       }
9217 
9218       if (Coef > 1) {
9219         assert(Op2.getReg() != X86::NoRegister);
9220         Ops.push_back(dwarf::DW_OP_constu);
9221         Ops.push_back(Coef);
9222         Ops.push_back(dwarf::DW_OP_mul);
9223       }
9224 
9225       if (((Op1.isReg() && Op1.getReg() != X86::NoRegister) || Op1.isFI()) &&
9226           Op2.getReg() != X86::NoRegister) {
9227         Ops.push_back(dwarf::DW_OP_plus);
9228       }
9229     }
9230 
9231     DIExpression::appendOffset(Ops, Offset);
9232     Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), Ops);
9233 
9234     return ParamLoadedValue(*Op, Expr);
9235   }
9236   case X86::MOV8ri:
9237   case X86::MOV16ri:
9238     // TODO: Handle MOV8ri and MOV16ri.
9239     return std::nullopt;
9240   case X86::MOV32ri:
9241   case X86::MOV64ri:
9242   case X86::MOV64ri32:
9243     // MOV32ri may be used for producing zero-extended 32-bit immediates in
9244     // 64-bit parameters, so we need to consider super-registers.
9245     if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
9246       return std::nullopt;
9247     return ParamLoadedValue(MI.getOperand(1), Expr);
9248   case X86::MOV8rr:
9249   case X86::MOV16rr:
9250   case X86::MOV32rr:
9251   case X86::MOV64rr:
9252     return describeMOVrrLoadedValue(MI, Reg, TRI);
9253   case X86::XOR32rr: {
9254     // 64-bit parameters are zero-materialized using XOR32rr, so also consider
9255     // super-registers.
9256     if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
9257       return std::nullopt;
9258     if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
9259       return ParamLoadedValue(MachineOperand::CreateImm(0), Expr);
9260     return std::nullopt;
9261   }
9262   case X86::MOVSX64rr32: {
9263     // We may need to describe the lower 32 bits of the MOVSX; for example, in
9264     // cases like this:
9265     //
9266     //  $ebx = [...]
9267     //  $rdi = MOVSX64rr32 $ebx
9268     //  $esi = MOV32rr $edi
9269     if (!TRI->isSubRegisterEq(MI.getOperand(0).getReg(), Reg))
9270       return std::nullopt;
9271 
9272     Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
9273 
9274     // If the described register is the destination register we need to
9275     // sign-extend the source register from 32 bits. The other case we handle
9276     // is when the described register is the 32-bit sub-register of the
9277     // destination register, in case we just need to return the source
9278     // register.
9279     if (Reg == MI.getOperand(0).getReg())
9280       Expr = DIExpression::appendExt(Expr, 32, 64, true);
9281     else
9282       assert(X86MCRegisterClasses[X86::GR32RegClassID].contains(Reg) &&
9283              "Unhandled sub-register case for MOVSX64rr32");
9284 
9285     return ParamLoadedValue(MI.getOperand(1), Expr);
9286   }
9287   default:
9288     assert(!MI.isMoveImmediate() && "Unexpected MoveImm instruction");
9289     return TargetInstrInfo::describeLoadedValue(MI, Reg);
9290   }
9291 }
9292 
9293 /// This is an architecture-specific helper function of reassociateOps.
9294 /// Set special operand attributes for new instructions after reassociation.
9295 void X86InstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1,
9296                                          MachineInstr &OldMI2,
9297                                          MachineInstr &NewMI1,
9298                                          MachineInstr &NewMI2) const {
9299   // Propagate FP flags from the original instructions.
9300   // But clear poison-generating flags because those may not be valid now.
9301   // TODO: There should be a helper function for copying only fast-math-flags.
9302   uint32_t IntersectedFlags = OldMI1.getFlags() & OldMI2.getFlags();
9303   NewMI1.setFlags(IntersectedFlags);
9304   NewMI1.clearFlag(MachineInstr::MIFlag::NoSWrap);
9305   NewMI1.clearFlag(MachineInstr::MIFlag::NoUWrap);
9306   NewMI1.clearFlag(MachineInstr::MIFlag::IsExact);
9307 
9308   NewMI2.setFlags(IntersectedFlags);
9309   NewMI2.clearFlag(MachineInstr::MIFlag::NoSWrap);
9310   NewMI2.clearFlag(MachineInstr::MIFlag::NoUWrap);
9311   NewMI2.clearFlag(MachineInstr::MIFlag::IsExact);
9312 
9313   // Integer instructions may define an implicit EFLAGS dest register operand.
9314   MachineOperand *OldFlagDef1 = OldMI1.findRegisterDefOperand(X86::EFLAGS);
9315   MachineOperand *OldFlagDef2 = OldMI2.findRegisterDefOperand(X86::EFLAGS);
9316 
9317   assert(!OldFlagDef1 == !OldFlagDef2 &&
9318          "Unexpected instruction type for reassociation");
9319 
9320   if (!OldFlagDef1 || !OldFlagDef2)
9321     return;
9322 
9323   assert(OldFlagDef1->isDead() && OldFlagDef2->isDead() &&
9324          "Must have dead EFLAGS operand in reassociable instruction");
9325 
9326   MachineOperand *NewFlagDef1 = NewMI1.findRegisterDefOperand(X86::EFLAGS);
9327   MachineOperand *NewFlagDef2 = NewMI2.findRegisterDefOperand(X86::EFLAGS);
9328 
9329   assert(NewFlagDef1 && NewFlagDef2 &&
9330          "Unexpected operand in reassociable instruction");
9331 
9332   // Mark the new EFLAGS operands as dead to be helpful to subsequent iterations
9333   // of this pass or other passes. The EFLAGS operands must be dead in these new
9334   // instructions because the EFLAGS operands in the original instructions must
9335   // be dead in order for reassociation to occur.
9336   NewFlagDef1->setIsDead();
9337   NewFlagDef2->setIsDead();
9338 }
9339 
9340 std::pair<unsigned, unsigned>
9341 X86InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
9342   return std::make_pair(TF, 0u);
9343 }
9344 
9345 ArrayRef<std::pair<unsigned, const char *>>
9346 X86InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
9347   using namespace X86II;
9348   static const std::pair<unsigned, const char *> TargetFlags[] = {
9349       {MO_GOT_ABSOLUTE_ADDRESS, "x86-got-absolute-address"},
9350       {MO_PIC_BASE_OFFSET, "x86-pic-base-offset"},
9351       {MO_GOT, "x86-got"},
9352       {MO_GOTOFF, "x86-gotoff"},
9353       {MO_GOTPCREL, "x86-gotpcrel"},
9354       {MO_GOTPCREL_NORELAX, "x86-gotpcrel-norelax"},
9355       {MO_PLT, "x86-plt"},
9356       {MO_TLSGD, "x86-tlsgd"},
9357       {MO_TLSLD, "x86-tlsld"},
9358       {MO_TLSLDM, "x86-tlsldm"},
9359       {MO_GOTTPOFF, "x86-gottpoff"},
9360       {MO_INDNTPOFF, "x86-indntpoff"},
9361       {MO_TPOFF, "x86-tpoff"},
9362       {MO_DTPOFF, "x86-dtpoff"},
9363       {MO_NTPOFF, "x86-ntpoff"},
9364       {MO_GOTNTPOFF, "x86-gotntpoff"},
9365       {MO_DLLIMPORT, "x86-dllimport"},
9366       {MO_DARWIN_NONLAZY, "x86-darwin-nonlazy"},
9367       {MO_DARWIN_NONLAZY_PIC_BASE, "x86-darwin-nonlazy-pic-base"},
9368       {MO_TLVP, "x86-tlvp"},
9369       {MO_TLVP_PIC_BASE, "x86-tlvp-pic-base"},
9370       {MO_SECREL, "x86-secrel"},
9371       {MO_COFFSTUB, "x86-coffstub"}};
9372   return ArrayRef(TargetFlags);
9373 }
9374 
9375 namespace {
9376   /// Create Global Base Reg pass. This initializes the PIC
9377   /// global base register for x86-32.
9378   struct CGBR : public MachineFunctionPass {
9379     static char ID;
9380     CGBR() : MachineFunctionPass(ID) {}
9381 
9382     bool runOnMachineFunction(MachineFunction &MF) override {
9383       const X86TargetMachine *TM =
9384         static_cast<const X86TargetMachine *>(&MF.getTarget());
9385       const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
9386 
9387       // Don't do anything in the 64-bit small and kernel code models. They use
9388       // RIP-relative addressing for everything.
9389       if (STI.is64Bit() && (TM->getCodeModel() == CodeModel::Small ||
9390                             TM->getCodeModel() == CodeModel::Kernel))
9391         return false;
9392 
9393       // Only emit a global base reg in PIC mode.
9394       if (!TM->isPositionIndependent())
9395         return false;
9396 
9397       X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
9398       Register GlobalBaseReg = X86FI->getGlobalBaseReg();
9399 
9400       // If we didn't need a GlobalBaseReg, don't insert code.
9401       if (GlobalBaseReg == 0)
9402         return false;
9403 
9404       // Insert the set of GlobalBaseReg into the first MBB of the function
9405       MachineBasicBlock &FirstMBB = MF.front();
9406       MachineBasicBlock::iterator MBBI = FirstMBB.begin();
9407       DebugLoc DL = FirstMBB.findDebugLoc(MBBI);
9408       MachineRegisterInfo &RegInfo = MF.getRegInfo();
9409       const X86InstrInfo *TII = STI.getInstrInfo();
9410 
9411       Register PC;
9412       if (STI.isPICStyleGOT())
9413         PC = RegInfo.createVirtualRegister(&X86::GR32RegClass);
9414       else
9415         PC = GlobalBaseReg;
9416 
9417       if (STI.is64Bit()) {
9418         if (TM->getCodeModel() == CodeModel::Medium) {
9419           // In the medium code model, use a RIP-relative LEA to materialize the
9420           // GOT.
9421           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::LEA64r), PC)
9422               .addReg(X86::RIP)
9423               .addImm(0)
9424               .addReg(0)
9425               .addExternalSymbol("_GLOBAL_OFFSET_TABLE_")
9426               .addReg(0);
9427         } else if (TM->getCodeModel() == CodeModel::Large) {
9428           // In the large code model, we are aiming for this code, though the
9429           // register allocation may vary:
9430           //   leaq .LN$pb(%rip), %rax
9431           //   movq $_GLOBAL_OFFSET_TABLE_ - .LN$pb, %rcx
9432           //   addq %rcx, %rax
9433           // RAX now holds address of _GLOBAL_OFFSET_TABLE_.
9434           Register PBReg = RegInfo.createVirtualRegister(&X86::GR64RegClass);
9435           Register GOTReg = RegInfo.createVirtualRegister(&X86::GR64RegClass);
9436           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::LEA64r), PBReg)
9437               .addReg(X86::RIP)
9438               .addImm(0)
9439               .addReg(0)
9440               .addSym(MF.getPICBaseSymbol())
9441               .addReg(0);
9442           std::prev(MBBI)->setPreInstrSymbol(MF, MF.getPICBaseSymbol());
9443           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::MOV64ri), GOTReg)
9444               .addExternalSymbol("_GLOBAL_OFFSET_TABLE_",
9445                                  X86II::MO_PIC_BASE_OFFSET);
9446           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::ADD64rr), PC)
9447               .addReg(PBReg, RegState::Kill)
9448               .addReg(GOTReg, RegState::Kill);
9449         } else {
9450           llvm_unreachable("unexpected code model");
9451         }
9452       } else {
9453         // Operand of MovePCtoStack is completely ignored by asm printer. It's
9454         // only used in JIT code emission as displacement to pc.
9455         BuildMI(FirstMBB, MBBI, DL, TII->get(X86::MOVPC32r), PC).addImm(0);
9456 
9457         // If we're using vanilla 'GOT' PIC style, we should use relative
9458         // addressing not to pc, but to _GLOBAL_OFFSET_TABLE_ external.
9459         if (STI.isPICStyleGOT()) {
9460           // Generate addl $__GLOBAL_OFFSET_TABLE_ + [.-piclabel],
9461           // %some_register
9462           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::ADD32ri), GlobalBaseReg)
9463               .addReg(PC)
9464               .addExternalSymbol("_GLOBAL_OFFSET_TABLE_",
9465                                  X86II::MO_GOT_ABSOLUTE_ADDRESS);
9466         }
9467       }
9468 
9469       return true;
9470     }
9471 
9472     StringRef getPassName() const override {
9473       return "X86 PIC Global Base Reg Initialization";
9474     }
9475 
9476     void getAnalysisUsage(AnalysisUsage &AU) const override {
9477       AU.setPreservesCFG();
9478       MachineFunctionPass::getAnalysisUsage(AU);
9479     }
9480   };
9481 } // namespace
9482 
9483 char CGBR::ID = 0;
9484 FunctionPass*
9485 llvm::createX86GlobalBaseRegPass() { return new CGBR(); }
9486 
9487 namespace {
9488   struct LDTLSCleanup : public MachineFunctionPass {
9489     static char ID;
9490     LDTLSCleanup() : MachineFunctionPass(ID) {}
9491 
9492     bool runOnMachineFunction(MachineFunction &MF) override {
9493       if (skipFunction(MF.getFunction()))
9494         return false;
9495 
9496       X86MachineFunctionInfo *MFI = MF.getInfo<X86MachineFunctionInfo>();
9497       if (MFI->getNumLocalDynamicTLSAccesses() < 2) {
9498         // No point folding accesses if there isn't at least two.
9499         return false;
9500       }
9501 
9502       MachineDominatorTree *DT = &getAnalysis<MachineDominatorTree>();
9503       return VisitNode(DT->getRootNode(), 0);
9504     }
9505 
9506     // Visit the dominator subtree rooted at Node in pre-order.
9507     // If TLSBaseAddrReg is non-null, then use that to replace any
9508     // TLS_base_addr instructions. Otherwise, create the register
9509     // when the first such instruction is seen, and then use it
9510     // as we encounter more instructions.
9511     bool VisitNode(MachineDomTreeNode *Node, unsigned TLSBaseAddrReg) {
9512       MachineBasicBlock *BB = Node->getBlock();
9513       bool Changed = false;
9514 
9515       // Traverse the current block.
9516       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
9517            ++I) {
9518         switch (I->getOpcode()) {
9519           case X86::TLS_base_addr32:
9520           case X86::TLS_base_addr64:
9521             if (TLSBaseAddrReg)
9522               I = ReplaceTLSBaseAddrCall(*I, TLSBaseAddrReg);
9523             else
9524               I = SetRegister(*I, &TLSBaseAddrReg);
9525             Changed = true;
9526             break;
9527           default:
9528             break;
9529         }
9530       }
9531 
9532       // Visit the children of this block in the dominator tree.
9533       for (auto &I : *Node) {
9534         Changed |= VisitNode(I, TLSBaseAddrReg);
9535       }
9536 
9537       return Changed;
9538     }
9539 
9540     // Replace the TLS_base_addr instruction I with a copy from
9541     // TLSBaseAddrReg, returning the new instruction.
9542     MachineInstr *ReplaceTLSBaseAddrCall(MachineInstr &I,
9543                                          unsigned TLSBaseAddrReg) {
9544       MachineFunction *MF = I.getParent()->getParent();
9545       const X86Subtarget &STI = MF->getSubtarget<X86Subtarget>();
9546       const bool is64Bit = STI.is64Bit();
9547       const X86InstrInfo *TII = STI.getInstrInfo();
9548 
9549       // Insert a Copy from TLSBaseAddrReg to RAX/EAX.
9550       MachineInstr *Copy =
9551           BuildMI(*I.getParent(), I, I.getDebugLoc(),
9552                   TII->get(TargetOpcode::COPY), is64Bit ? X86::RAX : X86::EAX)
9553               .addReg(TLSBaseAddrReg);
9554 
9555       // Erase the TLS_base_addr instruction.
9556       I.eraseFromParent();
9557 
9558       return Copy;
9559     }
9560 
9561     // Create a virtual register in *TLSBaseAddrReg, and populate it by
9562     // inserting a copy instruction after I. Returns the new instruction.
9563     MachineInstr *SetRegister(MachineInstr &I, unsigned *TLSBaseAddrReg) {
9564       MachineFunction *MF = I.getParent()->getParent();
9565       const X86Subtarget &STI = MF->getSubtarget<X86Subtarget>();
9566       const bool is64Bit = STI.is64Bit();
9567       const X86InstrInfo *TII = STI.getInstrInfo();
9568 
9569       // Create a virtual register for the TLS base address.
9570       MachineRegisterInfo &RegInfo = MF->getRegInfo();
9571       *TLSBaseAddrReg = RegInfo.createVirtualRegister(is64Bit
9572                                                       ? &X86::GR64RegClass
9573                                                       : &X86::GR32RegClass);
9574 
9575       // Insert a copy from RAX/EAX to TLSBaseAddrReg.
9576       MachineInstr *Next = I.getNextNode();
9577       MachineInstr *Copy =
9578           BuildMI(*I.getParent(), Next, I.getDebugLoc(),
9579                   TII->get(TargetOpcode::COPY), *TLSBaseAddrReg)
9580               .addReg(is64Bit ? X86::RAX : X86::EAX);
9581 
9582       return Copy;
9583     }
9584 
9585     StringRef getPassName() const override {
9586       return "Local Dynamic TLS Access Clean-up";
9587     }
9588 
9589     void getAnalysisUsage(AnalysisUsage &AU) const override {
9590       AU.setPreservesCFG();
9591       AU.addRequired<MachineDominatorTree>();
9592       MachineFunctionPass::getAnalysisUsage(AU);
9593     }
9594   };
9595 }
9596 
9597 char LDTLSCleanup::ID = 0;
9598 FunctionPass*
9599 llvm::createCleanupLocalDynamicTLSPass() { return new LDTLSCleanup(); }
9600 
9601 /// Constants defining how certain sequences should be outlined.
9602 ///
9603 /// \p MachineOutlinerDefault implies that the function is called with a call
9604 /// instruction, and a return must be emitted for the outlined function frame.
9605 ///
9606 /// That is,
9607 ///
9608 /// I1                                 OUTLINED_FUNCTION:
9609 /// I2 --> call OUTLINED_FUNCTION       I1
9610 /// I3                                  I2
9611 ///                                     I3
9612 ///                                     ret
9613 ///
9614 /// * Call construction overhead: 1 (call instruction)
9615 /// * Frame construction overhead: 1 (return instruction)
9616 ///
9617 /// \p MachineOutlinerTailCall implies that the function is being tail called.
9618 /// A jump is emitted instead of a call, and the return is already present in
9619 /// the outlined sequence. That is,
9620 ///
9621 /// I1                                 OUTLINED_FUNCTION:
9622 /// I2 --> jmp OUTLINED_FUNCTION       I1
9623 /// ret                                I2
9624 ///                                    ret
9625 ///
9626 /// * Call construction overhead: 1 (jump instruction)
9627 /// * Frame construction overhead: 0 (don't need to return)
9628 ///
9629 enum MachineOutlinerClass {
9630   MachineOutlinerDefault,
9631   MachineOutlinerTailCall
9632 };
9633 
9634 std::optional<outliner::OutlinedFunction>
9635 X86InstrInfo::getOutliningCandidateInfo(
9636     std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
9637   unsigned SequenceSize =
9638       std::accumulate(RepeatedSequenceLocs[0].front(),
9639                       std::next(RepeatedSequenceLocs[0].back()), 0,
9640                       [](unsigned Sum, const MachineInstr &MI) {
9641                         // FIXME: x86 doesn't implement getInstSizeInBytes, so
9642                         // we can't tell the cost.  Just assume each instruction
9643                         // is one byte.
9644                         if (MI.isDebugInstr() || MI.isKill())
9645                           return Sum;
9646                         return Sum + 1;
9647                       });
9648 
9649   // We check to see if CFI Instructions are present, and if they are
9650   // we find the number of CFI Instructions in the candidates.
9651   unsigned CFICount = 0;
9652   for (auto &I : make_range(RepeatedSequenceLocs[0].front(),
9653                             std::next(RepeatedSequenceLocs[0].back()))) {
9654     if (I.isCFIInstruction())
9655       CFICount++;
9656   }
9657 
9658   // We compare the number of found CFI Instructions to  the number of CFI
9659   // instructions in the parent function for each candidate.  We must check this
9660   // since if we outline one of the CFI instructions in a function, we have to
9661   // outline them all for correctness. If we do not, the address offsets will be
9662   // incorrect between the two sections of the program.
9663   for (outliner::Candidate &C : RepeatedSequenceLocs) {
9664     std::vector<MCCFIInstruction> CFIInstructions =
9665         C.getMF()->getFrameInstructions();
9666 
9667     if (CFICount > 0 && CFICount != CFIInstructions.size())
9668       return std::nullopt;
9669   }
9670 
9671   // FIXME: Use real size in bytes for call and ret instructions.
9672   if (RepeatedSequenceLocs[0].back()->isTerminator()) {
9673     for (outliner::Candidate &C : RepeatedSequenceLocs)
9674       C.setCallInfo(MachineOutlinerTailCall, 1);
9675 
9676     return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
9677                                       0, // Number of bytes to emit frame.
9678                                       MachineOutlinerTailCall // Type of frame.
9679     );
9680   }
9681 
9682   if (CFICount > 0)
9683     return std::nullopt;
9684 
9685   for (outliner::Candidate &C : RepeatedSequenceLocs)
9686     C.setCallInfo(MachineOutlinerDefault, 1);
9687 
9688   return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize, 1,
9689                                     MachineOutlinerDefault);
9690 }
9691 
9692 bool X86InstrInfo::isFunctionSafeToOutlineFrom(MachineFunction &MF,
9693                                            bool OutlineFromLinkOnceODRs) const {
9694   const Function &F = MF.getFunction();
9695 
9696   // Does the function use a red zone? If it does, then we can't risk messing
9697   // with the stack.
9698   if (Subtarget.getFrameLowering()->has128ByteRedZone(MF)) {
9699     // It could have a red zone. If it does, then we don't want to touch it.
9700     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
9701     if (!X86FI || X86FI->getUsesRedZone())
9702       return false;
9703   }
9704 
9705   // If we *don't* want to outline from things that could potentially be deduped
9706   // then return false.
9707   if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
9708       return false;
9709 
9710   // This function is viable for outlining, so return true.
9711   return true;
9712 }
9713 
9714 outliner::InstrType
9715 X86InstrInfo::getOutliningTypeImpl(MachineBasicBlock::iterator &MIT,  unsigned Flags) const {
9716   MachineInstr &MI = *MIT;
9717 
9718   // Is this a terminator for a basic block?
9719   if (MI.isTerminator())
9720     // TargetInstrInfo::getOutliningType has already filtered out anything
9721     // that would break this, so we can allow it here.
9722     return outliner::InstrType::Legal;
9723 
9724   // Don't outline anything that modifies or reads from the stack pointer.
9725   //
9726   // FIXME: There are instructions which are being manually built without
9727   // explicit uses/defs so we also have to check the MCInstrDesc. We should be
9728   // able to remove the extra checks once those are fixed up. For example,
9729   // sometimes we might get something like %rax = POP64r 1. This won't be
9730   // caught by modifiesRegister or readsRegister even though the instruction
9731   // really ought to be formed so that modifiesRegister/readsRegister would
9732   // catch it.
9733   if (MI.modifiesRegister(X86::RSP, &RI) || MI.readsRegister(X86::RSP, &RI) ||
9734       MI.getDesc().hasImplicitUseOfPhysReg(X86::RSP) ||
9735       MI.getDesc().hasImplicitDefOfPhysReg(X86::RSP))
9736     return outliner::InstrType::Illegal;
9737 
9738   // Outlined calls change the instruction pointer, so don't read from it.
9739   if (MI.readsRegister(X86::RIP, &RI) ||
9740       MI.getDesc().hasImplicitUseOfPhysReg(X86::RIP) ||
9741       MI.getDesc().hasImplicitDefOfPhysReg(X86::RIP))
9742     return outliner::InstrType::Illegal;
9743 
9744   // Don't outline CFI instructions.
9745   if (MI.isCFIInstruction())
9746     return outliner::InstrType::Illegal;
9747 
9748   return outliner::InstrType::Legal;
9749 }
9750 
9751 void X86InstrInfo::buildOutlinedFrame(MachineBasicBlock &MBB,
9752                                           MachineFunction &MF,
9753                                           const outliner::OutlinedFunction &OF)
9754                                           const {
9755   // If we're a tail call, we already have a return, so don't do anything.
9756   if (OF.FrameConstructionID == MachineOutlinerTailCall)
9757     return;
9758 
9759   // We're a normal call, so our sequence doesn't have a return instruction.
9760   // Add it in.
9761   MachineInstr *retq = BuildMI(MF, DebugLoc(), get(X86::RET64));
9762   MBB.insert(MBB.end(), retq);
9763 }
9764 
9765 MachineBasicBlock::iterator
9766 X86InstrInfo::insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
9767                                  MachineBasicBlock::iterator &It,
9768                                  MachineFunction &MF,
9769                                  outliner::Candidate &C) const {
9770   // Is it a tail call?
9771   if (C.CallConstructionID == MachineOutlinerTailCall) {
9772     // Yes, just insert a JMP.
9773     It = MBB.insert(It,
9774                   BuildMI(MF, DebugLoc(), get(X86::TAILJMPd64))
9775                       .addGlobalAddress(M.getNamedValue(MF.getName())));
9776   } else {
9777     // No, insert a call.
9778     It = MBB.insert(It,
9779                   BuildMI(MF, DebugLoc(), get(X86::CALL64pcrel32))
9780                       .addGlobalAddress(M.getNamedValue(MF.getName())));
9781   }
9782 
9783   return It;
9784 }
9785 
9786 bool X86InstrInfo::getMachineCombinerPatterns(
9787     MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
9788     bool DoRegPressureReduce) const {
9789   unsigned Opc = Root.getOpcode();
9790   switch (Opc) {
9791   default:
9792     return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
9793                                                        DoRegPressureReduce);
9794   case X86::VPDPWSSDrr:
9795   case X86::VPDPWSSDrm:
9796   case X86::VPDPWSSDYrr:
9797   case X86::VPDPWSSDYrm: {
9798     Patterns.push_back(MachineCombinerPattern::DPWSSD);
9799     return true;
9800   }
9801   case X86::VPDPWSSDZ128r:
9802   case X86::VPDPWSSDZ128m:
9803   case X86::VPDPWSSDZ256r:
9804   case X86::VPDPWSSDZ256m:
9805   case X86::VPDPWSSDZr:
9806   case X86::VPDPWSSDZm: {
9807     if (Subtarget.hasBWI())
9808       Patterns.push_back(MachineCombinerPattern::DPWSSD);
9809     return true;
9810   }
9811   }
9812 }
9813 
9814 static void
9815 genAlternativeDpCodeSequence(MachineInstr &Root, const TargetInstrInfo &TII,
9816                              SmallVectorImpl<MachineInstr *> &InsInstrs,
9817                              SmallVectorImpl<MachineInstr *> &DelInstrs,
9818                              DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) {
9819   MachineFunction *MF = Root.getMF();
9820   MachineRegisterInfo &RegInfo = MF->getRegInfo();
9821 
9822   unsigned Opc = Root.getOpcode();
9823   unsigned AddOpc = 0;
9824   unsigned MaddOpc = 0;
9825   switch (Opc) {
9826   default:
9827     assert(false && "It should not reach here");
9828     break;
9829   // vpdpwssd xmm2,xmm3,xmm1
9830   // -->
9831   // vpmaddwd xmm3,xmm3,xmm1
9832   // vpaddd xmm2,xmm2,xmm3
9833   case X86::VPDPWSSDrr:
9834     MaddOpc = X86::VPMADDWDrr;
9835     AddOpc = X86::VPADDDrr;
9836     break;
9837   case X86::VPDPWSSDrm:
9838     MaddOpc = X86::VPMADDWDrm;
9839     AddOpc = X86::VPADDDrr;
9840     break;
9841   case X86::VPDPWSSDZ128r:
9842     MaddOpc = X86::VPMADDWDZ128rr;
9843     AddOpc = X86::VPADDDZ128rr;
9844     break;
9845   case X86::VPDPWSSDZ128m:
9846     MaddOpc = X86::VPMADDWDZ128rm;
9847     AddOpc = X86::VPADDDZ128rr;
9848     break;
9849   // vpdpwssd ymm2,ymm3,ymm1
9850   // -->
9851   // vpmaddwd ymm3,ymm3,ymm1
9852   // vpaddd ymm2,ymm2,ymm3
9853   case X86::VPDPWSSDYrr:
9854     MaddOpc = X86::VPMADDWDYrr;
9855     AddOpc = X86::VPADDDYrr;
9856     break;
9857   case X86::VPDPWSSDYrm:
9858     MaddOpc = X86::VPMADDWDYrm;
9859     AddOpc = X86::VPADDDYrr;
9860     break;
9861   case X86::VPDPWSSDZ256r:
9862     MaddOpc = X86::VPMADDWDZ256rr;
9863     AddOpc = X86::VPADDDZ256rr;
9864     break;
9865   case X86::VPDPWSSDZ256m:
9866     MaddOpc = X86::VPMADDWDZ256rm;
9867     AddOpc = X86::VPADDDZ256rr;
9868     break;
9869   // vpdpwssd zmm2,zmm3,zmm1
9870   // -->
9871   // vpmaddwd zmm3,zmm3,zmm1
9872   // vpaddd zmm2,zmm2,zmm3
9873   case X86::VPDPWSSDZr:
9874     MaddOpc = X86::VPMADDWDZrr;
9875     AddOpc = X86::VPADDDZrr;
9876     break;
9877   case X86::VPDPWSSDZm:
9878     MaddOpc = X86::VPMADDWDZrm;
9879     AddOpc = X86::VPADDDZrr;
9880     break;
9881   }
9882   // Create vpmaddwd.
9883   const TargetRegisterClass *RC =
9884       RegInfo.getRegClass(Root.getOperand(0).getReg());
9885   Register NewReg = RegInfo.createVirtualRegister(RC);
9886   MachineInstr *Madd = Root.getMF()->CloneMachineInstr(&Root);
9887   Madd->setDesc(TII.get(MaddOpc));
9888   Madd->untieRegOperand(1);
9889   Madd->removeOperand(1);
9890   Madd->getOperand(0).setReg(NewReg);
9891   InstrIdxForVirtReg.insert(std::make_pair(NewReg, 0));
9892   // Create vpaddd.
9893   Register DstReg = Root.getOperand(0).getReg();
9894   bool IsKill = Root.getOperand(1).isKill();
9895   MachineInstr *Add =
9896       BuildMI(*MF, MIMetadata(Root), TII.get(AddOpc), DstReg)
9897           .addReg(Root.getOperand(1).getReg(), getKillRegState(IsKill))
9898           .addReg(Madd->getOperand(0).getReg(), getKillRegState(true));
9899   InsInstrs.push_back(Madd);
9900   InsInstrs.push_back(Add);
9901   DelInstrs.push_back(&Root);
9902 }
9903 
9904 void X86InstrInfo::genAlternativeCodeSequence(
9905     MachineInstr &Root, MachineCombinerPattern Pattern,
9906     SmallVectorImpl<MachineInstr *> &InsInstrs,
9907     SmallVectorImpl<MachineInstr *> &DelInstrs,
9908     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
9909   switch (Pattern) {
9910   default:
9911     // Reassociate instructions.
9912     TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9913                                                 DelInstrs, InstrIdxForVirtReg);
9914     return;
9915   case MachineCombinerPattern::DPWSSD:
9916     genAlternativeDpCodeSequence(Root, *this, InsInstrs, DelInstrs,
9917                                  InstrIdxForVirtReg);
9918     return;
9919   }
9920 }
9921 
9922 #define GET_INSTRINFO_HELPERS
9923 #include "X86GenInstrInfo.inc"
9924