1 //===-- X86InstrInfo.cpp - X86 Instruction Information --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the X86 implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86InstrInfo.h"
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86InstrFoldTables.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Sequence.h"
23 #include "llvm/CodeGen/LivePhysRegs.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetOptions.h"
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "x86-instr-info"
47 
48 #define GET_INSTRINFO_CTOR_DTOR
49 #include "X86GenInstrInfo.inc"
50 
51 static cl::opt<bool>
52     NoFusing("disable-spill-fusing",
53              cl::desc("Disable fusing of spill code into instructions"),
54              cl::Hidden);
55 static cl::opt<bool>
56 PrintFailedFusing("print-failed-fuse-candidates",
57                   cl::desc("Print instructions that the allocator wants to"
58                            " fuse, but the X86 backend currently can't"),
59                   cl::Hidden);
60 static cl::opt<bool>
61 ReMatPICStubLoad("remat-pic-stub-load",
62                  cl::desc("Re-materialize load from stub in PIC mode"),
63                  cl::init(false), cl::Hidden);
64 static cl::opt<unsigned>
65 PartialRegUpdateClearance("partial-reg-update-clearance",
66                           cl::desc("Clearance between two register writes "
67                                    "for inserting XOR to avoid partial "
68                                    "register update"),
69                           cl::init(64), cl::Hidden);
70 static cl::opt<unsigned>
71 UndefRegClearance("undef-reg-clearance",
72                   cl::desc("How many idle instructions we would like before "
73                            "certain undef register reads"),
74                   cl::init(128), cl::Hidden);
75 
76 
77 // Pin the vtable to this file.
78 void X86InstrInfo::anchor() {}
79 
80 X86InstrInfo::X86InstrInfo(X86Subtarget &STI)
81     : X86GenInstrInfo((STI.isTarget64BitLP64() ? X86::ADJCALLSTACKDOWN64
82                                                : X86::ADJCALLSTACKDOWN32),
83                       (STI.isTarget64BitLP64() ? X86::ADJCALLSTACKUP64
84                                                : X86::ADJCALLSTACKUP32),
85                       X86::CATCHRET,
86                       (STI.is64Bit() ? X86::RETQ : X86::RETL)),
87       Subtarget(STI), RI(STI.getTargetTriple()) {
88 }
89 
90 bool
91 X86InstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
92                                     unsigned &SrcReg, unsigned &DstReg,
93                                     unsigned &SubIdx) const {
94   switch (MI.getOpcode()) {
95   default: break;
96   case X86::MOVSX16rr8:
97   case X86::MOVZX16rr8:
98   case X86::MOVSX32rr8:
99   case X86::MOVZX32rr8:
100   case X86::MOVSX64rr8:
101     if (!Subtarget.is64Bit())
102       // It's not always legal to reference the low 8-bit of the larger
103       // register in 32-bit mode.
104       return false;
105     LLVM_FALLTHROUGH;
106   case X86::MOVSX32rr16:
107   case X86::MOVZX32rr16:
108   case X86::MOVSX64rr16:
109   case X86::MOVSX64rr32: {
110     if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
111       // Be conservative.
112       return false;
113     SrcReg = MI.getOperand(1).getReg();
114     DstReg = MI.getOperand(0).getReg();
115     switch (MI.getOpcode()) {
116     default: llvm_unreachable("Unreachable!");
117     case X86::MOVSX16rr8:
118     case X86::MOVZX16rr8:
119     case X86::MOVSX32rr8:
120     case X86::MOVZX32rr8:
121     case X86::MOVSX64rr8:
122       SubIdx = X86::sub_8bit;
123       break;
124     case X86::MOVSX32rr16:
125     case X86::MOVZX32rr16:
126     case X86::MOVSX64rr16:
127       SubIdx = X86::sub_16bit;
128       break;
129     case X86::MOVSX64rr32:
130       SubIdx = X86::sub_32bit;
131       break;
132     }
133     return true;
134   }
135   }
136   return false;
137 }
138 
139 int X86InstrInfo::getSPAdjust(const MachineInstr &MI) const {
140   const MachineFunction *MF = MI.getParent()->getParent();
141   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
142 
143   if (isFrameInstr(MI)) {
144     unsigned StackAlign = TFI->getStackAlignment();
145     int SPAdj = alignTo(getFrameSize(MI), StackAlign);
146     SPAdj -= getFrameAdjustment(MI);
147     if (!isFrameSetup(MI))
148       SPAdj = -SPAdj;
149     return SPAdj;
150   }
151 
152   // To know whether a call adjusts the stack, we need information
153   // that is bound to the following ADJCALLSTACKUP pseudo.
154   // Look for the next ADJCALLSTACKUP that follows the call.
155   if (MI.isCall()) {
156     const MachineBasicBlock *MBB = MI.getParent();
157     auto I = ++MachineBasicBlock::const_iterator(MI);
158     for (auto E = MBB->end(); I != E; ++I) {
159       if (I->getOpcode() == getCallFrameDestroyOpcode() ||
160           I->isCall())
161         break;
162     }
163 
164     // If we could not find a frame destroy opcode, then it has already
165     // been simplified, so we don't care.
166     if (I->getOpcode() != getCallFrameDestroyOpcode())
167       return 0;
168 
169     return -(I->getOperand(1).getImm());
170   }
171 
172   // Currently handle only PUSHes we can reasonably expect to see
173   // in call sequences
174   switch (MI.getOpcode()) {
175   default:
176     return 0;
177   case X86::PUSH32i8:
178   case X86::PUSH32r:
179   case X86::PUSH32rmm:
180   case X86::PUSH32rmr:
181   case X86::PUSHi32:
182     return 4;
183   case X86::PUSH64i8:
184   case X86::PUSH64r:
185   case X86::PUSH64rmm:
186   case X86::PUSH64rmr:
187   case X86::PUSH64i32:
188     return 8;
189   }
190 }
191 
192 /// Return true and the FrameIndex if the specified
193 /// operand and follow operands form a reference to the stack frame.
194 bool X86InstrInfo::isFrameOperand(const MachineInstr &MI, unsigned int Op,
195                                   int &FrameIndex) const {
196   if (MI.getOperand(Op + X86::AddrBaseReg).isFI() &&
197       MI.getOperand(Op + X86::AddrScaleAmt).isImm() &&
198       MI.getOperand(Op + X86::AddrIndexReg).isReg() &&
199       MI.getOperand(Op + X86::AddrDisp).isImm() &&
200       MI.getOperand(Op + X86::AddrScaleAmt).getImm() == 1 &&
201       MI.getOperand(Op + X86::AddrIndexReg).getReg() == 0 &&
202       MI.getOperand(Op + X86::AddrDisp).getImm() == 0) {
203     FrameIndex = MI.getOperand(Op + X86::AddrBaseReg).getIndex();
204     return true;
205   }
206   return false;
207 }
208 
209 static bool isFrameLoadOpcode(int Opcode, unsigned &MemBytes) {
210   switch (Opcode) {
211   default:
212     return false;
213   case X86::MOV8rm:
214   case X86::KMOVBkm:
215     MemBytes = 1;
216     return true;
217   case X86::MOV16rm:
218   case X86::KMOVWkm:
219     MemBytes = 2;
220     return true;
221   case X86::MOV32rm:
222   case X86::MOVSSrm:
223   case X86::VMOVSSZrm:
224   case X86::VMOVSSrm:
225   case X86::KMOVDkm:
226     MemBytes = 4;
227     return true;
228   case X86::MOV64rm:
229   case X86::LD_Fp64m:
230   case X86::MOVSDrm:
231   case X86::VMOVSDrm:
232   case X86::VMOVSDZrm:
233   case X86::MMX_MOVD64rm:
234   case X86::MMX_MOVQ64rm:
235   case X86::KMOVQkm:
236     MemBytes = 8;
237     return true;
238   case X86::MOVAPSrm:
239   case X86::MOVUPSrm:
240   case X86::MOVAPDrm:
241   case X86::MOVUPDrm:
242   case X86::MOVDQArm:
243   case X86::MOVDQUrm:
244   case X86::VMOVAPSrm:
245   case X86::VMOVUPSrm:
246   case X86::VMOVAPDrm:
247   case X86::VMOVUPDrm:
248   case X86::VMOVDQArm:
249   case X86::VMOVDQUrm:
250   case X86::VMOVAPSZ128rm:
251   case X86::VMOVUPSZ128rm:
252   case X86::VMOVAPSZ128rm_NOVLX:
253   case X86::VMOVUPSZ128rm_NOVLX:
254   case X86::VMOVAPDZ128rm:
255   case X86::VMOVUPDZ128rm:
256   case X86::VMOVDQU8Z128rm:
257   case X86::VMOVDQU16Z128rm:
258   case X86::VMOVDQA32Z128rm:
259   case X86::VMOVDQU32Z128rm:
260   case X86::VMOVDQA64Z128rm:
261   case X86::VMOVDQU64Z128rm:
262     MemBytes = 16;
263     return true;
264   case X86::VMOVAPSYrm:
265   case X86::VMOVUPSYrm:
266   case X86::VMOVAPDYrm:
267   case X86::VMOVUPDYrm:
268   case X86::VMOVDQAYrm:
269   case X86::VMOVDQUYrm:
270   case X86::VMOVAPSZ256rm:
271   case X86::VMOVUPSZ256rm:
272   case X86::VMOVAPSZ256rm_NOVLX:
273   case X86::VMOVUPSZ256rm_NOVLX:
274   case X86::VMOVAPDZ256rm:
275   case X86::VMOVUPDZ256rm:
276   case X86::VMOVDQU8Z256rm:
277   case X86::VMOVDQU16Z256rm:
278   case X86::VMOVDQA32Z256rm:
279   case X86::VMOVDQU32Z256rm:
280   case X86::VMOVDQA64Z256rm:
281   case X86::VMOVDQU64Z256rm:
282     MemBytes = 32;
283     return true;
284   case X86::VMOVAPSZrm:
285   case X86::VMOVUPSZrm:
286   case X86::VMOVAPDZrm:
287   case X86::VMOVUPDZrm:
288   case X86::VMOVDQU8Zrm:
289   case X86::VMOVDQU16Zrm:
290   case X86::VMOVDQA32Zrm:
291   case X86::VMOVDQU32Zrm:
292   case X86::VMOVDQA64Zrm:
293   case X86::VMOVDQU64Zrm:
294     MemBytes = 64;
295     return true;
296   }
297 }
298 
299 static bool isFrameStoreOpcode(int Opcode, unsigned &MemBytes) {
300   switch (Opcode) {
301   default:
302     return false;
303   case X86::MOV8mr:
304   case X86::KMOVBmk:
305     MemBytes = 1;
306     return true;
307   case X86::MOV16mr:
308   case X86::KMOVWmk:
309     MemBytes = 2;
310     return true;
311   case X86::MOV32mr:
312   case X86::MOVSSmr:
313   case X86::VMOVSSmr:
314   case X86::VMOVSSZmr:
315   case X86::KMOVDmk:
316     MemBytes = 4;
317     return true;
318   case X86::MOV64mr:
319   case X86::ST_FpP64m:
320   case X86::MOVSDmr:
321   case X86::VMOVSDmr:
322   case X86::VMOVSDZmr:
323   case X86::MMX_MOVD64mr:
324   case X86::MMX_MOVQ64mr:
325   case X86::MMX_MOVNTQmr:
326   case X86::KMOVQmk:
327     MemBytes = 8;
328     return true;
329   case X86::MOVAPSmr:
330   case X86::MOVUPSmr:
331   case X86::MOVAPDmr:
332   case X86::MOVUPDmr:
333   case X86::MOVDQAmr:
334   case X86::MOVDQUmr:
335   case X86::VMOVAPSmr:
336   case X86::VMOVUPSmr:
337   case X86::VMOVAPDmr:
338   case X86::VMOVUPDmr:
339   case X86::VMOVDQAmr:
340   case X86::VMOVDQUmr:
341   case X86::VMOVUPSZ128mr:
342   case X86::VMOVAPSZ128mr:
343   case X86::VMOVUPSZ128mr_NOVLX:
344   case X86::VMOVAPSZ128mr_NOVLX:
345   case X86::VMOVUPDZ128mr:
346   case X86::VMOVAPDZ128mr:
347   case X86::VMOVDQA32Z128mr:
348   case X86::VMOVDQU32Z128mr:
349   case X86::VMOVDQA64Z128mr:
350   case X86::VMOVDQU64Z128mr:
351   case X86::VMOVDQU8Z128mr:
352   case X86::VMOVDQU16Z128mr:
353     MemBytes = 16;
354     return true;
355   case X86::VMOVUPSYmr:
356   case X86::VMOVAPSYmr:
357   case X86::VMOVUPDYmr:
358   case X86::VMOVAPDYmr:
359   case X86::VMOVDQUYmr:
360   case X86::VMOVDQAYmr:
361   case X86::VMOVUPSZ256mr:
362   case X86::VMOVAPSZ256mr:
363   case X86::VMOVUPSZ256mr_NOVLX:
364   case X86::VMOVAPSZ256mr_NOVLX:
365   case X86::VMOVUPDZ256mr:
366   case X86::VMOVAPDZ256mr:
367   case X86::VMOVDQU8Z256mr:
368   case X86::VMOVDQU16Z256mr:
369   case X86::VMOVDQA32Z256mr:
370   case X86::VMOVDQU32Z256mr:
371   case X86::VMOVDQA64Z256mr:
372   case X86::VMOVDQU64Z256mr:
373     MemBytes = 32;
374     return true;
375   case X86::VMOVUPSZmr:
376   case X86::VMOVAPSZmr:
377   case X86::VMOVUPDZmr:
378   case X86::VMOVAPDZmr:
379   case X86::VMOVDQU8Zmr:
380   case X86::VMOVDQU16Zmr:
381   case X86::VMOVDQA32Zmr:
382   case X86::VMOVDQU32Zmr:
383   case X86::VMOVDQA64Zmr:
384   case X86::VMOVDQU64Zmr:
385     MemBytes = 64;
386     return true;
387   }
388   return false;
389 }
390 
391 unsigned X86InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
392                                            int &FrameIndex) const {
393   unsigned Dummy;
394   return X86InstrInfo::isLoadFromStackSlot(MI, FrameIndex, Dummy);
395 }
396 
397 unsigned X86InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
398                                            int &FrameIndex,
399                                            unsigned &MemBytes) const {
400   if (isFrameLoadOpcode(MI.getOpcode(), MemBytes))
401     if (MI.getOperand(0).getSubReg() == 0 && isFrameOperand(MI, 1, FrameIndex))
402       return MI.getOperand(0).getReg();
403   return 0;
404 }
405 
406 unsigned X86InstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
407                                                  int &FrameIndex) const {
408   unsigned Dummy;
409   if (isFrameLoadOpcode(MI.getOpcode(), Dummy)) {
410     unsigned Reg;
411     if ((Reg = isLoadFromStackSlot(MI, FrameIndex)))
412       return Reg;
413     // Check for post-frame index elimination operations
414     SmallVector<const MachineMemOperand *, 1> Accesses;
415     if (hasLoadFromStackSlot(MI, Accesses)) {
416       FrameIndex =
417           cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
418               ->getFrameIndex();
419       return 1;
420     }
421   }
422   return 0;
423 }
424 
425 unsigned X86InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
426                                           int &FrameIndex) const {
427   unsigned Dummy;
428   return X86InstrInfo::isStoreToStackSlot(MI, FrameIndex, Dummy);
429 }
430 
431 unsigned X86InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
432                                           int &FrameIndex,
433                                           unsigned &MemBytes) const {
434   if (isFrameStoreOpcode(MI.getOpcode(), MemBytes))
435     if (MI.getOperand(X86::AddrNumOperands).getSubReg() == 0 &&
436         isFrameOperand(MI, 0, FrameIndex))
437       return MI.getOperand(X86::AddrNumOperands).getReg();
438   return 0;
439 }
440 
441 unsigned X86InstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
442                                                 int &FrameIndex) const {
443   unsigned Dummy;
444   if (isFrameStoreOpcode(MI.getOpcode(), Dummy)) {
445     unsigned Reg;
446     if ((Reg = isStoreToStackSlot(MI, FrameIndex)))
447       return Reg;
448     // Check for post-frame index elimination operations
449     SmallVector<const MachineMemOperand *, 1> Accesses;
450     if (hasStoreToStackSlot(MI, Accesses)) {
451       FrameIndex =
452           cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
453               ->getFrameIndex();
454       return 1;
455     }
456   }
457   return 0;
458 }
459 
460 /// Return true if register is PIC base; i.e.g defined by X86::MOVPC32r.
461 static bool regIsPICBase(unsigned BaseReg, const MachineRegisterInfo &MRI) {
462   // Don't waste compile time scanning use-def chains of physregs.
463   if (!TargetRegisterInfo::isVirtualRegister(BaseReg))
464     return false;
465   bool isPICBase = false;
466   for (MachineRegisterInfo::def_instr_iterator I = MRI.def_instr_begin(BaseReg),
467          E = MRI.def_instr_end(); I != E; ++I) {
468     MachineInstr *DefMI = &*I;
469     if (DefMI->getOpcode() != X86::MOVPC32r)
470       return false;
471     assert(!isPICBase && "More than one PIC base?");
472     isPICBase = true;
473   }
474   return isPICBase;
475 }
476 
477 bool X86InstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
478                                                      AliasAnalysis *AA) const {
479   switch (MI.getOpcode()) {
480   default: break;
481   case X86::MOV8rm:
482   case X86::MOV8rm_NOREX:
483   case X86::MOV16rm:
484   case X86::MOV32rm:
485   case X86::MOV64rm:
486   case X86::LD_Fp64m:
487   case X86::MOVSSrm:
488   case X86::MOVSDrm:
489   case X86::MOVAPSrm:
490   case X86::MOVUPSrm:
491   case X86::MOVAPDrm:
492   case X86::MOVUPDrm:
493   case X86::MOVDQArm:
494   case X86::MOVDQUrm:
495   case X86::VMOVSSrm:
496   case X86::VMOVSDrm:
497   case X86::VMOVAPSrm:
498   case X86::VMOVUPSrm:
499   case X86::VMOVAPDrm:
500   case X86::VMOVUPDrm:
501   case X86::VMOVDQArm:
502   case X86::VMOVDQUrm:
503   case X86::VMOVAPSYrm:
504   case X86::VMOVUPSYrm:
505   case X86::VMOVAPDYrm:
506   case X86::VMOVUPDYrm:
507   case X86::VMOVDQAYrm:
508   case X86::VMOVDQUYrm:
509   case X86::MMX_MOVD64rm:
510   case X86::MMX_MOVQ64rm:
511   // AVX-512
512   case X86::VMOVSSZrm:
513   case X86::VMOVSDZrm:
514   case X86::VMOVAPDZ128rm:
515   case X86::VMOVAPDZ256rm:
516   case X86::VMOVAPDZrm:
517   case X86::VMOVAPSZ128rm:
518   case X86::VMOVAPSZ256rm:
519   case X86::VMOVAPSZ128rm_NOVLX:
520   case X86::VMOVAPSZ256rm_NOVLX:
521   case X86::VMOVAPSZrm:
522   case X86::VMOVDQA32Z128rm:
523   case X86::VMOVDQA32Z256rm:
524   case X86::VMOVDQA32Zrm:
525   case X86::VMOVDQA64Z128rm:
526   case X86::VMOVDQA64Z256rm:
527   case X86::VMOVDQA64Zrm:
528   case X86::VMOVDQU16Z128rm:
529   case X86::VMOVDQU16Z256rm:
530   case X86::VMOVDQU16Zrm:
531   case X86::VMOVDQU32Z128rm:
532   case X86::VMOVDQU32Z256rm:
533   case X86::VMOVDQU32Zrm:
534   case X86::VMOVDQU64Z128rm:
535   case X86::VMOVDQU64Z256rm:
536   case X86::VMOVDQU64Zrm:
537   case X86::VMOVDQU8Z128rm:
538   case X86::VMOVDQU8Z256rm:
539   case X86::VMOVDQU8Zrm:
540   case X86::VMOVUPDZ128rm:
541   case X86::VMOVUPDZ256rm:
542   case X86::VMOVUPDZrm:
543   case X86::VMOVUPSZ128rm:
544   case X86::VMOVUPSZ256rm:
545   case X86::VMOVUPSZ128rm_NOVLX:
546   case X86::VMOVUPSZ256rm_NOVLX:
547   case X86::VMOVUPSZrm: {
548     // Loads from constant pools are trivially rematerializable.
549     if (MI.getOperand(1 + X86::AddrBaseReg).isReg() &&
550         MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
551         MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
552         MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
553         MI.isDereferenceableInvariantLoad(AA)) {
554       unsigned BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
555       if (BaseReg == 0 || BaseReg == X86::RIP)
556         return true;
557       // Allow re-materialization of PIC load.
558       if (!ReMatPICStubLoad && MI.getOperand(1 + X86::AddrDisp).isGlobal())
559         return false;
560       const MachineFunction &MF = *MI.getParent()->getParent();
561       const MachineRegisterInfo &MRI = MF.getRegInfo();
562       return regIsPICBase(BaseReg, MRI);
563     }
564     return false;
565   }
566 
567   case X86::LEA32r:
568   case X86::LEA64r: {
569     if (MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
570         MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
571         MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
572         !MI.getOperand(1 + X86::AddrDisp).isReg()) {
573       // lea fi#, lea GV, etc. are all rematerializable.
574       if (!MI.getOperand(1 + X86::AddrBaseReg).isReg())
575         return true;
576       unsigned BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
577       if (BaseReg == 0)
578         return true;
579       // Allow re-materialization of lea PICBase + x.
580       const MachineFunction &MF = *MI.getParent()->getParent();
581       const MachineRegisterInfo &MRI = MF.getRegInfo();
582       return regIsPICBase(BaseReg, MRI);
583     }
584     return false;
585   }
586   }
587 
588   // All other instructions marked M_REMATERIALIZABLE are always trivially
589   // rematerializable.
590   return true;
591 }
592 
593 bool X86InstrInfo::isSafeToClobberEFLAGS(MachineBasicBlock &MBB,
594                                          MachineBasicBlock::iterator I) const {
595   MachineBasicBlock::iterator E = MBB.end();
596 
597   // For compile time consideration, if we are not able to determine the
598   // safety after visiting 4 instructions in each direction, we will assume
599   // it's not safe.
600   MachineBasicBlock::iterator Iter = I;
601   for (unsigned i = 0; Iter != E && i < 4; ++i) {
602     bool SeenDef = false;
603     for (unsigned j = 0, e = Iter->getNumOperands(); j != e; ++j) {
604       MachineOperand &MO = Iter->getOperand(j);
605       if (MO.isRegMask() && MO.clobbersPhysReg(X86::EFLAGS))
606         SeenDef = true;
607       if (!MO.isReg())
608         continue;
609       if (MO.getReg() == X86::EFLAGS) {
610         if (MO.isUse())
611           return false;
612         SeenDef = true;
613       }
614     }
615 
616     if (SeenDef)
617       // This instruction defines EFLAGS, no need to look any further.
618       return true;
619     ++Iter;
620     // Skip over debug instructions.
621     while (Iter != E && Iter->isDebugInstr())
622       ++Iter;
623   }
624 
625   // It is safe to clobber EFLAGS at the end of a block of no successor has it
626   // live in.
627   if (Iter == E) {
628     for (MachineBasicBlock *S : MBB.successors())
629       if (S->isLiveIn(X86::EFLAGS))
630         return false;
631     return true;
632   }
633 
634   MachineBasicBlock::iterator B = MBB.begin();
635   Iter = I;
636   for (unsigned i = 0; i < 4; ++i) {
637     // If we make it to the beginning of the block, it's safe to clobber
638     // EFLAGS iff EFLAGS is not live-in.
639     if (Iter == B)
640       return !MBB.isLiveIn(X86::EFLAGS);
641 
642     --Iter;
643     // Skip over debug instructions.
644     while (Iter != B && Iter->isDebugInstr())
645       --Iter;
646 
647     bool SawKill = false;
648     for (unsigned j = 0, e = Iter->getNumOperands(); j != e; ++j) {
649       MachineOperand &MO = Iter->getOperand(j);
650       // A register mask may clobber EFLAGS, but we should still look for a
651       // live EFLAGS def.
652       if (MO.isRegMask() && MO.clobbersPhysReg(X86::EFLAGS))
653         SawKill = true;
654       if (MO.isReg() && MO.getReg() == X86::EFLAGS) {
655         if (MO.isDef()) return MO.isDead();
656         if (MO.isKill()) SawKill = true;
657       }
658     }
659 
660     if (SawKill)
661       // This instruction kills EFLAGS and doesn't redefine it, so
662       // there's no need to look further.
663       return true;
664   }
665 
666   // Conservative answer.
667   return false;
668 }
669 
670 void X86InstrInfo::reMaterialize(MachineBasicBlock &MBB,
671                                  MachineBasicBlock::iterator I,
672                                  unsigned DestReg, unsigned SubIdx,
673                                  const MachineInstr &Orig,
674                                  const TargetRegisterInfo &TRI) const {
675   bool ClobbersEFLAGS = false;
676   for (const MachineOperand &MO : Orig.operands()) {
677     if (MO.isReg() && MO.isDef() && MO.getReg() == X86::EFLAGS) {
678       ClobbersEFLAGS = true;
679       break;
680     }
681   }
682 
683   if (ClobbersEFLAGS && !isSafeToClobberEFLAGS(MBB, I)) {
684     // The instruction clobbers EFLAGS. Re-materialize as MOV32ri to avoid side
685     // effects.
686     int Value;
687     switch (Orig.getOpcode()) {
688     case X86::MOV32r0:  Value = 0; break;
689     case X86::MOV32r1:  Value = 1; break;
690     case X86::MOV32r_1: Value = -1; break;
691     default:
692       llvm_unreachable("Unexpected instruction!");
693     }
694 
695     const DebugLoc &DL = Orig.getDebugLoc();
696     BuildMI(MBB, I, DL, get(X86::MOV32ri))
697         .add(Orig.getOperand(0))
698         .addImm(Value);
699   } else {
700     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
701     MBB.insert(I, MI);
702   }
703 
704   MachineInstr &NewMI = *std::prev(I);
705   NewMI.substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
706 }
707 
708 /// True if MI has a condition code def, e.g. EFLAGS, that is not marked dead.
709 bool X86InstrInfo::hasLiveCondCodeDef(MachineInstr &MI) const {
710   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
711     MachineOperand &MO = MI.getOperand(i);
712     if (MO.isReg() && MO.isDef() &&
713         MO.getReg() == X86::EFLAGS && !MO.isDead()) {
714       return true;
715     }
716   }
717   return false;
718 }
719 
720 /// Check whether the shift count for a machine operand is non-zero.
721 inline static unsigned getTruncatedShiftCount(MachineInstr &MI,
722                                               unsigned ShiftAmtOperandIdx) {
723   // The shift count is six bits with the REX.W prefix and five bits without.
724   unsigned ShiftCountMask = (MI.getDesc().TSFlags & X86II::REX_W) ? 63 : 31;
725   unsigned Imm = MI.getOperand(ShiftAmtOperandIdx).getImm();
726   return Imm & ShiftCountMask;
727 }
728 
729 /// Check whether the given shift count is appropriate
730 /// can be represented by a LEA instruction.
731 inline static bool isTruncatedShiftCountForLEA(unsigned ShAmt) {
732   // Left shift instructions can be transformed into load-effective-address
733   // instructions if we can encode them appropriately.
734   // A LEA instruction utilizes a SIB byte to encode its scale factor.
735   // The SIB.scale field is two bits wide which means that we can encode any
736   // shift amount less than 4.
737   return ShAmt < 4 && ShAmt > 0;
738 }
739 
740 bool X86InstrInfo::classifyLEAReg(MachineInstr &MI, const MachineOperand &Src,
741                                   unsigned Opc, bool AllowSP, unsigned &NewSrc,
742                                   bool &isKill, bool &isUndef,
743                                   MachineOperand &ImplicitOp,
744                                   LiveVariables *LV) const {
745   MachineFunction &MF = *MI.getParent()->getParent();
746   const TargetRegisterClass *RC;
747   if (AllowSP) {
748     RC = Opc != X86::LEA32r ? &X86::GR64RegClass : &X86::GR32RegClass;
749   } else {
750     RC = Opc != X86::LEA32r ?
751       &X86::GR64_NOSPRegClass : &X86::GR32_NOSPRegClass;
752   }
753   unsigned SrcReg = Src.getReg();
754 
755   // For both LEA64 and LEA32 the register already has essentially the right
756   // type (32-bit or 64-bit) we may just need to forbid SP.
757   if (Opc != X86::LEA64_32r) {
758     NewSrc = SrcReg;
759     isKill = Src.isKill();
760     isUndef = Src.isUndef();
761 
762     if (TargetRegisterInfo::isVirtualRegister(NewSrc) &&
763         !MF.getRegInfo().constrainRegClass(NewSrc, RC))
764       return false;
765 
766     return true;
767   }
768 
769   // This is for an LEA64_32r and incoming registers are 32-bit. One way or
770   // another we need to add 64-bit registers to the final MI.
771   if (TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
772     ImplicitOp = Src;
773     ImplicitOp.setImplicit();
774 
775     NewSrc = getX86SubSuperRegister(Src.getReg(), 64);
776     isKill = Src.isKill();
777     isUndef = Src.isUndef();
778   } else {
779     // Virtual register of the wrong class, we have to create a temporary 64-bit
780     // vreg to feed into the LEA.
781     NewSrc = MF.getRegInfo().createVirtualRegister(RC);
782     MachineInstr *Copy =
783         BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(TargetOpcode::COPY))
784             .addReg(NewSrc, RegState::Define | RegState::Undef, X86::sub_32bit)
785             .add(Src);
786 
787     // Which is obviously going to be dead after we're done with it.
788     isKill = true;
789     isUndef = false;
790 
791     if (LV)
792       LV->replaceKillInstruction(SrcReg, MI, *Copy);
793   }
794 
795   // We've set all the parameters without issue.
796   return true;
797 }
798 
799 /// Helper for convertToThreeAddress when 16-bit LEA is disabled, use 32-bit
800 /// LEA to form 3-address code by promoting to a 32-bit superregister and then
801 /// truncating back down to a 16-bit subregister.
802 MachineInstr *X86InstrInfo::convertToThreeAddressWithLEA(
803     unsigned MIOpc, MachineFunction::iterator &MFI, MachineInstr &MI,
804     LiveVariables *LV) const {
805   MachineBasicBlock::iterator MBBI = MI.getIterator();
806   unsigned Dest = MI.getOperand(0).getReg();
807   unsigned Src = MI.getOperand(1).getReg();
808   bool isDead = MI.getOperand(0).isDead();
809   bool isKill = MI.getOperand(1).isKill();
810 
811   MachineRegisterInfo &RegInfo = MFI->getParent()->getRegInfo();
812   unsigned leaOutReg = RegInfo.createVirtualRegister(&X86::GR32RegClass);
813   unsigned Opc, leaInReg;
814   if (Subtarget.is64Bit()) {
815     Opc = X86::LEA64_32r;
816     leaInReg = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
817   } else {
818     Opc = X86::LEA32r;
819     leaInReg = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
820   }
821 
822   // Build and insert into an implicit UNDEF value. This is OK because
823   // well be shifting and then extracting the lower 16-bits.
824   // This has the potential to cause partial register stall. e.g.
825   //   movw    (%rbp,%rcx,2), %dx
826   //   leal    -65(%rdx), %esi
827   // But testing has shown this *does* help performance in 64-bit mode (at
828   // least on modern x86 machines).
829   BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), leaInReg);
830   MachineInstr *InsMI =
831       BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
832           .addReg(leaInReg, RegState::Define, X86::sub_16bit)
833           .addReg(Src, getKillRegState(isKill));
834 
835   MachineInstrBuilder MIB =
836       BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(Opc), leaOutReg);
837   switch (MIOpc) {
838   default: llvm_unreachable("Unreachable!");
839   case X86::SHL16ri: {
840     unsigned ShAmt = MI.getOperand(2).getImm();
841     MIB.addReg(0).addImm(1ULL << ShAmt)
842        .addReg(leaInReg, RegState::Kill).addImm(0).addReg(0);
843     break;
844   }
845   case X86::INC16r:
846     addRegOffset(MIB, leaInReg, true, 1);
847     break;
848   case X86::DEC16r:
849     addRegOffset(MIB, leaInReg, true, -1);
850     break;
851   case X86::ADD16ri:
852   case X86::ADD16ri8:
853   case X86::ADD16ri_DB:
854   case X86::ADD16ri8_DB:
855     addRegOffset(MIB, leaInReg, true, MI.getOperand(2).getImm());
856     break;
857   case X86::ADD16rr:
858   case X86::ADD16rr_DB: {
859     unsigned Src2 = MI.getOperand(2).getReg();
860     bool isKill2 = MI.getOperand(2).isKill();
861     unsigned leaInReg2 = 0;
862     MachineInstr *InsMI2 = nullptr;
863     if (Src == Src2) {
864       // ADD16rr killed %reg1028, %reg1028
865       // just a single insert_subreg.
866       addRegReg(MIB, leaInReg, true, leaInReg, false);
867     } else {
868       if (Subtarget.is64Bit())
869         leaInReg2 = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
870       else
871         leaInReg2 = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
872       // Build and insert into an implicit UNDEF value. This is OK because
873       // well be shifting and then extracting the lower 16-bits.
874       BuildMI(*MFI, &*MIB, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), leaInReg2);
875       InsMI2 = BuildMI(*MFI, &*MIB, MI.getDebugLoc(), get(TargetOpcode::COPY))
876                    .addReg(leaInReg2, RegState::Define, X86::sub_16bit)
877                    .addReg(Src2, getKillRegState(isKill2));
878       addRegReg(MIB, leaInReg, true, leaInReg2, true);
879     }
880     if (LV && isKill2 && InsMI2)
881       LV->replaceKillInstruction(Src2, MI, *InsMI2);
882     break;
883   }
884   }
885 
886   MachineInstr *NewMI = MIB;
887   MachineInstr *ExtMI =
888       BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
889           .addReg(Dest, RegState::Define | getDeadRegState(isDead))
890           .addReg(leaOutReg, RegState::Kill, X86::sub_16bit);
891 
892   if (LV) {
893     // Update live variables
894     LV->getVarInfo(leaInReg).Kills.push_back(NewMI);
895     LV->getVarInfo(leaOutReg).Kills.push_back(ExtMI);
896     if (isKill)
897       LV->replaceKillInstruction(Src, MI, *InsMI);
898     if (isDead)
899       LV->replaceKillInstruction(Dest, MI, *ExtMI);
900   }
901 
902   return ExtMI;
903 }
904 
905 /// This method must be implemented by targets that
906 /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
907 /// may be able to convert a two-address instruction into a true
908 /// three-address instruction on demand.  This allows the X86 target (for
909 /// example) to convert ADD and SHL instructions into LEA instructions if they
910 /// would require register copies due to two-addressness.
911 ///
912 /// This method returns a null pointer if the transformation cannot be
913 /// performed, otherwise it returns the new instruction.
914 ///
915 MachineInstr *
916 X86InstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
917                                     MachineInstr &MI, LiveVariables *LV) const {
918   // The following opcodes also sets the condition code register(s). Only
919   // convert them to equivalent lea if the condition code register def's
920   // are dead!
921   if (hasLiveCondCodeDef(MI))
922     return nullptr;
923 
924   MachineFunction &MF = *MI.getParent()->getParent();
925   // All instructions input are two-addr instructions.  Get the known operands.
926   const MachineOperand &Dest = MI.getOperand(0);
927   const MachineOperand &Src = MI.getOperand(1);
928 
929   MachineInstr *NewMI = nullptr;
930   // FIXME: 16-bit LEA's are really slow on Athlons, but not bad on P4's.  When
931   // we have better subtarget support, enable the 16-bit LEA generation here.
932   // 16-bit LEA is also slow on Core2.
933   bool DisableLEA16 = true;
934   bool is64Bit = Subtarget.is64Bit();
935 
936   unsigned MIOpc = MI.getOpcode();
937   switch (MIOpc) {
938   default: return nullptr;
939   case X86::SHL64ri: {
940     assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
941     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
942     if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
943 
944     // LEA can't handle RSP.
945     if (TargetRegisterInfo::isVirtualRegister(Src.getReg()) &&
946         !MF.getRegInfo().constrainRegClass(Src.getReg(),
947                                            &X86::GR64_NOSPRegClass))
948       return nullptr;
949 
950     NewMI = BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r))
951                 .add(Dest)
952                 .addReg(0)
953                 .addImm(1ULL << ShAmt)
954                 .add(Src)
955                 .addImm(0)
956                 .addReg(0);
957     break;
958   }
959   case X86::SHL32ri: {
960     assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
961     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
962     if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
963 
964     unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
965 
966     // LEA can't handle ESP.
967     bool isKill, isUndef;
968     unsigned SrcReg;
969     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
970     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
971                         SrcReg, isKill, isUndef, ImplicitOp, LV))
972       return nullptr;
973 
974     MachineInstrBuilder MIB =
975         BuildMI(MF, MI.getDebugLoc(), get(Opc))
976             .add(Dest)
977             .addReg(0)
978             .addImm(1ULL << ShAmt)
979             .addReg(SrcReg, getKillRegState(isKill) | getUndefRegState(isUndef))
980             .addImm(0)
981             .addReg(0);
982     if (ImplicitOp.getReg() != 0)
983       MIB.add(ImplicitOp);
984     NewMI = MIB;
985 
986     break;
987   }
988   case X86::SHL16ri: {
989     assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
990     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
991     if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
992 
993     if (DisableLEA16)
994       return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
995                      : nullptr;
996     NewMI = BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r))
997                 .add(Dest)
998                 .addReg(0)
999                 .addImm(1ULL << ShAmt)
1000                 .add(Src)
1001                 .addImm(0)
1002                 .addReg(0);
1003     break;
1004   }
1005   case X86::INC64r:
1006   case X86::INC32r: {
1007     assert(MI.getNumOperands() >= 2 && "Unknown inc instruction!");
1008     unsigned Opc = MIOpc == X86::INC64r ? X86::LEA64r
1009       : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
1010     bool isKill, isUndef;
1011     unsigned SrcReg;
1012     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1013     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
1014                         SrcReg, isKill, isUndef, ImplicitOp, LV))
1015       return nullptr;
1016 
1017     MachineInstrBuilder MIB =
1018         BuildMI(MF, MI.getDebugLoc(), get(Opc))
1019             .add(Dest)
1020             .addReg(SrcReg,
1021                     getKillRegState(isKill) | getUndefRegState(isUndef));
1022     if (ImplicitOp.getReg() != 0)
1023       MIB.add(ImplicitOp);
1024 
1025     NewMI = addOffset(MIB, 1);
1026     break;
1027   }
1028   case X86::INC16r:
1029     if (DisableLEA16)
1030       return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1031                      : nullptr;
1032     assert(MI.getNumOperands() >= 2 && "Unknown inc instruction!");
1033     NewMI = addOffset(
1034         BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest).add(Src), 1);
1035     break;
1036   case X86::DEC64r:
1037   case X86::DEC32r: {
1038     assert(MI.getNumOperands() >= 2 && "Unknown dec instruction!");
1039     unsigned Opc = MIOpc == X86::DEC64r ? X86::LEA64r
1040       : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
1041 
1042     bool isKill, isUndef;
1043     unsigned SrcReg;
1044     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1045     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
1046                         SrcReg, isKill, isUndef, ImplicitOp, LV))
1047       return nullptr;
1048 
1049     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1050                                   .add(Dest)
1051                                   .addReg(SrcReg, getUndefRegState(isUndef) |
1052                                                       getKillRegState(isKill));
1053     if (ImplicitOp.getReg() != 0)
1054       MIB.add(ImplicitOp);
1055 
1056     NewMI = addOffset(MIB, -1);
1057 
1058     break;
1059   }
1060   case X86::DEC16r:
1061     if (DisableLEA16)
1062       return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1063                      : nullptr;
1064     assert(MI.getNumOperands() >= 2 && "Unknown dec instruction!");
1065     NewMI = addOffset(
1066         BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest).add(Src), -1);
1067     break;
1068   case X86::ADD64rr:
1069   case X86::ADD64rr_DB:
1070   case X86::ADD32rr:
1071   case X86::ADD32rr_DB: {
1072     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1073     unsigned Opc;
1074     if (MIOpc == X86::ADD64rr || MIOpc == X86::ADD64rr_DB)
1075       Opc = X86::LEA64r;
1076     else
1077       Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
1078 
1079     bool isKill, isUndef;
1080     unsigned SrcReg;
1081     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1082     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1083                         SrcReg, isKill, isUndef, ImplicitOp, LV))
1084       return nullptr;
1085 
1086     const MachineOperand &Src2 = MI.getOperand(2);
1087     bool isKill2, isUndef2;
1088     unsigned SrcReg2;
1089     MachineOperand ImplicitOp2 = MachineOperand::CreateReg(0, false);
1090     if (!classifyLEAReg(MI, Src2, Opc, /*AllowSP=*/ false,
1091                         SrcReg2, isKill2, isUndef2, ImplicitOp2, LV))
1092       return nullptr;
1093 
1094     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc)).add(Dest);
1095     if (ImplicitOp.getReg() != 0)
1096       MIB.add(ImplicitOp);
1097     if (ImplicitOp2.getReg() != 0)
1098       MIB.add(ImplicitOp2);
1099 
1100     NewMI = addRegReg(MIB, SrcReg, isKill, SrcReg2, isKill2);
1101 
1102     // Preserve undefness of the operands.
1103     NewMI->getOperand(1).setIsUndef(isUndef);
1104     NewMI->getOperand(3).setIsUndef(isUndef2);
1105 
1106     if (LV && Src2.isKill())
1107       LV->replaceKillInstruction(SrcReg2, MI, *NewMI);
1108     break;
1109   }
1110   case X86::ADD16rr:
1111   case X86::ADD16rr_DB: {
1112     if (DisableLEA16)
1113       return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1114                      : nullptr;
1115     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1116     unsigned Src2 = MI.getOperand(2).getReg();
1117     bool isKill2 = MI.getOperand(2).isKill();
1118     NewMI = addRegReg(BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest),
1119                       Src.getReg(), Src.isKill(), Src2, isKill2);
1120 
1121     // Preserve undefness of the operands.
1122     bool isUndef = MI.getOperand(1).isUndef();
1123     bool isUndef2 = MI.getOperand(2).isUndef();
1124     NewMI->getOperand(1).setIsUndef(isUndef);
1125     NewMI->getOperand(3).setIsUndef(isUndef2);
1126 
1127     if (LV && isKill2)
1128       LV->replaceKillInstruction(Src2, MI, *NewMI);
1129     break;
1130   }
1131   case X86::ADD64ri32:
1132   case X86::ADD64ri8:
1133   case X86::ADD64ri32_DB:
1134   case X86::ADD64ri8_DB:
1135     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1136     NewMI = addOffset(
1137         BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r)).add(Dest).add(Src),
1138         MI.getOperand(2));
1139     break;
1140   case X86::ADD32ri:
1141   case X86::ADD32ri8:
1142   case X86::ADD32ri_DB:
1143   case X86::ADD32ri8_DB: {
1144     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1145     unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
1146 
1147     bool isKill, isUndef;
1148     unsigned SrcReg;
1149     MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1150     if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1151                         SrcReg, isKill, isUndef, ImplicitOp, LV))
1152       return nullptr;
1153 
1154     MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1155                                   .add(Dest)
1156                                   .addReg(SrcReg, getUndefRegState(isUndef) |
1157                                                       getKillRegState(isKill));
1158     if (ImplicitOp.getReg() != 0)
1159       MIB.add(ImplicitOp);
1160 
1161     NewMI = addOffset(MIB, MI.getOperand(2));
1162     break;
1163   }
1164   case X86::ADD16ri:
1165   case X86::ADD16ri8:
1166   case X86::ADD16ri_DB:
1167   case X86::ADD16ri8_DB:
1168     if (DisableLEA16)
1169       return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1170                      : nullptr;
1171     assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1172     NewMI = addOffset(
1173         BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest).add(Src),
1174         MI.getOperand(2));
1175     break;
1176 
1177   case X86::VMOVDQU8Z128rmk:
1178   case X86::VMOVDQU8Z256rmk:
1179   case X86::VMOVDQU8Zrmk:
1180   case X86::VMOVDQU16Z128rmk:
1181   case X86::VMOVDQU16Z256rmk:
1182   case X86::VMOVDQU16Zrmk:
1183   case X86::VMOVDQU32Z128rmk: case X86::VMOVDQA32Z128rmk:
1184   case X86::VMOVDQU32Z256rmk: case X86::VMOVDQA32Z256rmk:
1185   case X86::VMOVDQU32Zrmk:    case X86::VMOVDQA32Zrmk:
1186   case X86::VMOVDQU64Z128rmk: case X86::VMOVDQA64Z128rmk:
1187   case X86::VMOVDQU64Z256rmk: case X86::VMOVDQA64Z256rmk:
1188   case X86::VMOVDQU64Zrmk:    case X86::VMOVDQA64Zrmk:
1189   case X86::VMOVUPDZ128rmk:   case X86::VMOVAPDZ128rmk:
1190   case X86::VMOVUPDZ256rmk:   case X86::VMOVAPDZ256rmk:
1191   case X86::VMOVUPDZrmk:      case X86::VMOVAPDZrmk:
1192   case X86::VMOVUPSZ128rmk:   case X86::VMOVAPSZ128rmk:
1193   case X86::VMOVUPSZ256rmk:   case X86::VMOVAPSZ256rmk:
1194   case X86::VMOVUPSZrmk:      case X86::VMOVAPSZrmk: {
1195     unsigned Opc;
1196     switch (MIOpc) {
1197     default: llvm_unreachable("Unreachable!");
1198     case X86::VMOVDQU8Z128rmk:  Opc = X86::VPBLENDMBZ128rmk; break;
1199     case X86::VMOVDQU8Z256rmk:  Opc = X86::VPBLENDMBZ256rmk; break;
1200     case X86::VMOVDQU8Zrmk:     Opc = X86::VPBLENDMBZrmk;    break;
1201     case X86::VMOVDQU16Z128rmk: Opc = X86::VPBLENDMWZ128rmk; break;
1202     case X86::VMOVDQU16Z256rmk: Opc = X86::VPBLENDMWZ256rmk; break;
1203     case X86::VMOVDQU16Zrmk:    Opc = X86::VPBLENDMWZrmk;    break;
1204     case X86::VMOVDQU32Z128rmk: Opc = X86::VPBLENDMDZ128rmk; break;
1205     case X86::VMOVDQU32Z256rmk: Opc = X86::VPBLENDMDZ256rmk; break;
1206     case X86::VMOVDQU32Zrmk:    Opc = X86::VPBLENDMDZrmk;    break;
1207     case X86::VMOVDQU64Z128rmk: Opc = X86::VPBLENDMQZ128rmk; break;
1208     case X86::VMOVDQU64Z256rmk: Opc = X86::VPBLENDMQZ256rmk; break;
1209     case X86::VMOVDQU64Zrmk:    Opc = X86::VPBLENDMQZrmk;    break;
1210     case X86::VMOVUPDZ128rmk:   Opc = X86::VBLENDMPDZ128rmk; break;
1211     case X86::VMOVUPDZ256rmk:   Opc = X86::VBLENDMPDZ256rmk; break;
1212     case X86::VMOVUPDZrmk:      Opc = X86::VBLENDMPDZrmk;    break;
1213     case X86::VMOVUPSZ128rmk:   Opc = X86::VBLENDMPSZ128rmk; break;
1214     case X86::VMOVUPSZ256rmk:   Opc = X86::VBLENDMPSZ256rmk; break;
1215     case X86::VMOVUPSZrmk:      Opc = X86::VBLENDMPSZrmk;    break;
1216     case X86::VMOVDQA32Z128rmk: Opc = X86::VPBLENDMDZ128rmk; break;
1217     case X86::VMOVDQA32Z256rmk: Opc = X86::VPBLENDMDZ256rmk; break;
1218     case X86::VMOVDQA32Zrmk:    Opc = X86::VPBLENDMDZrmk;    break;
1219     case X86::VMOVDQA64Z128rmk: Opc = X86::VPBLENDMQZ128rmk; break;
1220     case X86::VMOVDQA64Z256rmk: Opc = X86::VPBLENDMQZ256rmk; break;
1221     case X86::VMOVDQA64Zrmk:    Opc = X86::VPBLENDMQZrmk;    break;
1222     case X86::VMOVAPDZ128rmk:   Opc = X86::VBLENDMPDZ128rmk; break;
1223     case X86::VMOVAPDZ256rmk:   Opc = X86::VBLENDMPDZ256rmk; break;
1224     case X86::VMOVAPDZrmk:      Opc = X86::VBLENDMPDZrmk;    break;
1225     case X86::VMOVAPSZ128rmk:   Opc = X86::VBLENDMPSZ128rmk; break;
1226     case X86::VMOVAPSZ256rmk:   Opc = X86::VBLENDMPSZ256rmk; break;
1227     case X86::VMOVAPSZrmk:      Opc = X86::VBLENDMPSZrmk;    break;
1228     }
1229 
1230     NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1231               .add(Dest)
1232               .add(MI.getOperand(2))
1233               .add(Src)
1234               .add(MI.getOperand(3))
1235               .add(MI.getOperand(4))
1236               .add(MI.getOperand(5))
1237               .add(MI.getOperand(6))
1238               .add(MI.getOperand(7));
1239     break;
1240   }
1241   case X86::VMOVDQU8Z128rrk:
1242   case X86::VMOVDQU8Z256rrk:
1243   case X86::VMOVDQU8Zrrk:
1244   case X86::VMOVDQU16Z128rrk:
1245   case X86::VMOVDQU16Z256rrk:
1246   case X86::VMOVDQU16Zrrk:
1247   case X86::VMOVDQU32Z128rrk: case X86::VMOVDQA32Z128rrk:
1248   case X86::VMOVDQU32Z256rrk: case X86::VMOVDQA32Z256rrk:
1249   case X86::VMOVDQU32Zrrk:    case X86::VMOVDQA32Zrrk:
1250   case X86::VMOVDQU64Z128rrk: case X86::VMOVDQA64Z128rrk:
1251   case X86::VMOVDQU64Z256rrk: case X86::VMOVDQA64Z256rrk:
1252   case X86::VMOVDQU64Zrrk:    case X86::VMOVDQA64Zrrk:
1253   case X86::VMOVUPDZ128rrk:   case X86::VMOVAPDZ128rrk:
1254   case X86::VMOVUPDZ256rrk:   case X86::VMOVAPDZ256rrk:
1255   case X86::VMOVUPDZrrk:      case X86::VMOVAPDZrrk:
1256   case X86::VMOVUPSZ128rrk:   case X86::VMOVAPSZ128rrk:
1257   case X86::VMOVUPSZ256rrk:   case X86::VMOVAPSZ256rrk:
1258   case X86::VMOVUPSZrrk:      case X86::VMOVAPSZrrk: {
1259     unsigned Opc;
1260     switch (MIOpc) {
1261     default: llvm_unreachable("Unreachable!");
1262     case X86::VMOVDQU8Z128rrk:  Opc = X86::VPBLENDMBZ128rrk; break;
1263     case X86::VMOVDQU8Z256rrk:  Opc = X86::VPBLENDMBZ256rrk; break;
1264     case X86::VMOVDQU8Zrrk:     Opc = X86::VPBLENDMBZrrk;    break;
1265     case X86::VMOVDQU16Z128rrk: Opc = X86::VPBLENDMWZ128rrk; break;
1266     case X86::VMOVDQU16Z256rrk: Opc = X86::VPBLENDMWZ256rrk; break;
1267     case X86::VMOVDQU16Zrrk:    Opc = X86::VPBLENDMWZrrk;    break;
1268     case X86::VMOVDQU32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1269     case X86::VMOVDQU32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1270     case X86::VMOVDQU32Zrrk:    Opc = X86::VPBLENDMDZrrk;    break;
1271     case X86::VMOVDQU64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1272     case X86::VMOVDQU64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1273     case X86::VMOVDQU64Zrrk:    Opc = X86::VPBLENDMQZrrk;    break;
1274     case X86::VMOVUPDZ128rrk:   Opc = X86::VBLENDMPDZ128rrk; break;
1275     case X86::VMOVUPDZ256rrk:   Opc = X86::VBLENDMPDZ256rrk; break;
1276     case X86::VMOVUPDZrrk:      Opc = X86::VBLENDMPDZrrk;    break;
1277     case X86::VMOVUPSZ128rrk:   Opc = X86::VBLENDMPSZ128rrk; break;
1278     case X86::VMOVUPSZ256rrk:   Opc = X86::VBLENDMPSZ256rrk; break;
1279     case X86::VMOVUPSZrrk:      Opc = X86::VBLENDMPSZrrk;    break;
1280     case X86::VMOVDQA32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1281     case X86::VMOVDQA32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1282     case X86::VMOVDQA32Zrrk:    Opc = X86::VPBLENDMDZrrk;    break;
1283     case X86::VMOVDQA64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1284     case X86::VMOVDQA64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1285     case X86::VMOVDQA64Zrrk:    Opc = X86::VPBLENDMQZrrk;    break;
1286     case X86::VMOVAPDZ128rrk:   Opc = X86::VBLENDMPDZ128rrk; break;
1287     case X86::VMOVAPDZ256rrk:   Opc = X86::VBLENDMPDZ256rrk; break;
1288     case X86::VMOVAPDZrrk:      Opc = X86::VBLENDMPDZrrk;    break;
1289     case X86::VMOVAPSZ128rrk:   Opc = X86::VBLENDMPSZ128rrk; break;
1290     case X86::VMOVAPSZ256rrk:   Opc = X86::VBLENDMPSZ256rrk; break;
1291     case X86::VMOVAPSZrrk:      Opc = X86::VBLENDMPSZrrk;    break;
1292     }
1293 
1294     NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1295               .add(Dest)
1296               .add(MI.getOperand(2))
1297               .add(Src)
1298               .add(MI.getOperand(3));
1299     break;
1300   }
1301   }
1302 
1303   if (!NewMI) return nullptr;
1304 
1305   if (LV) {  // Update live variables
1306     if (Src.isKill())
1307       LV->replaceKillInstruction(Src.getReg(), MI, *NewMI);
1308     if (Dest.isDead())
1309       LV->replaceKillInstruction(Dest.getReg(), MI, *NewMI);
1310   }
1311 
1312   MFI->insert(MI.getIterator(), NewMI); // Insert the new inst
1313   return NewMI;
1314 }
1315 
1316 /// This determines which of three possible cases of a three source commute
1317 /// the source indexes correspond to taking into account any mask operands.
1318 /// All prevents commuting a passthru operand. Returns -1 if the commute isn't
1319 /// possible.
1320 /// Case 0 - Possible to commute the first and second operands.
1321 /// Case 1 - Possible to commute the first and third operands.
1322 /// Case 2 - Possible to commute the second and third operands.
1323 static unsigned getThreeSrcCommuteCase(uint64_t TSFlags, unsigned SrcOpIdx1,
1324                                        unsigned SrcOpIdx2) {
1325   // Put the lowest index to SrcOpIdx1 to simplify the checks below.
1326   if (SrcOpIdx1 > SrcOpIdx2)
1327     std::swap(SrcOpIdx1, SrcOpIdx2);
1328 
1329   unsigned Op1 = 1, Op2 = 2, Op3 = 3;
1330   if (X86II::isKMasked(TSFlags)) {
1331     Op2++;
1332     Op3++;
1333   }
1334 
1335   if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op2)
1336     return 0;
1337   if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op3)
1338     return 1;
1339   if (SrcOpIdx1 == Op2 && SrcOpIdx2 == Op3)
1340     return 2;
1341   llvm_unreachable("Unknown three src commute case.");
1342 }
1343 
1344 unsigned X86InstrInfo::getFMA3OpcodeToCommuteOperands(
1345     const MachineInstr &MI, unsigned SrcOpIdx1, unsigned SrcOpIdx2,
1346     const X86InstrFMA3Group &FMA3Group) const {
1347 
1348   unsigned Opc = MI.getOpcode();
1349 
1350   // TODO: Commuting the 1st operand of FMA*_Int requires some additional
1351   // analysis. The commute optimization is legal only if all users of FMA*_Int
1352   // use only the lowest element of the FMA*_Int instruction. Such analysis are
1353   // not implemented yet. So, just return 0 in that case.
1354   // When such analysis are available this place will be the right place for
1355   // calling it.
1356   assert(!(FMA3Group.isIntrinsic() && (SrcOpIdx1 == 1 || SrcOpIdx2 == 1)) &&
1357          "Intrinsic instructions can't commute operand 1");
1358 
1359   // Determine which case this commute is or if it can't be done.
1360   unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1361                                          SrcOpIdx2);
1362   assert(Case < 3 && "Unexpected case number!");
1363 
1364   // Define the FMA forms mapping array that helps to map input FMA form
1365   // to output FMA form to preserve the operation semantics after
1366   // commuting the operands.
1367   const unsigned Form132Index = 0;
1368   const unsigned Form213Index = 1;
1369   const unsigned Form231Index = 2;
1370   static const unsigned FormMapping[][3] = {
1371     // 0: SrcOpIdx1 == 1 && SrcOpIdx2 == 2;
1372     // FMA132 A, C, b; ==> FMA231 C, A, b;
1373     // FMA213 B, A, c; ==> FMA213 A, B, c;
1374     // FMA231 C, A, b; ==> FMA132 A, C, b;
1375     { Form231Index, Form213Index, Form132Index },
1376     // 1: SrcOpIdx1 == 1 && SrcOpIdx2 == 3;
1377     // FMA132 A, c, B; ==> FMA132 B, c, A;
1378     // FMA213 B, a, C; ==> FMA231 C, a, B;
1379     // FMA231 C, a, B; ==> FMA213 B, a, C;
1380     { Form132Index, Form231Index, Form213Index },
1381     // 2: SrcOpIdx1 == 2 && SrcOpIdx2 == 3;
1382     // FMA132 a, C, B; ==> FMA213 a, B, C;
1383     // FMA213 b, A, C; ==> FMA132 b, C, A;
1384     // FMA231 c, A, B; ==> FMA231 c, B, A;
1385     { Form213Index, Form132Index, Form231Index }
1386   };
1387 
1388   unsigned FMAForms[3];
1389   FMAForms[0] = FMA3Group.get132Opcode();
1390   FMAForms[1] = FMA3Group.get213Opcode();
1391   FMAForms[2] = FMA3Group.get231Opcode();
1392   unsigned FormIndex;
1393   for (FormIndex = 0; FormIndex < 3; FormIndex++)
1394     if (Opc == FMAForms[FormIndex])
1395       break;
1396 
1397   // Everything is ready, just adjust the FMA opcode and return it.
1398   FormIndex = FormMapping[Case][FormIndex];
1399   return FMAForms[FormIndex];
1400 }
1401 
1402 static void commuteVPTERNLOG(MachineInstr &MI, unsigned SrcOpIdx1,
1403                              unsigned SrcOpIdx2) {
1404   // Determine which case this commute is or if it can't be done.
1405   unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1406                                          SrcOpIdx2);
1407   assert(Case < 3 && "Unexpected case value!");
1408 
1409   // For each case we need to swap two pairs of bits in the final immediate.
1410   static const uint8_t SwapMasks[3][4] = {
1411     { 0x04, 0x10, 0x08, 0x20 }, // Swap bits 2/4 and 3/5.
1412     { 0x02, 0x10, 0x08, 0x40 }, // Swap bits 1/4 and 3/6.
1413     { 0x02, 0x04, 0x20, 0x40 }, // Swap bits 1/2 and 5/6.
1414   };
1415 
1416   uint8_t Imm = MI.getOperand(MI.getNumOperands()-1).getImm();
1417   // Clear out the bits we are swapping.
1418   uint8_t NewImm = Imm & ~(SwapMasks[Case][0] | SwapMasks[Case][1] |
1419                            SwapMasks[Case][2] | SwapMasks[Case][3]);
1420   // If the immediate had a bit of the pair set, then set the opposite bit.
1421   if (Imm & SwapMasks[Case][0]) NewImm |= SwapMasks[Case][1];
1422   if (Imm & SwapMasks[Case][1]) NewImm |= SwapMasks[Case][0];
1423   if (Imm & SwapMasks[Case][2]) NewImm |= SwapMasks[Case][3];
1424   if (Imm & SwapMasks[Case][3]) NewImm |= SwapMasks[Case][2];
1425   MI.getOperand(MI.getNumOperands()-1).setImm(NewImm);
1426 }
1427 
1428 // Returns true if this is a VPERMI2 or VPERMT2 instruction that can be
1429 // commuted.
1430 static bool isCommutableVPERMV3Instruction(unsigned Opcode) {
1431 #define VPERM_CASES(Suffix) \
1432   case X86::VPERMI2##Suffix##128rr:    case X86::VPERMT2##Suffix##128rr:    \
1433   case X86::VPERMI2##Suffix##256rr:    case X86::VPERMT2##Suffix##256rr:    \
1434   case X86::VPERMI2##Suffix##rr:       case X86::VPERMT2##Suffix##rr:       \
1435   case X86::VPERMI2##Suffix##128rm:    case X86::VPERMT2##Suffix##128rm:    \
1436   case X86::VPERMI2##Suffix##256rm:    case X86::VPERMT2##Suffix##256rm:    \
1437   case X86::VPERMI2##Suffix##rm:       case X86::VPERMT2##Suffix##rm:       \
1438   case X86::VPERMI2##Suffix##128rrkz:  case X86::VPERMT2##Suffix##128rrkz:  \
1439   case X86::VPERMI2##Suffix##256rrkz:  case X86::VPERMT2##Suffix##256rrkz:  \
1440   case X86::VPERMI2##Suffix##rrkz:     case X86::VPERMT2##Suffix##rrkz:     \
1441   case X86::VPERMI2##Suffix##128rmkz:  case X86::VPERMT2##Suffix##128rmkz:  \
1442   case X86::VPERMI2##Suffix##256rmkz:  case X86::VPERMT2##Suffix##256rmkz:  \
1443   case X86::VPERMI2##Suffix##rmkz:     case X86::VPERMT2##Suffix##rmkz:
1444 
1445 #define VPERM_CASES_BROADCAST(Suffix) \
1446   VPERM_CASES(Suffix) \
1447   case X86::VPERMI2##Suffix##128rmb:   case X86::VPERMT2##Suffix##128rmb:   \
1448   case X86::VPERMI2##Suffix##256rmb:   case X86::VPERMT2##Suffix##256rmb:   \
1449   case X86::VPERMI2##Suffix##rmb:      case X86::VPERMT2##Suffix##rmb:      \
1450   case X86::VPERMI2##Suffix##128rmbkz: case X86::VPERMT2##Suffix##128rmbkz: \
1451   case X86::VPERMI2##Suffix##256rmbkz: case X86::VPERMT2##Suffix##256rmbkz: \
1452   case X86::VPERMI2##Suffix##rmbkz:    case X86::VPERMT2##Suffix##rmbkz:
1453 
1454   switch (Opcode) {
1455   default: return false;
1456   VPERM_CASES(B)
1457   VPERM_CASES_BROADCAST(D)
1458   VPERM_CASES_BROADCAST(PD)
1459   VPERM_CASES_BROADCAST(PS)
1460   VPERM_CASES_BROADCAST(Q)
1461   VPERM_CASES(W)
1462     return true;
1463   }
1464 #undef VPERM_CASES_BROADCAST
1465 #undef VPERM_CASES
1466 }
1467 
1468 // Returns commuted opcode for VPERMI2 and VPERMT2 instructions by switching
1469 // from the I opcode to the T opcode and vice versa.
1470 static unsigned getCommutedVPERMV3Opcode(unsigned Opcode) {
1471 #define VPERM_CASES(Orig, New) \
1472   case X86::Orig##128rr:    return X86::New##128rr;   \
1473   case X86::Orig##128rrkz:  return X86::New##128rrkz; \
1474   case X86::Orig##128rm:    return X86::New##128rm;   \
1475   case X86::Orig##128rmkz:  return X86::New##128rmkz; \
1476   case X86::Orig##256rr:    return X86::New##256rr;   \
1477   case X86::Orig##256rrkz:  return X86::New##256rrkz; \
1478   case X86::Orig##256rm:    return X86::New##256rm;   \
1479   case X86::Orig##256rmkz:  return X86::New##256rmkz; \
1480   case X86::Orig##rr:       return X86::New##rr;      \
1481   case X86::Orig##rrkz:     return X86::New##rrkz;    \
1482   case X86::Orig##rm:       return X86::New##rm;      \
1483   case X86::Orig##rmkz:     return X86::New##rmkz;
1484 
1485 #define VPERM_CASES_BROADCAST(Orig, New) \
1486   VPERM_CASES(Orig, New) \
1487   case X86::Orig##128rmb:   return X86::New##128rmb;   \
1488   case X86::Orig##128rmbkz: return X86::New##128rmbkz; \
1489   case X86::Orig##256rmb:   return X86::New##256rmb;   \
1490   case X86::Orig##256rmbkz: return X86::New##256rmbkz; \
1491   case X86::Orig##rmb:      return X86::New##rmb;      \
1492   case X86::Orig##rmbkz:    return X86::New##rmbkz;
1493 
1494   switch (Opcode) {
1495   VPERM_CASES(VPERMI2B, VPERMT2B)
1496   VPERM_CASES_BROADCAST(VPERMI2D,  VPERMT2D)
1497   VPERM_CASES_BROADCAST(VPERMI2PD, VPERMT2PD)
1498   VPERM_CASES_BROADCAST(VPERMI2PS, VPERMT2PS)
1499   VPERM_CASES_BROADCAST(VPERMI2Q,  VPERMT2Q)
1500   VPERM_CASES(VPERMI2W, VPERMT2W)
1501   VPERM_CASES(VPERMT2B, VPERMI2B)
1502   VPERM_CASES_BROADCAST(VPERMT2D,  VPERMI2D)
1503   VPERM_CASES_BROADCAST(VPERMT2PD, VPERMI2PD)
1504   VPERM_CASES_BROADCAST(VPERMT2PS, VPERMI2PS)
1505   VPERM_CASES_BROADCAST(VPERMT2Q,  VPERMI2Q)
1506   VPERM_CASES(VPERMT2W, VPERMI2W)
1507   }
1508 
1509   llvm_unreachable("Unreachable!");
1510 #undef VPERM_CASES_BROADCAST
1511 #undef VPERM_CASES
1512 }
1513 
1514 MachineInstr *X86InstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
1515                                                    unsigned OpIdx1,
1516                                                    unsigned OpIdx2) const {
1517   auto cloneIfNew = [NewMI](MachineInstr &MI) -> MachineInstr & {
1518     if (NewMI)
1519       return *MI.getParent()->getParent()->CloneMachineInstr(&MI);
1520     return MI;
1521   };
1522 
1523   switch (MI.getOpcode()) {
1524   case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
1525   case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
1526   case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
1527   case X86::SHLD32rri8: // A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
1528   case X86::SHRD64rri8: // A = SHRD64rri8 B, C, I -> A = SHLD64rri8 C, B, (64-I)
1529   case X86::SHLD64rri8:{// A = SHLD64rri8 B, C, I -> A = SHRD64rri8 C, B, (64-I)
1530     unsigned Opc;
1531     unsigned Size;
1532     switch (MI.getOpcode()) {
1533     default: llvm_unreachable("Unreachable!");
1534     case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
1535     case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
1536     case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
1537     case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
1538     case X86::SHRD64rri8: Size = 64; Opc = X86::SHLD64rri8; break;
1539     case X86::SHLD64rri8: Size = 64; Opc = X86::SHRD64rri8; break;
1540     }
1541     unsigned Amt = MI.getOperand(3).getImm();
1542     auto &WorkingMI = cloneIfNew(MI);
1543     WorkingMI.setDesc(get(Opc));
1544     WorkingMI.getOperand(3).setImm(Size - Amt);
1545     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1546                                                    OpIdx1, OpIdx2);
1547   }
1548   case X86::PFSUBrr:
1549   case X86::PFSUBRrr: {
1550     // PFSUB  x, y: x = x - y
1551     // PFSUBR x, y: x = y - x
1552     unsigned Opc =
1553         (X86::PFSUBRrr == MI.getOpcode() ? X86::PFSUBrr : X86::PFSUBRrr);
1554     auto &WorkingMI = cloneIfNew(MI);
1555     WorkingMI.setDesc(get(Opc));
1556     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1557                                                    OpIdx1, OpIdx2);
1558   }
1559   case X86::BLENDPDrri:
1560   case X86::BLENDPSrri:
1561   case X86::VBLENDPDrri:
1562   case X86::VBLENDPSrri:
1563     // If we're optimizing for size, try to use MOVSD/MOVSS.
1564     if (MI.getParent()->getParent()->getFunction().optForSize()) {
1565       unsigned Mask, Opc;
1566       switch (MI.getOpcode()) {
1567       default: llvm_unreachable("Unreachable!");
1568       case X86::BLENDPDrri:  Opc = X86::MOVSDrr;  Mask = 0x03; break;
1569       case X86::BLENDPSrri:  Opc = X86::MOVSSrr;  Mask = 0x0F; break;
1570       case X86::VBLENDPDrri: Opc = X86::VMOVSDrr; Mask = 0x03; break;
1571       case X86::VBLENDPSrri: Opc = X86::VMOVSSrr; Mask = 0x0F; break;
1572       }
1573       if ((MI.getOperand(3).getImm() ^ Mask) == 1) {
1574         auto &WorkingMI = cloneIfNew(MI);
1575         WorkingMI.setDesc(get(Opc));
1576         WorkingMI.RemoveOperand(3);
1577         return TargetInstrInfo::commuteInstructionImpl(WorkingMI,
1578                                                        /*NewMI=*/false,
1579                                                        OpIdx1, OpIdx2);
1580       }
1581     }
1582     LLVM_FALLTHROUGH;
1583   case X86::PBLENDWrri:
1584   case X86::VBLENDPDYrri:
1585   case X86::VBLENDPSYrri:
1586   case X86::VPBLENDDrri:
1587   case X86::VPBLENDWrri:
1588   case X86::VPBLENDDYrri:
1589   case X86::VPBLENDWYrri:{
1590     unsigned Mask;
1591     switch (MI.getOpcode()) {
1592     default: llvm_unreachable("Unreachable!");
1593     case X86::BLENDPDrri:    Mask = 0x03; break;
1594     case X86::BLENDPSrri:    Mask = 0x0F; break;
1595     case X86::PBLENDWrri:    Mask = 0xFF; break;
1596     case X86::VBLENDPDrri:   Mask = 0x03; break;
1597     case X86::VBLENDPSrri:   Mask = 0x0F; break;
1598     case X86::VBLENDPDYrri:  Mask = 0x0F; break;
1599     case X86::VBLENDPSYrri:  Mask = 0xFF; break;
1600     case X86::VPBLENDDrri:   Mask = 0x0F; break;
1601     case X86::VPBLENDWrri:   Mask = 0xFF; break;
1602     case X86::VPBLENDDYrri:  Mask = 0xFF; break;
1603     case X86::VPBLENDWYrri:  Mask = 0xFF; break;
1604     }
1605     // Only the least significant bits of Imm are used.
1606     unsigned Imm = MI.getOperand(3).getImm() & Mask;
1607     auto &WorkingMI = cloneIfNew(MI);
1608     WorkingMI.getOperand(3).setImm(Mask ^ Imm);
1609     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1610                                                    OpIdx1, OpIdx2);
1611   }
1612   case X86::MOVSDrr:
1613   case X86::MOVSSrr:
1614   case X86::VMOVSDrr:
1615   case X86::VMOVSSrr:{
1616     // On SSE41 or later we can commute a MOVSS/MOVSD to a BLENDPS/BLENDPD.
1617     assert(Subtarget.hasSSE41() && "Commuting MOVSD/MOVSS requires SSE41!");
1618 
1619     unsigned Mask, Opc;
1620     switch (MI.getOpcode()) {
1621     default: llvm_unreachable("Unreachable!");
1622     case X86::MOVSDrr:  Opc = X86::BLENDPDrri;  Mask = 0x02; break;
1623     case X86::MOVSSrr:  Opc = X86::BLENDPSrri;  Mask = 0x0E; break;
1624     case X86::VMOVSDrr: Opc = X86::VBLENDPDrri; Mask = 0x02; break;
1625     case X86::VMOVSSrr: Opc = X86::VBLENDPSrri; Mask = 0x0E; break;
1626     }
1627 
1628     auto &WorkingMI = cloneIfNew(MI);
1629     WorkingMI.setDesc(get(Opc));
1630     WorkingMI.addOperand(MachineOperand::CreateImm(Mask));
1631     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1632                                                    OpIdx1, OpIdx2);
1633   }
1634   case X86::PCLMULQDQrr:
1635   case X86::VPCLMULQDQrr:
1636   case X86::VPCLMULQDQYrr:
1637   case X86::VPCLMULQDQZrr:
1638   case X86::VPCLMULQDQZ128rr:
1639   case X86::VPCLMULQDQZ256rr: {
1640     // SRC1 64bits = Imm[0] ? SRC1[127:64] : SRC1[63:0]
1641     // SRC2 64bits = Imm[4] ? SRC2[127:64] : SRC2[63:0]
1642     unsigned Imm = MI.getOperand(3).getImm();
1643     unsigned Src1Hi = Imm & 0x01;
1644     unsigned Src2Hi = Imm & 0x10;
1645     auto &WorkingMI = cloneIfNew(MI);
1646     WorkingMI.getOperand(3).setImm((Src1Hi << 4) | (Src2Hi >> 4));
1647     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1648                                                    OpIdx1, OpIdx2);
1649   }
1650   case X86::VPCMPBZ128rri:  case X86::VPCMPUBZ128rri:
1651   case X86::VPCMPBZ256rri:  case X86::VPCMPUBZ256rri:
1652   case X86::VPCMPBZrri:     case X86::VPCMPUBZrri:
1653   case X86::VPCMPDZ128rri:  case X86::VPCMPUDZ128rri:
1654   case X86::VPCMPDZ256rri:  case X86::VPCMPUDZ256rri:
1655   case X86::VPCMPDZrri:     case X86::VPCMPUDZrri:
1656   case X86::VPCMPQZ128rri:  case X86::VPCMPUQZ128rri:
1657   case X86::VPCMPQZ256rri:  case X86::VPCMPUQZ256rri:
1658   case X86::VPCMPQZrri:     case X86::VPCMPUQZrri:
1659   case X86::VPCMPWZ128rri:  case X86::VPCMPUWZ128rri:
1660   case X86::VPCMPWZ256rri:  case X86::VPCMPUWZ256rri:
1661   case X86::VPCMPWZrri:     case X86::VPCMPUWZrri:
1662   case X86::VPCMPBZ128rrik: case X86::VPCMPUBZ128rrik:
1663   case X86::VPCMPBZ256rrik: case X86::VPCMPUBZ256rrik:
1664   case X86::VPCMPBZrrik:    case X86::VPCMPUBZrrik:
1665   case X86::VPCMPDZ128rrik: case X86::VPCMPUDZ128rrik:
1666   case X86::VPCMPDZ256rrik: case X86::VPCMPUDZ256rrik:
1667   case X86::VPCMPDZrrik:    case X86::VPCMPUDZrrik:
1668   case X86::VPCMPQZ128rrik: case X86::VPCMPUQZ128rrik:
1669   case X86::VPCMPQZ256rrik: case X86::VPCMPUQZ256rrik:
1670   case X86::VPCMPQZrrik:    case X86::VPCMPUQZrrik:
1671   case X86::VPCMPWZ128rrik: case X86::VPCMPUWZ128rrik:
1672   case X86::VPCMPWZ256rrik: case X86::VPCMPUWZ256rrik:
1673   case X86::VPCMPWZrrik:    case X86::VPCMPUWZrrik: {
1674     // Flip comparison mode immediate (if necessary).
1675     unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm() & 0x7;
1676     Imm = X86::getSwappedVPCMPImm(Imm);
1677     auto &WorkingMI = cloneIfNew(MI);
1678     WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(Imm);
1679     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1680                                                    OpIdx1, OpIdx2);
1681   }
1682   case X86::VPCOMBri: case X86::VPCOMUBri:
1683   case X86::VPCOMDri: case X86::VPCOMUDri:
1684   case X86::VPCOMQri: case X86::VPCOMUQri:
1685   case X86::VPCOMWri: case X86::VPCOMUWri: {
1686     // Flip comparison mode immediate (if necessary).
1687     unsigned Imm = MI.getOperand(3).getImm() & 0x7;
1688     Imm = X86::getSwappedVPCOMImm(Imm);
1689     auto &WorkingMI = cloneIfNew(MI);
1690     WorkingMI.getOperand(3).setImm(Imm);
1691     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1692                                                    OpIdx1, OpIdx2);
1693   }
1694   case X86::VPERM2F128rr:
1695   case X86::VPERM2I128rr: {
1696     // Flip permute source immediate.
1697     // Imm & 0x02: lo = if set, select Op1.lo/hi else Op0.lo/hi.
1698     // Imm & 0x20: hi = if set, select Op1.lo/hi else Op0.lo/hi.
1699     unsigned Imm = MI.getOperand(3).getImm() & 0xFF;
1700     auto &WorkingMI = cloneIfNew(MI);
1701     WorkingMI.getOperand(3).setImm(Imm ^ 0x22);
1702     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1703                                                    OpIdx1, OpIdx2);
1704   }
1705   case X86::MOVHLPSrr:
1706   case X86::UNPCKHPDrr:
1707   case X86::VMOVHLPSrr:
1708   case X86::VUNPCKHPDrr:
1709   case X86::VMOVHLPSZrr:
1710   case X86::VUNPCKHPDZ128rr: {
1711     assert(Subtarget.hasSSE2() && "Commuting MOVHLP/UNPCKHPD requires SSE2!");
1712 
1713     unsigned Opc = MI.getOpcode();
1714     switch (Opc) {
1715     default: llvm_unreachable("Unreachable!");
1716     case X86::MOVHLPSrr:       Opc = X86::UNPCKHPDrr;      break;
1717     case X86::UNPCKHPDrr:      Opc = X86::MOVHLPSrr;       break;
1718     case X86::VMOVHLPSrr:      Opc = X86::VUNPCKHPDrr;     break;
1719     case X86::VUNPCKHPDrr:     Opc = X86::VMOVHLPSrr;      break;
1720     case X86::VMOVHLPSZrr:     Opc = X86::VUNPCKHPDZ128rr; break;
1721     case X86::VUNPCKHPDZ128rr: Opc = X86::VMOVHLPSZrr;     break;
1722     }
1723     auto &WorkingMI = cloneIfNew(MI);
1724     WorkingMI.setDesc(get(Opc));
1725     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1726                                                    OpIdx1, OpIdx2);
1727   }
1728   case X86::CMOVB16rr:  case X86::CMOVB32rr:  case X86::CMOVB64rr:
1729   case X86::CMOVAE16rr: case X86::CMOVAE32rr: case X86::CMOVAE64rr:
1730   case X86::CMOVE16rr:  case X86::CMOVE32rr:  case X86::CMOVE64rr:
1731   case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
1732   case X86::CMOVBE16rr: case X86::CMOVBE32rr: case X86::CMOVBE64rr:
1733   case X86::CMOVA16rr:  case X86::CMOVA32rr:  case X86::CMOVA64rr:
1734   case X86::CMOVL16rr:  case X86::CMOVL32rr:  case X86::CMOVL64rr:
1735   case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
1736   case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
1737   case X86::CMOVG16rr:  case X86::CMOVG32rr:  case X86::CMOVG64rr:
1738   case X86::CMOVS16rr:  case X86::CMOVS32rr:  case X86::CMOVS64rr:
1739   case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
1740   case X86::CMOVP16rr:  case X86::CMOVP32rr:  case X86::CMOVP64rr:
1741   case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
1742   case X86::CMOVO16rr:  case X86::CMOVO32rr:  case X86::CMOVO64rr:
1743   case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr: {
1744     unsigned Opc;
1745     switch (MI.getOpcode()) {
1746     default: llvm_unreachable("Unreachable!");
1747     case X86::CMOVB16rr:  Opc = X86::CMOVAE16rr; break;
1748     case X86::CMOVB32rr:  Opc = X86::CMOVAE32rr; break;
1749     case X86::CMOVB64rr:  Opc = X86::CMOVAE64rr; break;
1750     case X86::CMOVAE16rr: Opc = X86::CMOVB16rr; break;
1751     case X86::CMOVAE32rr: Opc = X86::CMOVB32rr; break;
1752     case X86::CMOVAE64rr: Opc = X86::CMOVB64rr; break;
1753     case X86::CMOVE16rr:  Opc = X86::CMOVNE16rr; break;
1754     case X86::CMOVE32rr:  Opc = X86::CMOVNE32rr; break;
1755     case X86::CMOVE64rr:  Opc = X86::CMOVNE64rr; break;
1756     case X86::CMOVNE16rr: Opc = X86::CMOVE16rr; break;
1757     case X86::CMOVNE32rr: Opc = X86::CMOVE32rr; break;
1758     case X86::CMOVNE64rr: Opc = X86::CMOVE64rr; break;
1759     case X86::CMOVBE16rr: Opc = X86::CMOVA16rr; break;
1760     case X86::CMOVBE32rr: Opc = X86::CMOVA32rr; break;
1761     case X86::CMOVBE64rr: Opc = X86::CMOVA64rr; break;
1762     case X86::CMOVA16rr:  Opc = X86::CMOVBE16rr; break;
1763     case X86::CMOVA32rr:  Opc = X86::CMOVBE32rr; break;
1764     case X86::CMOVA64rr:  Opc = X86::CMOVBE64rr; break;
1765     case X86::CMOVL16rr:  Opc = X86::CMOVGE16rr; break;
1766     case X86::CMOVL32rr:  Opc = X86::CMOVGE32rr; break;
1767     case X86::CMOVL64rr:  Opc = X86::CMOVGE64rr; break;
1768     case X86::CMOVGE16rr: Opc = X86::CMOVL16rr; break;
1769     case X86::CMOVGE32rr: Opc = X86::CMOVL32rr; break;
1770     case X86::CMOVGE64rr: Opc = X86::CMOVL64rr; break;
1771     case X86::CMOVLE16rr: Opc = X86::CMOVG16rr; break;
1772     case X86::CMOVLE32rr: Opc = X86::CMOVG32rr; break;
1773     case X86::CMOVLE64rr: Opc = X86::CMOVG64rr; break;
1774     case X86::CMOVG16rr:  Opc = X86::CMOVLE16rr; break;
1775     case X86::CMOVG32rr:  Opc = X86::CMOVLE32rr; break;
1776     case X86::CMOVG64rr:  Opc = X86::CMOVLE64rr; break;
1777     case X86::CMOVS16rr:  Opc = X86::CMOVNS16rr; break;
1778     case X86::CMOVS32rr:  Opc = X86::CMOVNS32rr; break;
1779     case X86::CMOVS64rr:  Opc = X86::CMOVNS64rr; break;
1780     case X86::CMOVNS16rr: Opc = X86::CMOVS16rr; break;
1781     case X86::CMOVNS32rr: Opc = X86::CMOVS32rr; break;
1782     case X86::CMOVNS64rr: Opc = X86::CMOVS64rr; break;
1783     case X86::CMOVP16rr:  Opc = X86::CMOVNP16rr; break;
1784     case X86::CMOVP32rr:  Opc = X86::CMOVNP32rr; break;
1785     case X86::CMOVP64rr:  Opc = X86::CMOVNP64rr; break;
1786     case X86::CMOVNP16rr: Opc = X86::CMOVP16rr; break;
1787     case X86::CMOVNP32rr: Opc = X86::CMOVP32rr; break;
1788     case X86::CMOVNP64rr: Opc = X86::CMOVP64rr; break;
1789     case X86::CMOVO16rr:  Opc = X86::CMOVNO16rr; break;
1790     case X86::CMOVO32rr:  Opc = X86::CMOVNO32rr; break;
1791     case X86::CMOVO64rr:  Opc = X86::CMOVNO64rr; break;
1792     case X86::CMOVNO16rr: Opc = X86::CMOVO16rr; break;
1793     case X86::CMOVNO32rr: Opc = X86::CMOVO32rr; break;
1794     case X86::CMOVNO64rr: Opc = X86::CMOVO64rr; break;
1795     }
1796     auto &WorkingMI = cloneIfNew(MI);
1797     WorkingMI.setDesc(get(Opc));
1798     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1799                                                    OpIdx1, OpIdx2);
1800   }
1801   case X86::VPTERNLOGDZrri:      case X86::VPTERNLOGDZrmi:
1802   case X86::VPTERNLOGDZ128rri:   case X86::VPTERNLOGDZ128rmi:
1803   case X86::VPTERNLOGDZ256rri:   case X86::VPTERNLOGDZ256rmi:
1804   case X86::VPTERNLOGQZrri:      case X86::VPTERNLOGQZrmi:
1805   case X86::VPTERNLOGQZ128rri:   case X86::VPTERNLOGQZ128rmi:
1806   case X86::VPTERNLOGQZ256rri:   case X86::VPTERNLOGQZ256rmi:
1807   case X86::VPTERNLOGDZrrik:
1808   case X86::VPTERNLOGDZ128rrik:
1809   case X86::VPTERNLOGDZ256rrik:
1810   case X86::VPTERNLOGQZrrik:
1811   case X86::VPTERNLOGQZ128rrik:
1812   case X86::VPTERNLOGQZ256rrik:
1813   case X86::VPTERNLOGDZrrikz:    case X86::VPTERNLOGDZrmikz:
1814   case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
1815   case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
1816   case X86::VPTERNLOGQZrrikz:    case X86::VPTERNLOGQZrmikz:
1817   case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
1818   case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
1819   case X86::VPTERNLOGDZ128rmbi:
1820   case X86::VPTERNLOGDZ256rmbi:
1821   case X86::VPTERNLOGDZrmbi:
1822   case X86::VPTERNLOGQZ128rmbi:
1823   case X86::VPTERNLOGQZ256rmbi:
1824   case X86::VPTERNLOGQZrmbi:
1825   case X86::VPTERNLOGDZ128rmbikz:
1826   case X86::VPTERNLOGDZ256rmbikz:
1827   case X86::VPTERNLOGDZrmbikz:
1828   case X86::VPTERNLOGQZ128rmbikz:
1829   case X86::VPTERNLOGQZ256rmbikz:
1830   case X86::VPTERNLOGQZrmbikz: {
1831     auto &WorkingMI = cloneIfNew(MI);
1832     commuteVPTERNLOG(WorkingMI, OpIdx1, OpIdx2);
1833     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1834                                                    OpIdx1, OpIdx2);
1835   }
1836   default: {
1837     if (isCommutableVPERMV3Instruction(MI.getOpcode())) {
1838       unsigned Opc = getCommutedVPERMV3Opcode(MI.getOpcode());
1839       auto &WorkingMI = cloneIfNew(MI);
1840       WorkingMI.setDesc(get(Opc));
1841       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1842                                                      OpIdx1, OpIdx2);
1843     }
1844 
1845     const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
1846                                                       MI.getDesc().TSFlags);
1847     if (FMA3Group) {
1848       unsigned Opc =
1849         getFMA3OpcodeToCommuteOperands(MI, OpIdx1, OpIdx2, *FMA3Group);
1850       auto &WorkingMI = cloneIfNew(MI);
1851       WorkingMI.setDesc(get(Opc));
1852       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1853                                                      OpIdx1, OpIdx2);
1854     }
1855 
1856     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
1857   }
1858   }
1859 }
1860 
1861 bool
1862 X86InstrInfo::findThreeSrcCommutedOpIndices(const MachineInstr &MI,
1863                                             unsigned &SrcOpIdx1,
1864                                             unsigned &SrcOpIdx2,
1865                                             bool IsIntrinsic) const {
1866   uint64_t TSFlags = MI.getDesc().TSFlags;
1867 
1868   unsigned FirstCommutableVecOp = 1;
1869   unsigned LastCommutableVecOp = 3;
1870   unsigned KMaskOp = -1U;
1871   if (X86II::isKMasked(TSFlags)) {
1872     // For k-zero-masked operations it is Ok to commute the first vector
1873     // operand.
1874     // For regular k-masked operations a conservative choice is done as the
1875     // elements of the first vector operand, for which the corresponding bit
1876     // in the k-mask operand is set to 0, are copied to the result of the
1877     // instruction.
1878     // TODO/FIXME: The commute still may be legal if it is known that the
1879     // k-mask operand is set to either all ones or all zeroes.
1880     // It is also Ok to commute the 1st operand if all users of MI use only
1881     // the elements enabled by the k-mask operand. For example,
1882     //   v4 = VFMADD213PSZrk v1, k, v2, v3; // v1[i] = k[i] ? v2[i]*v1[i]+v3[i]
1883     //                                                     : v1[i];
1884     //   VMOVAPSZmrk <mem_addr>, k, v4; // this is the ONLY user of v4 ->
1885     //                                  // Ok, to commute v1 in FMADD213PSZrk.
1886 
1887     // The k-mask operand has index = 2 for masked and zero-masked operations.
1888     KMaskOp = 2;
1889 
1890     // The operand with index = 1 is used as a source for those elements for
1891     // which the corresponding bit in the k-mask is set to 0.
1892     if (X86II::isKMergeMasked(TSFlags))
1893       FirstCommutableVecOp = 3;
1894 
1895     LastCommutableVecOp++;
1896   } else if (IsIntrinsic) {
1897     // Commuting the first operand of an intrinsic instruction isn't possible
1898     // unless we can prove that only the lowest element of the result is used.
1899     FirstCommutableVecOp = 2;
1900   }
1901 
1902   if (isMem(MI, LastCommutableVecOp))
1903     LastCommutableVecOp--;
1904 
1905   // Only the first RegOpsNum operands are commutable.
1906   // Also, the value 'CommuteAnyOperandIndex' is valid here as it means
1907   // that the operand is not specified/fixed.
1908   if (SrcOpIdx1 != CommuteAnyOperandIndex &&
1909       (SrcOpIdx1 < FirstCommutableVecOp || SrcOpIdx1 > LastCommutableVecOp ||
1910        SrcOpIdx1 == KMaskOp))
1911     return false;
1912   if (SrcOpIdx2 != CommuteAnyOperandIndex &&
1913       (SrcOpIdx2 < FirstCommutableVecOp || SrcOpIdx2 > LastCommutableVecOp ||
1914        SrcOpIdx2 == KMaskOp))
1915     return false;
1916 
1917   // Look for two different register operands assumed to be commutable
1918   // regardless of the FMA opcode. The FMA opcode is adjusted later.
1919   if (SrcOpIdx1 == CommuteAnyOperandIndex ||
1920       SrcOpIdx2 == CommuteAnyOperandIndex) {
1921     unsigned CommutableOpIdx1 = SrcOpIdx1;
1922     unsigned CommutableOpIdx2 = SrcOpIdx2;
1923 
1924     // At least one of operands to be commuted is not specified and
1925     // this method is free to choose appropriate commutable operands.
1926     if (SrcOpIdx1 == SrcOpIdx2)
1927       // Both of operands are not fixed. By default set one of commutable
1928       // operands to the last register operand of the instruction.
1929       CommutableOpIdx2 = LastCommutableVecOp;
1930     else if (SrcOpIdx2 == CommuteAnyOperandIndex)
1931       // Only one of operands is not fixed.
1932       CommutableOpIdx2 = SrcOpIdx1;
1933 
1934     // CommutableOpIdx2 is well defined now. Let's choose another commutable
1935     // operand and assign its index to CommutableOpIdx1.
1936     unsigned Op2Reg = MI.getOperand(CommutableOpIdx2).getReg();
1937     for (CommutableOpIdx1 = LastCommutableVecOp;
1938          CommutableOpIdx1 >= FirstCommutableVecOp; CommutableOpIdx1--) {
1939       // Just ignore and skip the k-mask operand.
1940       if (CommutableOpIdx1 == KMaskOp)
1941         continue;
1942 
1943       // The commuted operands must have different registers.
1944       // Otherwise, the commute transformation does not change anything and
1945       // is useless then.
1946       if (Op2Reg != MI.getOperand(CommutableOpIdx1).getReg())
1947         break;
1948     }
1949 
1950     // No appropriate commutable operands were found.
1951     if (CommutableOpIdx1 < FirstCommutableVecOp)
1952       return false;
1953 
1954     // Assign the found pair of commutable indices to SrcOpIdx1 and SrcOpidx2
1955     // to return those values.
1956     if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
1957                               CommutableOpIdx1, CommutableOpIdx2))
1958       return false;
1959   }
1960 
1961   return true;
1962 }
1963 
1964 bool X86InstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1,
1965                                          unsigned &SrcOpIdx2) const {
1966   const MCInstrDesc &Desc = MI.getDesc();
1967   if (!Desc.isCommutable())
1968     return false;
1969 
1970   switch (MI.getOpcode()) {
1971   case X86::CMPSDrr:
1972   case X86::CMPSSrr:
1973   case X86::CMPPDrri:
1974   case X86::CMPPSrri:
1975   case X86::VCMPSDrr:
1976   case X86::VCMPSSrr:
1977   case X86::VCMPPDrri:
1978   case X86::VCMPPSrri:
1979   case X86::VCMPPDYrri:
1980   case X86::VCMPPSYrri:
1981   case X86::VCMPSDZrr:
1982   case X86::VCMPSSZrr:
1983   case X86::VCMPPDZrri:
1984   case X86::VCMPPSZrri:
1985   case X86::VCMPPDZ128rri:
1986   case X86::VCMPPSZ128rri:
1987   case X86::VCMPPDZ256rri:
1988   case X86::VCMPPSZ256rri: {
1989     // Float comparison can be safely commuted for
1990     // Ordered/Unordered/Equal/NotEqual tests
1991     unsigned Imm = MI.getOperand(3).getImm() & 0x7;
1992     switch (Imm) {
1993     case 0x00: // EQUAL
1994     case 0x03: // UNORDERED
1995     case 0x04: // NOT EQUAL
1996     case 0x07: // ORDERED
1997       // The indices of the commutable operands are 1 and 2.
1998       // Assign them to the returned operand indices here.
1999       return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 1, 2);
2000     }
2001     return false;
2002   }
2003   case X86::MOVSDrr:
2004   case X86::MOVSSrr:
2005   case X86::VMOVSDrr:
2006   case X86::VMOVSSrr:
2007     if (Subtarget.hasSSE41())
2008       return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2009     return false;
2010   case X86::MOVHLPSrr:
2011   case X86::UNPCKHPDrr:
2012   case X86::VMOVHLPSrr:
2013   case X86::VUNPCKHPDrr:
2014   case X86::VMOVHLPSZrr:
2015   case X86::VUNPCKHPDZ128rr:
2016     if (Subtarget.hasSSE2())
2017       return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2018     return false;
2019   case X86::VPTERNLOGDZrri:      case X86::VPTERNLOGDZrmi:
2020   case X86::VPTERNLOGDZ128rri:   case X86::VPTERNLOGDZ128rmi:
2021   case X86::VPTERNLOGDZ256rri:   case X86::VPTERNLOGDZ256rmi:
2022   case X86::VPTERNLOGQZrri:      case X86::VPTERNLOGQZrmi:
2023   case X86::VPTERNLOGQZ128rri:   case X86::VPTERNLOGQZ128rmi:
2024   case X86::VPTERNLOGQZ256rri:   case X86::VPTERNLOGQZ256rmi:
2025   case X86::VPTERNLOGDZrrik:
2026   case X86::VPTERNLOGDZ128rrik:
2027   case X86::VPTERNLOGDZ256rrik:
2028   case X86::VPTERNLOGQZrrik:
2029   case X86::VPTERNLOGQZ128rrik:
2030   case X86::VPTERNLOGQZ256rrik:
2031   case X86::VPTERNLOGDZrrikz:    case X86::VPTERNLOGDZrmikz:
2032   case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
2033   case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
2034   case X86::VPTERNLOGQZrrikz:    case X86::VPTERNLOGQZrmikz:
2035   case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
2036   case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
2037   case X86::VPTERNLOGDZ128rmbi:
2038   case X86::VPTERNLOGDZ256rmbi:
2039   case X86::VPTERNLOGDZrmbi:
2040   case X86::VPTERNLOGQZ128rmbi:
2041   case X86::VPTERNLOGQZ256rmbi:
2042   case X86::VPTERNLOGQZrmbi:
2043   case X86::VPTERNLOGDZ128rmbikz:
2044   case X86::VPTERNLOGDZ256rmbikz:
2045   case X86::VPTERNLOGDZrmbikz:
2046   case X86::VPTERNLOGQZ128rmbikz:
2047   case X86::VPTERNLOGQZ256rmbikz:
2048   case X86::VPTERNLOGQZrmbikz:
2049     return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2050   case X86::VPMADD52HUQZ128r:
2051   case X86::VPMADD52HUQZ128rk:
2052   case X86::VPMADD52HUQZ128rkz:
2053   case X86::VPMADD52HUQZ256r:
2054   case X86::VPMADD52HUQZ256rk:
2055   case X86::VPMADD52HUQZ256rkz:
2056   case X86::VPMADD52HUQZr:
2057   case X86::VPMADD52HUQZrk:
2058   case X86::VPMADD52HUQZrkz:
2059   case X86::VPMADD52LUQZ128r:
2060   case X86::VPMADD52LUQZ128rk:
2061   case X86::VPMADD52LUQZ128rkz:
2062   case X86::VPMADD52LUQZ256r:
2063   case X86::VPMADD52LUQZ256rk:
2064   case X86::VPMADD52LUQZ256rkz:
2065   case X86::VPMADD52LUQZr:
2066   case X86::VPMADD52LUQZrk:
2067   case X86::VPMADD52LUQZrkz: {
2068     unsigned CommutableOpIdx1 = 2;
2069     unsigned CommutableOpIdx2 = 3;
2070     if (X86II::isKMasked(Desc.TSFlags)) {
2071       // Skip the mask register.
2072       ++CommutableOpIdx1;
2073       ++CommutableOpIdx2;
2074     }
2075     if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2076                               CommutableOpIdx1, CommutableOpIdx2))
2077       return false;
2078     if (!MI.getOperand(SrcOpIdx1).isReg() ||
2079         !MI.getOperand(SrcOpIdx2).isReg())
2080       // No idea.
2081       return false;
2082     return true;
2083   }
2084 
2085   default:
2086     const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
2087                                                       MI.getDesc().TSFlags);
2088     if (FMA3Group)
2089       return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2,
2090                                            FMA3Group->isIntrinsic());
2091 
2092     // Handled masked instructions since we need to skip over the mask input
2093     // and the preserved input.
2094     if (X86II::isKMasked(Desc.TSFlags)) {
2095       // First assume that the first input is the mask operand and skip past it.
2096       unsigned CommutableOpIdx1 = Desc.getNumDefs() + 1;
2097       unsigned CommutableOpIdx2 = Desc.getNumDefs() + 2;
2098       // Check if the first input is tied. If there isn't one then we only
2099       // need to skip the mask operand which we did above.
2100       if ((MI.getDesc().getOperandConstraint(Desc.getNumDefs(),
2101                                              MCOI::TIED_TO) != -1)) {
2102         // If this is zero masking instruction with a tied operand, we need to
2103         // move the first index back to the first input since this must
2104         // be a 3 input instruction and we want the first two non-mask inputs.
2105         // Otherwise this is a 2 input instruction with a preserved input and
2106         // mask, so we need to move the indices to skip one more input.
2107         if (X86II::isKMergeMasked(Desc.TSFlags)) {
2108           ++CommutableOpIdx1;
2109           ++CommutableOpIdx2;
2110         } else {
2111           --CommutableOpIdx1;
2112         }
2113       }
2114 
2115       if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2116                                 CommutableOpIdx1, CommutableOpIdx2))
2117         return false;
2118 
2119       if (!MI.getOperand(SrcOpIdx1).isReg() ||
2120           !MI.getOperand(SrcOpIdx2).isReg())
2121         // No idea.
2122         return false;
2123       return true;
2124     }
2125 
2126     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2127   }
2128   return false;
2129 }
2130 
2131 X86::CondCode X86::getCondFromBranchOpc(unsigned BrOpc) {
2132   switch (BrOpc) {
2133   default: return X86::COND_INVALID;
2134   case X86::JE_1:  return X86::COND_E;
2135   case X86::JNE_1: return X86::COND_NE;
2136   case X86::JL_1:  return X86::COND_L;
2137   case X86::JLE_1: return X86::COND_LE;
2138   case X86::JG_1:  return X86::COND_G;
2139   case X86::JGE_1: return X86::COND_GE;
2140   case X86::JB_1:  return X86::COND_B;
2141   case X86::JBE_1: return X86::COND_BE;
2142   case X86::JA_1:  return X86::COND_A;
2143   case X86::JAE_1: return X86::COND_AE;
2144   case X86::JS_1:  return X86::COND_S;
2145   case X86::JNS_1: return X86::COND_NS;
2146   case X86::JP_1:  return X86::COND_P;
2147   case X86::JNP_1: return X86::COND_NP;
2148   case X86::JO_1:  return X86::COND_O;
2149   case X86::JNO_1: return X86::COND_NO;
2150   }
2151 }
2152 
2153 /// Return condition code of a SET opcode.
2154 X86::CondCode X86::getCondFromSETOpc(unsigned Opc) {
2155   switch (Opc) {
2156   default: return X86::COND_INVALID;
2157   case X86::SETAr:  case X86::SETAm:  return X86::COND_A;
2158   case X86::SETAEr: case X86::SETAEm: return X86::COND_AE;
2159   case X86::SETBr:  case X86::SETBm:  return X86::COND_B;
2160   case X86::SETBEr: case X86::SETBEm: return X86::COND_BE;
2161   case X86::SETEr:  case X86::SETEm:  return X86::COND_E;
2162   case X86::SETGr:  case X86::SETGm:  return X86::COND_G;
2163   case X86::SETGEr: case X86::SETGEm: return X86::COND_GE;
2164   case X86::SETLr:  case X86::SETLm:  return X86::COND_L;
2165   case X86::SETLEr: case X86::SETLEm: return X86::COND_LE;
2166   case X86::SETNEr: case X86::SETNEm: return X86::COND_NE;
2167   case X86::SETNOr: case X86::SETNOm: return X86::COND_NO;
2168   case X86::SETNPr: case X86::SETNPm: return X86::COND_NP;
2169   case X86::SETNSr: case X86::SETNSm: return X86::COND_NS;
2170   case X86::SETOr:  case X86::SETOm:  return X86::COND_O;
2171   case X86::SETPr:  case X86::SETPm:  return X86::COND_P;
2172   case X86::SETSr:  case X86::SETSm:  return X86::COND_S;
2173   }
2174 }
2175 
2176 /// Return condition code of a CMov opcode.
2177 X86::CondCode X86::getCondFromCMovOpc(unsigned Opc) {
2178   switch (Opc) {
2179   default: return X86::COND_INVALID;
2180   case X86::CMOVA16rm:  case X86::CMOVA16rr:  case X86::CMOVA32rm:
2181   case X86::CMOVA32rr:  case X86::CMOVA64rm:  case X86::CMOVA64rr:
2182     return X86::COND_A;
2183   case X86::CMOVAE16rm: case X86::CMOVAE16rr: case X86::CMOVAE32rm:
2184   case X86::CMOVAE32rr: case X86::CMOVAE64rm: case X86::CMOVAE64rr:
2185     return X86::COND_AE;
2186   case X86::CMOVB16rm:  case X86::CMOVB16rr:  case X86::CMOVB32rm:
2187   case X86::CMOVB32rr:  case X86::CMOVB64rm:  case X86::CMOVB64rr:
2188     return X86::COND_B;
2189   case X86::CMOVBE16rm: case X86::CMOVBE16rr: case X86::CMOVBE32rm:
2190   case X86::CMOVBE32rr: case X86::CMOVBE64rm: case X86::CMOVBE64rr:
2191     return X86::COND_BE;
2192   case X86::CMOVE16rm:  case X86::CMOVE16rr:  case X86::CMOVE32rm:
2193   case X86::CMOVE32rr:  case X86::CMOVE64rm:  case X86::CMOVE64rr:
2194     return X86::COND_E;
2195   case X86::CMOVG16rm:  case X86::CMOVG16rr:  case X86::CMOVG32rm:
2196   case X86::CMOVG32rr:  case X86::CMOVG64rm:  case X86::CMOVG64rr:
2197     return X86::COND_G;
2198   case X86::CMOVGE16rm: case X86::CMOVGE16rr: case X86::CMOVGE32rm:
2199   case X86::CMOVGE32rr: case X86::CMOVGE64rm: case X86::CMOVGE64rr:
2200     return X86::COND_GE;
2201   case X86::CMOVL16rm:  case X86::CMOVL16rr:  case X86::CMOVL32rm:
2202   case X86::CMOVL32rr:  case X86::CMOVL64rm:  case X86::CMOVL64rr:
2203     return X86::COND_L;
2204   case X86::CMOVLE16rm: case X86::CMOVLE16rr: case X86::CMOVLE32rm:
2205   case X86::CMOVLE32rr: case X86::CMOVLE64rm: case X86::CMOVLE64rr:
2206     return X86::COND_LE;
2207   case X86::CMOVNE16rm: case X86::CMOVNE16rr: case X86::CMOVNE32rm:
2208   case X86::CMOVNE32rr: case X86::CMOVNE64rm: case X86::CMOVNE64rr:
2209     return X86::COND_NE;
2210   case X86::CMOVNO16rm: case X86::CMOVNO16rr: case X86::CMOVNO32rm:
2211   case X86::CMOVNO32rr: case X86::CMOVNO64rm: case X86::CMOVNO64rr:
2212     return X86::COND_NO;
2213   case X86::CMOVNP16rm: case X86::CMOVNP16rr: case X86::CMOVNP32rm:
2214   case X86::CMOVNP32rr: case X86::CMOVNP64rm: case X86::CMOVNP64rr:
2215     return X86::COND_NP;
2216   case X86::CMOVNS16rm: case X86::CMOVNS16rr: case X86::CMOVNS32rm:
2217   case X86::CMOVNS32rr: case X86::CMOVNS64rm: case X86::CMOVNS64rr:
2218     return X86::COND_NS;
2219   case X86::CMOVO16rm:  case X86::CMOVO16rr:  case X86::CMOVO32rm:
2220   case X86::CMOVO32rr:  case X86::CMOVO64rm:  case X86::CMOVO64rr:
2221     return X86::COND_O;
2222   case X86::CMOVP16rm:  case X86::CMOVP16rr:  case X86::CMOVP32rm:
2223   case X86::CMOVP32rr:  case X86::CMOVP64rm:  case X86::CMOVP64rr:
2224     return X86::COND_P;
2225   case X86::CMOVS16rm:  case X86::CMOVS16rr:  case X86::CMOVS32rm:
2226   case X86::CMOVS32rr:  case X86::CMOVS64rm:  case X86::CMOVS64rr:
2227     return X86::COND_S;
2228   }
2229 }
2230 
2231 unsigned X86::GetCondBranchFromCond(X86::CondCode CC) {
2232   switch (CC) {
2233   default: llvm_unreachable("Illegal condition code!");
2234   case X86::COND_E:  return X86::JE_1;
2235   case X86::COND_NE: return X86::JNE_1;
2236   case X86::COND_L:  return X86::JL_1;
2237   case X86::COND_LE: return X86::JLE_1;
2238   case X86::COND_G:  return X86::JG_1;
2239   case X86::COND_GE: return X86::JGE_1;
2240   case X86::COND_B:  return X86::JB_1;
2241   case X86::COND_BE: return X86::JBE_1;
2242   case X86::COND_A:  return X86::JA_1;
2243   case X86::COND_AE: return X86::JAE_1;
2244   case X86::COND_S:  return X86::JS_1;
2245   case X86::COND_NS: return X86::JNS_1;
2246   case X86::COND_P:  return X86::JP_1;
2247   case X86::COND_NP: return X86::JNP_1;
2248   case X86::COND_O:  return X86::JO_1;
2249   case X86::COND_NO: return X86::JNO_1;
2250   }
2251 }
2252 
2253 /// Return the inverse of the specified condition,
2254 /// e.g. turning COND_E to COND_NE.
2255 X86::CondCode X86::GetOppositeBranchCondition(X86::CondCode CC) {
2256   switch (CC) {
2257   default: llvm_unreachable("Illegal condition code!");
2258   case X86::COND_E:  return X86::COND_NE;
2259   case X86::COND_NE: return X86::COND_E;
2260   case X86::COND_L:  return X86::COND_GE;
2261   case X86::COND_LE: return X86::COND_G;
2262   case X86::COND_G:  return X86::COND_LE;
2263   case X86::COND_GE: return X86::COND_L;
2264   case X86::COND_B:  return X86::COND_AE;
2265   case X86::COND_BE: return X86::COND_A;
2266   case X86::COND_A:  return X86::COND_BE;
2267   case X86::COND_AE: return X86::COND_B;
2268   case X86::COND_S:  return X86::COND_NS;
2269   case X86::COND_NS: return X86::COND_S;
2270   case X86::COND_P:  return X86::COND_NP;
2271   case X86::COND_NP: return X86::COND_P;
2272   case X86::COND_O:  return X86::COND_NO;
2273   case X86::COND_NO: return X86::COND_O;
2274   case X86::COND_NE_OR_P:  return X86::COND_E_AND_NP;
2275   case X86::COND_E_AND_NP: return X86::COND_NE_OR_P;
2276   }
2277 }
2278 
2279 /// Assuming the flags are set by MI(a,b), return the condition code if we
2280 /// modify the instructions such that flags are set by MI(b,a).
2281 static X86::CondCode getSwappedCondition(X86::CondCode CC) {
2282   switch (CC) {
2283   default: return X86::COND_INVALID;
2284   case X86::COND_E:  return X86::COND_E;
2285   case X86::COND_NE: return X86::COND_NE;
2286   case X86::COND_L:  return X86::COND_G;
2287   case X86::COND_LE: return X86::COND_GE;
2288   case X86::COND_G:  return X86::COND_L;
2289   case X86::COND_GE: return X86::COND_LE;
2290   case X86::COND_B:  return X86::COND_A;
2291   case X86::COND_BE: return X86::COND_AE;
2292   case X86::COND_A:  return X86::COND_B;
2293   case X86::COND_AE: return X86::COND_BE;
2294   }
2295 }
2296 
2297 std::pair<X86::CondCode, bool>
2298 X86::getX86ConditionCode(CmpInst::Predicate Predicate) {
2299   X86::CondCode CC = X86::COND_INVALID;
2300   bool NeedSwap = false;
2301   switch (Predicate) {
2302   default: break;
2303   // Floating-point Predicates
2304   case CmpInst::FCMP_UEQ: CC = X86::COND_E;       break;
2305   case CmpInst::FCMP_OLT: NeedSwap = true;        LLVM_FALLTHROUGH;
2306   case CmpInst::FCMP_OGT: CC = X86::COND_A;       break;
2307   case CmpInst::FCMP_OLE: NeedSwap = true;        LLVM_FALLTHROUGH;
2308   case CmpInst::FCMP_OGE: CC = X86::COND_AE;      break;
2309   case CmpInst::FCMP_UGT: NeedSwap = true;        LLVM_FALLTHROUGH;
2310   case CmpInst::FCMP_ULT: CC = X86::COND_B;       break;
2311   case CmpInst::FCMP_UGE: NeedSwap = true;        LLVM_FALLTHROUGH;
2312   case CmpInst::FCMP_ULE: CC = X86::COND_BE;      break;
2313   case CmpInst::FCMP_ONE: CC = X86::COND_NE;      break;
2314   case CmpInst::FCMP_UNO: CC = X86::COND_P;       break;
2315   case CmpInst::FCMP_ORD: CC = X86::COND_NP;      break;
2316   case CmpInst::FCMP_OEQ:                         LLVM_FALLTHROUGH;
2317   case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
2318 
2319   // Integer Predicates
2320   case CmpInst::ICMP_EQ:  CC = X86::COND_E;       break;
2321   case CmpInst::ICMP_NE:  CC = X86::COND_NE;      break;
2322   case CmpInst::ICMP_UGT: CC = X86::COND_A;       break;
2323   case CmpInst::ICMP_UGE: CC = X86::COND_AE;      break;
2324   case CmpInst::ICMP_ULT: CC = X86::COND_B;       break;
2325   case CmpInst::ICMP_ULE: CC = X86::COND_BE;      break;
2326   case CmpInst::ICMP_SGT: CC = X86::COND_G;       break;
2327   case CmpInst::ICMP_SGE: CC = X86::COND_GE;      break;
2328   case CmpInst::ICMP_SLT: CC = X86::COND_L;       break;
2329   case CmpInst::ICMP_SLE: CC = X86::COND_LE;      break;
2330   }
2331 
2332   return std::make_pair(CC, NeedSwap);
2333 }
2334 
2335 /// Return a set opcode for the given condition and
2336 /// whether it has memory operand.
2337 unsigned X86::getSETFromCond(CondCode CC, bool HasMemoryOperand) {
2338   static const uint16_t Opc[16][2] = {
2339     { X86::SETAr,  X86::SETAm  },
2340     { X86::SETAEr, X86::SETAEm },
2341     { X86::SETBr,  X86::SETBm  },
2342     { X86::SETBEr, X86::SETBEm },
2343     { X86::SETEr,  X86::SETEm  },
2344     { X86::SETGr,  X86::SETGm  },
2345     { X86::SETGEr, X86::SETGEm },
2346     { X86::SETLr,  X86::SETLm  },
2347     { X86::SETLEr, X86::SETLEm },
2348     { X86::SETNEr, X86::SETNEm },
2349     { X86::SETNOr, X86::SETNOm },
2350     { X86::SETNPr, X86::SETNPm },
2351     { X86::SETNSr, X86::SETNSm },
2352     { X86::SETOr,  X86::SETOm  },
2353     { X86::SETPr,  X86::SETPm  },
2354     { X86::SETSr,  X86::SETSm  }
2355   };
2356 
2357   assert(CC <= LAST_VALID_COND && "Can only handle standard cond codes");
2358   return Opc[CC][HasMemoryOperand ? 1 : 0];
2359 }
2360 
2361 /// Return a cmov opcode for the given condition,
2362 /// register size in bytes, and operand type.
2363 unsigned X86::getCMovFromCond(CondCode CC, unsigned RegBytes,
2364                               bool HasMemoryOperand) {
2365   static const uint16_t Opc[32][3] = {
2366     { X86::CMOVA16rr,  X86::CMOVA32rr,  X86::CMOVA64rr  },
2367     { X86::CMOVAE16rr, X86::CMOVAE32rr, X86::CMOVAE64rr },
2368     { X86::CMOVB16rr,  X86::CMOVB32rr,  X86::CMOVB64rr  },
2369     { X86::CMOVBE16rr, X86::CMOVBE32rr, X86::CMOVBE64rr },
2370     { X86::CMOVE16rr,  X86::CMOVE32rr,  X86::CMOVE64rr  },
2371     { X86::CMOVG16rr,  X86::CMOVG32rr,  X86::CMOVG64rr  },
2372     { X86::CMOVGE16rr, X86::CMOVGE32rr, X86::CMOVGE64rr },
2373     { X86::CMOVL16rr,  X86::CMOVL32rr,  X86::CMOVL64rr  },
2374     { X86::CMOVLE16rr, X86::CMOVLE32rr, X86::CMOVLE64rr },
2375     { X86::CMOVNE16rr, X86::CMOVNE32rr, X86::CMOVNE64rr },
2376     { X86::CMOVNO16rr, X86::CMOVNO32rr, X86::CMOVNO64rr },
2377     { X86::CMOVNP16rr, X86::CMOVNP32rr, X86::CMOVNP64rr },
2378     { X86::CMOVNS16rr, X86::CMOVNS32rr, X86::CMOVNS64rr },
2379     { X86::CMOVO16rr,  X86::CMOVO32rr,  X86::CMOVO64rr  },
2380     { X86::CMOVP16rr,  X86::CMOVP32rr,  X86::CMOVP64rr  },
2381     { X86::CMOVS16rr,  X86::CMOVS32rr,  X86::CMOVS64rr  },
2382     { X86::CMOVA16rm,  X86::CMOVA32rm,  X86::CMOVA64rm  },
2383     { X86::CMOVAE16rm, X86::CMOVAE32rm, X86::CMOVAE64rm },
2384     { X86::CMOVB16rm,  X86::CMOVB32rm,  X86::CMOVB64rm  },
2385     { X86::CMOVBE16rm, X86::CMOVBE32rm, X86::CMOVBE64rm },
2386     { X86::CMOVE16rm,  X86::CMOVE32rm,  X86::CMOVE64rm  },
2387     { X86::CMOVG16rm,  X86::CMOVG32rm,  X86::CMOVG64rm  },
2388     { X86::CMOVGE16rm, X86::CMOVGE32rm, X86::CMOVGE64rm },
2389     { X86::CMOVL16rm,  X86::CMOVL32rm,  X86::CMOVL64rm  },
2390     { X86::CMOVLE16rm, X86::CMOVLE32rm, X86::CMOVLE64rm },
2391     { X86::CMOVNE16rm, X86::CMOVNE32rm, X86::CMOVNE64rm },
2392     { X86::CMOVNO16rm, X86::CMOVNO32rm, X86::CMOVNO64rm },
2393     { X86::CMOVNP16rm, X86::CMOVNP32rm, X86::CMOVNP64rm },
2394     { X86::CMOVNS16rm, X86::CMOVNS32rm, X86::CMOVNS64rm },
2395     { X86::CMOVO16rm,  X86::CMOVO32rm,  X86::CMOVO64rm  },
2396     { X86::CMOVP16rm,  X86::CMOVP32rm,  X86::CMOVP64rm  },
2397     { X86::CMOVS16rm,  X86::CMOVS32rm,  X86::CMOVS64rm  }
2398   };
2399 
2400   assert(CC < 16 && "Can only handle standard cond codes");
2401   unsigned Idx = HasMemoryOperand ? 16+CC : CC;
2402   switch(RegBytes) {
2403   default: llvm_unreachable("Illegal register size!");
2404   case 2: return Opc[Idx][0];
2405   case 4: return Opc[Idx][1];
2406   case 8: return Opc[Idx][2];
2407   }
2408 }
2409 
2410 /// Get the VPCMP immediate for the given condition.
2411 unsigned X86::getVPCMPImmForCond(ISD::CondCode CC) {
2412   switch (CC) {
2413   default: llvm_unreachable("Unexpected SETCC condition");
2414   case ISD::SETNE:  return 4;
2415   case ISD::SETEQ:  return 0;
2416   case ISD::SETULT:
2417   case ISD::SETLT: return 1;
2418   case ISD::SETUGT:
2419   case ISD::SETGT: return 6;
2420   case ISD::SETUGE:
2421   case ISD::SETGE: return 5;
2422   case ISD::SETULE:
2423   case ISD::SETLE: return 2;
2424   }
2425 }
2426 
2427 /// Get the VPCMP immediate if the opcodes are swapped.
2428 unsigned X86::getSwappedVPCMPImm(unsigned Imm) {
2429   switch (Imm) {
2430   default: llvm_unreachable("Unreachable!");
2431   case 0x01: Imm = 0x06; break; // LT  -> NLE
2432   case 0x02: Imm = 0x05; break; // LE  -> NLT
2433   case 0x05: Imm = 0x02; break; // NLT -> LE
2434   case 0x06: Imm = 0x01; break; // NLE -> LT
2435   case 0x00: // EQ
2436   case 0x03: // FALSE
2437   case 0x04: // NE
2438   case 0x07: // TRUE
2439     break;
2440   }
2441 
2442   return Imm;
2443 }
2444 
2445 /// Get the VPCOM immediate if the opcodes are swapped.
2446 unsigned X86::getSwappedVPCOMImm(unsigned Imm) {
2447   switch (Imm) {
2448   default: llvm_unreachable("Unreachable!");
2449   case 0x00: Imm = 0x02; break; // LT -> GT
2450   case 0x01: Imm = 0x03; break; // LE -> GE
2451   case 0x02: Imm = 0x00; break; // GT -> LT
2452   case 0x03: Imm = 0x01; break; // GE -> LE
2453   case 0x04: // EQ
2454   case 0x05: // NE
2455   case 0x06: // FALSE
2456   case 0x07: // TRUE
2457     break;
2458   }
2459 
2460   return Imm;
2461 }
2462 
2463 bool X86InstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
2464   if (!MI.isTerminator()) return false;
2465 
2466   // Conditional branch is a special case.
2467   if (MI.isBranch() && !MI.isBarrier())
2468     return true;
2469   if (!MI.isPredicable())
2470     return true;
2471   return !isPredicated(MI);
2472 }
2473 
2474 bool X86InstrInfo::isUnconditionalTailCall(const MachineInstr &MI) const {
2475   switch (MI.getOpcode()) {
2476   case X86::TCRETURNdi:
2477   case X86::TCRETURNri:
2478   case X86::TCRETURNmi:
2479   case X86::TCRETURNdi64:
2480   case X86::TCRETURNri64:
2481   case X86::TCRETURNmi64:
2482     return true;
2483   default:
2484     return false;
2485   }
2486 }
2487 
2488 bool X86InstrInfo::canMakeTailCallConditional(
2489     SmallVectorImpl<MachineOperand> &BranchCond,
2490     const MachineInstr &TailCall) const {
2491   if (TailCall.getOpcode() != X86::TCRETURNdi &&
2492       TailCall.getOpcode() != X86::TCRETURNdi64) {
2493     // Only direct calls can be done with a conditional branch.
2494     return false;
2495   }
2496 
2497   const MachineFunction *MF = TailCall.getParent()->getParent();
2498   if (Subtarget.isTargetWin64() && MF->hasWinCFI()) {
2499     // Conditional tail calls confuse the Win64 unwinder.
2500     return false;
2501   }
2502 
2503   assert(BranchCond.size() == 1);
2504   if (BranchCond[0].getImm() > X86::LAST_VALID_COND) {
2505     // Can't make a conditional tail call with this condition.
2506     return false;
2507   }
2508 
2509   const X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
2510   if (X86FI->getTCReturnAddrDelta() != 0 ||
2511       TailCall.getOperand(1).getImm() != 0) {
2512     // A conditional tail call cannot do any stack adjustment.
2513     return false;
2514   }
2515 
2516   return true;
2517 }
2518 
2519 void X86InstrInfo::replaceBranchWithTailCall(
2520     MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &BranchCond,
2521     const MachineInstr &TailCall) const {
2522   assert(canMakeTailCallConditional(BranchCond, TailCall));
2523 
2524   MachineBasicBlock::iterator I = MBB.end();
2525   while (I != MBB.begin()) {
2526     --I;
2527     if (I->isDebugInstr())
2528       continue;
2529     if (!I->isBranch())
2530       assert(0 && "Can't find the branch to replace!");
2531 
2532     X86::CondCode CC = X86::getCondFromBranchOpc(I->getOpcode());
2533     assert(BranchCond.size() == 1);
2534     if (CC != BranchCond[0].getImm())
2535       continue;
2536 
2537     break;
2538   }
2539 
2540   unsigned Opc = TailCall.getOpcode() == X86::TCRETURNdi ? X86::TCRETURNdicc
2541                                                          : X86::TCRETURNdi64cc;
2542 
2543   auto MIB = BuildMI(MBB, I, MBB.findDebugLoc(I), get(Opc));
2544   MIB->addOperand(TailCall.getOperand(0)); // Destination.
2545   MIB.addImm(0); // Stack offset (not used).
2546   MIB->addOperand(BranchCond[0]); // Condition.
2547   MIB.copyImplicitOps(TailCall); // Regmask and (imp-used) parameters.
2548 
2549   // Add implicit uses and defs of all live regs potentially clobbered by the
2550   // call. This way they still appear live across the call.
2551   LivePhysRegs LiveRegs(getRegisterInfo());
2552   LiveRegs.addLiveOuts(MBB);
2553   SmallVector<std::pair<MCPhysReg, const MachineOperand *>, 8> Clobbers;
2554   LiveRegs.stepForward(*MIB, Clobbers);
2555   for (const auto &C : Clobbers) {
2556     MIB.addReg(C.first, RegState::Implicit);
2557     MIB.addReg(C.first, RegState::Implicit | RegState::Define);
2558   }
2559 
2560   I->eraseFromParent();
2561 }
2562 
2563 // Given a MBB and its TBB, find the FBB which was a fallthrough MBB (it may
2564 // not be a fallthrough MBB now due to layout changes). Return nullptr if the
2565 // fallthrough MBB cannot be identified.
2566 static MachineBasicBlock *getFallThroughMBB(MachineBasicBlock *MBB,
2567                                             MachineBasicBlock *TBB) {
2568   // Look for non-EHPad successors other than TBB. If we find exactly one, it
2569   // is the fallthrough MBB. If we find zero, then TBB is both the target MBB
2570   // and fallthrough MBB. If we find more than one, we cannot identify the
2571   // fallthrough MBB and should return nullptr.
2572   MachineBasicBlock *FallthroughBB = nullptr;
2573   for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) {
2574     if ((*SI)->isEHPad() || (*SI == TBB && FallthroughBB))
2575       continue;
2576     // Return a nullptr if we found more than one fallthrough successor.
2577     if (FallthroughBB && FallthroughBB != TBB)
2578       return nullptr;
2579     FallthroughBB = *SI;
2580   }
2581   return FallthroughBB;
2582 }
2583 
2584 bool X86InstrInfo::AnalyzeBranchImpl(
2585     MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB,
2586     SmallVectorImpl<MachineOperand> &Cond,
2587     SmallVectorImpl<MachineInstr *> &CondBranches, bool AllowModify) const {
2588 
2589   // Start from the bottom of the block and work up, examining the
2590   // terminator instructions.
2591   MachineBasicBlock::iterator I = MBB.end();
2592   MachineBasicBlock::iterator UnCondBrIter = MBB.end();
2593   while (I != MBB.begin()) {
2594     --I;
2595     if (I->isDebugInstr())
2596       continue;
2597 
2598     // Working from the bottom, when we see a non-terminator instruction, we're
2599     // done.
2600     if (!isUnpredicatedTerminator(*I))
2601       break;
2602 
2603     // A terminator that isn't a branch can't easily be handled by this
2604     // analysis.
2605     if (!I->isBranch())
2606       return true;
2607 
2608     // Handle unconditional branches.
2609     if (I->getOpcode() == X86::JMP_1) {
2610       UnCondBrIter = I;
2611 
2612       if (!AllowModify) {
2613         TBB = I->getOperand(0).getMBB();
2614         continue;
2615       }
2616 
2617       // If the block has any instructions after a JMP, delete them.
2618       while (std::next(I) != MBB.end())
2619         std::next(I)->eraseFromParent();
2620 
2621       Cond.clear();
2622       FBB = nullptr;
2623 
2624       // Delete the JMP if it's equivalent to a fall-through.
2625       if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
2626         TBB = nullptr;
2627         I->eraseFromParent();
2628         I = MBB.end();
2629         UnCondBrIter = MBB.end();
2630         continue;
2631       }
2632 
2633       // TBB is used to indicate the unconditional destination.
2634       TBB = I->getOperand(0).getMBB();
2635       continue;
2636     }
2637 
2638     // Handle conditional branches.
2639     X86::CondCode BranchCode = X86::getCondFromBranchOpc(I->getOpcode());
2640     if (BranchCode == X86::COND_INVALID)
2641       return true;  // Can't handle indirect branch.
2642 
2643     // In practice we should never have an undef eflags operand, if we do
2644     // abort here as we are not prepared to preserve the flag.
2645     if (I->getOperand(1).isUndef())
2646       return true;
2647 
2648     // Working from the bottom, handle the first conditional branch.
2649     if (Cond.empty()) {
2650       MachineBasicBlock *TargetBB = I->getOperand(0).getMBB();
2651       if (AllowModify && UnCondBrIter != MBB.end() &&
2652           MBB.isLayoutSuccessor(TargetBB)) {
2653         // If we can modify the code and it ends in something like:
2654         //
2655         //     jCC L1
2656         //     jmp L2
2657         //   L1:
2658         //     ...
2659         //   L2:
2660         //
2661         // Then we can change this to:
2662         //
2663         //     jnCC L2
2664         //   L1:
2665         //     ...
2666         //   L2:
2667         //
2668         // Which is a bit more efficient.
2669         // We conditionally jump to the fall-through block.
2670         BranchCode = GetOppositeBranchCondition(BranchCode);
2671         unsigned JNCC = GetCondBranchFromCond(BranchCode);
2672         MachineBasicBlock::iterator OldInst = I;
2673 
2674         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(JNCC))
2675           .addMBB(UnCondBrIter->getOperand(0).getMBB());
2676         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(X86::JMP_1))
2677           .addMBB(TargetBB);
2678 
2679         OldInst->eraseFromParent();
2680         UnCondBrIter->eraseFromParent();
2681 
2682         // Restart the analysis.
2683         UnCondBrIter = MBB.end();
2684         I = MBB.end();
2685         continue;
2686       }
2687 
2688       FBB = TBB;
2689       TBB = I->getOperand(0).getMBB();
2690       Cond.push_back(MachineOperand::CreateImm(BranchCode));
2691       CondBranches.push_back(&*I);
2692       continue;
2693     }
2694 
2695     // Handle subsequent conditional branches. Only handle the case where all
2696     // conditional branches branch to the same destination and their condition
2697     // opcodes fit one of the special multi-branch idioms.
2698     assert(Cond.size() == 1);
2699     assert(TBB);
2700 
2701     // If the conditions are the same, we can leave them alone.
2702     X86::CondCode OldBranchCode = (X86::CondCode)Cond[0].getImm();
2703     auto NewTBB = I->getOperand(0).getMBB();
2704     if (OldBranchCode == BranchCode && TBB == NewTBB)
2705       continue;
2706 
2707     // If they differ, see if they fit one of the known patterns. Theoretically,
2708     // we could handle more patterns here, but we shouldn't expect to see them
2709     // if instruction selection has done a reasonable job.
2710     if (TBB == NewTBB &&
2711                ((OldBranchCode == X86::COND_P && BranchCode == X86::COND_NE) ||
2712                 (OldBranchCode == X86::COND_NE && BranchCode == X86::COND_P))) {
2713       BranchCode = X86::COND_NE_OR_P;
2714     } else if ((OldBranchCode == X86::COND_NP && BranchCode == X86::COND_NE) ||
2715                (OldBranchCode == X86::COND_E && BranchCode == X86::COND_P)) {
2716       if (NewTBB != (FBB ? FBB : getFallThroughMBB(&MBB, TBB)))
2717         return true;
2718 
2719       // X86::COND_E_AND_NP usually has two different branch destinations.
2720       //
2721       // JP B1
2722       // JE B2
2723       // JMP B1
2724       // B1:
2725       // B2:
2726       //
2727       // Here this condition branches to B2 only if NP && E. It has another
2728       // equivalent form:
2729       //
2730       // JNE B1
2731       // JNP B2
2732       // JMP B1
2733       // B1:
2734       // B2:
2735       //
2736       // Similarly it branches to B2 only if E && NP. That is why this condition
2737       // is named with COND_E_AND_NP.
2738       BranchCode = X86::COND_E_AND_NP;
2739     } else
2740       return true;
2741 
2742     // Update the MachineOperand.
2743     Cond[0].setImm(BranchCode);
2744     CondBranches.push_back(&*I);
2745   }
2746 
2747   return false;
2748 }
2749 
2750 bool X86InstrInfo::analyzeBranch(MachineBasicBlock &MBB,
2751                                  MachineBasicBlock *&TBB,
2752                                  MachineBasicBlock *&FBB,
2753                                  SmallVectorImpl<MachineOperand> &Cond,
2754                                  bool AllowModify) const {
2755   SmallVector<MachineInstr *, 4> CondBranches;
2756   return AnalyzeBranchImpl(MBB, TBB, FBB, Cond, CondBranches, AllowModify);
2757 }
2758 
2759 bool X86InstrInfo::analyzeBranchPredicate(MachineBasicBlock &MBB,
2760                                           MachineBranchPredicate &MBP,
2761                                           bool AllowModify) const {
2762   using namespace std::placeholders;
2763 
2764   SmallVector<MachineOperand, 4> Cond;
2765   SmallVector<MachineInstr *, 4> CondBranches;
2766   if (AnalyzeBranchImpl(MBB, MBP.TrueDest, MBP.FalseDest, Cond, CondBranches,
2767                         AllowModify))
2768     return true;
2769 
2770   if (Cond.size() != 1)
2771     return true;
2772 
2773   assert(MBP.TrueDest && "expected!");
2774 
2775   if (!MBP.FalseDest)
2776     MBP.FalseDest = MBB.getNextNode();
2777 
2778   const TargetRegisterInfo *TRI = &getRegisterInfo();
2779 
2780   MachineInstr *ConditionDef = nullptr;
2781   bool SingleUseCondition = true;
2782 
2783   for (auto I = std::next(MBB.rbegin()), E = MBB.rend(); I != E; ++I) {
2784     if (I->modifiesRegister(X86::EFLAGS, TRI)) {
2785       ConditionDef = &*I;
2786       break;
2787     }
2788 
2789     if (I->readsRegister(X86::EFLAGS, TRI))
2790       SingleUseCondition = false;
2791   }
2792 
2793   if (!ConditionDef)
2794     return true;
2795 
2796   if (SingleUseCondition) {
2797     for (auto *Succ : MBB.successors())
2798       if (Succ->isLiveIn(X86::EFLAGS))
2799         SingleUseCondition = false;
2800   }
2801 
2802   MBP.ConditionDef = ConditionDef;
2803   MBP.SingleUseCondition = SingleUseCondition;
2804 
2805   // Currently we only recognize the simple pattern:
2806   //
2807   //   test %reg, %reg
2808   //   je %label
2809   //
2810   const unsigned TestOpcode =
2811       Subtarget.is64Bit() ? X86::TEST64rr : X86::TEST32rr;
2812 
2813   if (ConditionDef->getOpcode() == TestOpcode &&
2814       ConditionDef->getNumOperands() == 3 &&
2815       ConditionDef->getOperand(0).isIdenticalTo(ConditionDef->getOperand(1)) &&
2816       (Cond[0].getImm() == X86::COND_NE || Cond[0].getImm() == X86::COND_E)) {
2817     MBP.LHS = ConditionDef->getOperand(0);
2818     MBP.RHS = MachineOperand::CreateImm(0);
2819     MBP.Predicate = Cond[0].getImm() == X86::COND_NE
2820                         ? MachineBranchPredicate::PRED_NE
2821                         : MachineBranchPredicate::PRED_EQ;
2822     return false;
2823   }
2824 
2825   return true;
2826 }
2827 
2828 unsigned X86InstrInfo::removeBranch(MachineBasicBlock &MBB,
2829                                     int *BytesRemoved) const {
2830   assert(!BytesRemoved && "code size not handled");
2831 
2832   MachineBasicBlock::iterator I = MBB.end();
2833   unsigned Count = 0;
2834 
2835   while (I != MBB.begin()) {
2836     --I;
2837     if (I->isDebugInstr())
2838       continue;
2839     if (I->getOpcode() != X86::JMP_1 &&
2840         X86::getCondFromBranchOpc(I->getOpcode()) == X86::COND_INVALID)
2841       break;
2842     // Remove the branch.
2843     I->eraseFromParent();
2844     I = MBB.end();
2845     ++Count;
2846   }
2847 
2848   return Count;
2849 }
2850 
2851 unsigned X86InstrInfo::insertBranch(MachineBasicBlock &MBB,
2852                                     MachineBasicBlock *TBB,
2853                                     MachineBasicBlock *FBB,
2854                                     ArrayRef<MachineOperand> Cond,
2855                                     const DebugLoc &DL,
2856                                     int *BytesAdded) const {
2857   // Shouldn't be a fall through.
2858   assert(TBB && "insertBranch must not be told to insert a fallthrough");
2859   assert((Cond.size() == 1 || Cond.size() == 0) &&
2860          "X86 branch conditions have one component!");
2861   assert(!BytesAdded && "code size not handled");
2862 
2863   if (Cond.empty()) {
2864     // Unconditional branch?
2865     assert(!FBB && "Unconditional branch with multiple successors!");
2866     BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(TBB);
2867     return 1;
2868   }
2869 
2870   // If FBB is null, it is implied to be a fall-through block.
2871   bool FallThru = FBB == nullptr;
2872 
2873   // Conditional branch.
2874   unsigned Count = 0;
2875   X86::CondCode CC = (X86::CondCode)Cond[0].getImm();
2876   switch (CC) {
2877   case X86::COND_NE_OR_P:
2878     // Synthesize NE_OR_P with two branches.
2879     BuildMI(&MBB, DL, get(X86::JNE_1)).addMBB(TBB);
2880     ++Count;
2881     BuildMI(&MBB, DL, get(X86::JP_1)).addMBB(TBB);
2882     ++Count;
2883     break;
2884   case X86::COND_E_AND_NP:
2885     // Use the next block of MBB as FBB if it is null.
2886     if (FBB == nullptr) {
2887       FBB = getFallThroughMBB(&MBB, TBB);
2888       assert(FBB && "MBB cannot be the last block in function when the false "
2889                     "body is a fall-through.");
2890     }
2891     // Synthesize COND_E_AND_NP with two branches.
2892     BuildMI(&MBB, DL, get(X86::JNE_1)).addMBB(FBB);
2893     ++Count;
2894     BuildMI(&MBB, DL, get(X86::JNP_1)).addMBB(TBB);
2895     ++Count;
2896     break;
2897   default: {
2898     unsigned Opc = GetCondBranchFromCond(CC);
2899     BuildMI(&MBB, DL, get(Opc)).addMBB(TBB);
2900     ++Count;
2901   }
2902   }
2903   if (!FallThru) {
2904     // Two-way Conditional branch. Insert the second branch.
2905     BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(FBB);
2906     ++Count;
2907   }
2908   return Count;
2909 }
2910 
2911 bool X86InstrInfo::
2912 canInsertSelect(const MachineBasicBlock &MBB,
2913                 ArrayRef<MachineOperand> Cond,
2914                 unsigned TrueReg, unsigned FalseReg,
2915                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
2916   // Not all subtargets have cmov instructions.
2917   if (!Subtarget.hasCMov())
2918     return false;
2919   if (Cond.size() != 1)
2920     return false;
2921   // We cannot do the composite conditions, at least not in SSA form.
2922   if ((X86::CondCode)Cond[0].getImm() > X86::COND_S)
2923     return false;
2924 
2925   // Check register classes.
2926   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2927   const TargetRegisterClass *RC =
2928     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
2929   if (!RC)
2930     return false;
2931 
2932   // We have cmov instructions for 16, 32, and 64 bit general purpose registers.
2933   if (X86::GR16RegClass.hasSubClassEq(RC) ||
2934       X86::GR32RegClass.hasSubClassEq(RC) ||
2935       X86::GR64RegClass.hasSubClassEq(RC)) {
2936     // This latency applies to Pentium M, Merom, Wolfdale, Nehalem, and Sandy
2937     // Bridge. Probably Ivy Bridge as well.
2938     CondCycles = 2;
2939     TrueCycles = 2;
2940     FalseCycles = 2;
2941     return true;
2942   }
2943 
2944   // Can't do vectors.
2945   return false;
2946 }
2947 
2948 void X86InstrInfo::insertSelect(MachineBasicBlock &MBB,
2949                                 MachineBasicBlock::iterator I,
2950                                 const DebugLoc &DL, unsigned DstReg,
2951                                 ArrayRef<MachineOperand> Cond, unsigned TrueReg,
2952                                 unsigned FalseReg) const {
2953   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2954   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
2955   const TargetRegisterClass &RC = *MRI.getRegClass(DstReg);
2956   assert(Cond.size() == 1 && "Invalid Cond array");
2957   unsigned Opc = getCMovFromCond((X86::CondCode)Cond[0].getImm(),
2958                                  TRI.getRegSizeInBits(RC) / 8,
2959                                  false /*HasMemoryOperand*/);
2960   BuildMI(MBB, I, DL, get(Opc), DstReg).addReg(FalseReg).addReg(TrueReg);
2961 }
2962 
2963 /// Test if the given register is a physical h register.
2964 static bool isHReg(unsigned Reg) {
2965   return X86::GR8_ABCD_HRegClass.contains(Reg);
2966 }
2967 
2968 // Try and copy between VR128/VR64 and GR64 registers.
2969 static unsigned CopyToFromAsymmetricReg(unsigned DestReg, unsigned SrcReg,
2970                                         const X86Subtarget &Subtarget) {
2971   bool HasAVX = Subtarget.hasAVX();
2972   bool HasAVX512 = Subtarget.hasAVX512();
2973 
2974   // SrcReg(MaskReg) -> DestReg(GR64)
2975   // SrcReg(MaskReg) -> DestReg(GR32)
2976 
2977   // All KMASK RegClasses hold the same k registers, can be tested against anyone.
2978   if (X86::VK16RegClass.contains(SrcReg)) {
2979     if (X86::GR64RegClass.contains(DestReg)) {
2980       assert(Subtarget.hasBWI());
2981       return X86::KMOVQrk;
2982     }
2983     if (X86::GR32RegClass.contains(DestReg))
2984       return Subtarget.hasBWI() ? X86::KMOVDrk : X86::KMOVWrk;
2985   }
2986 
2987   // SrcReg(GR64) -> DestReg(MaskReg)
2988   // SrcReg(GR32) -> DestReg(MaskReg)
2989 
2990   // All KMASK RegClasses hold the same k registers, can be tested against anyone.
2991   if (X86::VK16RegClass.contains(DestReg)) {
2992     if (X86::GR64RegClass.contains(SrcReg)) {
2993       assert(Subtarget.hasBWI());
2994       return X86::KMOVQkr;
2995     }
2996     if (X86::GR32RegClass.contains(SrcReg))
2997       return Subtarget.hasBWI() ? X86::KMOVDkr : X86::KMOVWkr;
2998   }
2999 
3000 
3001   // SrcReg(VR128) -> DestReg(GR64)
3002   // SrcReg(VR64)  -> DestReg(GR64)
3003   // SrcReg(GR64)  -> DestReg(VR128)
3004   // SrcReg(GR64)  -> DestReg(VR64)
3005 
3006   if (X86::GR64RegClass.contains(DestReg)) {
3007     if (X86::VR128XRegClass.contains(SrcReg))
3008       // Copy from a VR128 register to a GR64 register.
3009       return HasAVX512 ? X86::VMOVPQIto64Zrr :
3010              HasAVX    ? X86::VMOVPQIto64rr  :
3011                          X86::MOVPQIto64rr;
3012     if (X86::VR64RegClass.contains(SrcReg))
3013       // Copy from a VR64 register to a GR64 register.
3014       return X86::MMX_MOVD64from64rr;
3015   } else if (X86::GR64RegClass.contains(SrcReg)) {
3016     // Copy from a GR64 register to a VR128 register.
3017     if (X86::VR128XRegClass.contains(DestReg))
3018       return HasAVX512 ? X86::VMOV64toPQIZrr :
3019              HasAVX    ? X86::VMOV64toPQIrr  :
3020                          X86::MOV64toPQIrr;
3021     // Copy from a GR64 register to a VR64 register.
3022     if (X86::VR64RegClass.contains(DestReg))
3023       return X86::MMX_MOVD64to64rr;
3024   }
3025 
3026   // SrcReg(FR32) -> DestReg(GR32)
3027   // SrcReg(GR32) -> DestReg(FR32)
3028 
3029   if (X86::GR32RegClass.contains(DestReg) &&
3030       X86::FR32XRegClass.contains(SrcReg))
3031     // Copy from a FR32 register to a GR32 register.
3032     return HasAVX512 ? X86::VMOVSS2DIZrr :
3033            HasAVX    ? X86::VMOVSS2DIrr  :
3034                        X86::MOVSS2DIrr;
3035 
3036   if (X86::FR32XRegClass.contains(DestReg) &&
3037       X86::GR32RegClass.contains(SrcReg))
3038     // Copy from a GR32 register to a FR32 register.
3039     return HasAVX512 ? X86::VMOVDI2SSZrr :
3040            HasAVX    ? X86::VMOVDI2SSrr  :
3041                        X86::MOVDI2SSrr;
3042   return 0;
3043 }
3044 
3045 void X86InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
3046                                MachineBasicBlock::iterator MI,
3047                                const DebugLoc &DL, unsigned DestReg,
3048                                unsigned SrcReg, bool KillSrc) const {
3049   // First deal with the normal symmetric copies.
3050   bool HasAVX = Subtarget.hasAVX();
3051   bool HasVLX = Subtarget.hasVLX();
3052   unsigned Opc = 0;
3053   if (X86::GR64RegClass.contains(DestReg, SrcReg))
3054     Opc = X86::MOV64rr;
3055   else if (X86::GR32RegClass.contains(DestReg, SrcReg))
3056     Opc = X86::MOV32rr;
3057   else if (X86::GR16RegClass.contains(DestReg, SrcReg))
3058     Opc = X86::MOV16rr;
3059   else if (X86::GR8RegClass.contains(DestReg, SrcReg)) {
3060     // Copying to or from a physical H register on x86-64 requires a NOREX
3061     // move.  Otherwise use a normal move.
3062     if ((isHReg(DestReg) || isHReg(SrcReg)) &&
3063         Subtarget.is64Bit()) {
3064       Opc = X86::MOV8rr_NOREX;
3065       // Both operands must be encodable without an REX prefix.
3066       assert(X86::GR8_NOREXRegClass.contains(SrcReg, DestReg) &&
3067              "8-bit H register can not be copied outside GR8_NOREX");
3068     } else
3069       Opc = X86::MOV8rr;
3070   }
3071   else if (X86::VR64RegClass.contains(DestReg, SrcReg))
3072     Opc = X86::MMX_MOVQ64rr;
3073   else if (X86::VR128XRegClass.contains(DestReg, SrcReg)) {
3074     if (HasVLX)
3075       Opc = X86::VMOVAPSZ128rr;
3076     else if (X86::VR128RegClass.contains(DestReg, SrcReg))
3077       Opc = HasAVX ? X86::VMOVAPSrr : X86::MOVAPSrr;
3078     else {
3079       // If this an extended register and we don't have VLX we need to use a
3080       // 512-bit move.
3081       Opc = X86::VMOVAPSZrr;
3082       const TargetRegisterInfo *TRI = &getRegisterInfo();
3083       DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_xmm,
3084                                          &X86::VR512RegClass);
3085       SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm,
3086                                         &X86::VR512RegClass);
3087     }
3088   } else if (X86::VR256XRegClass.contains(DestReg, SrcReg)) {
3089     if (HasVLX)
3090       Opc = X86::VMOVAPSZ256rr;
3091     else if (X86::VR256RegClass.contains(DestReg, SrcReg))
3092       Opc = X86::VMOVAPSYrr;
3093     else {
3094       // If this an extended register and we don't have VLX we need to use a
3095       // 512-bit move.
3096       Opc = X86::VMOVAPSZrr;
3097       const TargetRegisterInfo *TRI = &getRegisterInfo();
3098       DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_ymm,
3099                                          &X86::VR512RegClass);
3100       SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_ymm,
3101                                         &X86::VR512RegClass);
3102     }
3103   } else if (X86::VR512RegClass.contains(DestReg, SrcReg))
3104     Opc = X86::VMOVAPSZrr;
3105   // All KMASK RegClasses hold the same k registers, can be tested against anyone.
3106   else if (X86::VK16RegClass.contains(DestReg, SrcReg))
3107     Opc = Subtarget.hasBWI() ? X86::KMOVQkk : X86::KMOVWkk;
3108   if (!Opc)
3109     Opc = CopyToFromAsymmetricReg(DestReg, SrcReg, Subtarget);
3110 
3111   if (Opc) {
3112     BuildMI(MBB, MI, DL, get(Opc), DestReg)
3113       .addReg(SrcReg, getKillRegState(KillSrc));
3114     return;
3115   }
3116 
3117   if (SrcReg == X86::EFLAGS || DestReg == X86::EFLAGS) {
3118     // FIXME: We use a fatal error here because historically LLVM has tried
3119     // lower some of these physreg copies and we want to ensure we get
3120     // reasonable bug reports if someone encounters a case no other testing
3121     // found. This path should be removed after the LLVM 7 release.
3122     report_fatal_error("Unable to copy EFLAGS physical register!");
3123   }
3124 
3125   LLVM_DEBUG(dbgs() << "Cannot copy " << RI.getName(SrcReg) << " to "
3126                     << RI.getName(DestReg) << '\n');
3127   report_fatal_error("Cannot emit physreg copy instruction");
3128 }
3129 
3130 bool X86InstrInfo::isCopyInstrImpl(const MachineInstr &MI,
3131                                    const MachineOperand *&Src,
3132                                    const MachineOperand *&Dest) const {
3133   if (MI.isMoveReg()) {
3134     Dest = &MI.getOperand(0);
3135     Src = &MI.getOperand(1);
3136     return true;
3137   }
3138   return false;
3139 }
3140 
3141 static unsigned getLoadStoreRegOpcode(unsigned Reg,
3142                                       const TargetRegisterClass *RC,
3143                                       bool isStackAligned,
3144                                       const X86Subtarget &STI,
3145                                       bool load) {
3146   bool HasAVX = STI.hasAVX();
3147   bool HasAVX512 = STI.hasAVX512();
3148   bool HasVLX = STI.hasVLX();
3149 
3150   switch (STI.getRegisterInfo()->getSpillSize(*RC)) {
3151   default:
3152     llvm_unreachable("Unknown spill size");
3153   case 1:
3154     assert(X86::GR8RegClass.hasSubClassEq(RC) && "Unknown 1-byte regclass");
3155     if (STI.is64Bit())
3156       // Copying to or from a physical H register on x86-64 requires a NOREX
3157       // move.  Otherwise use a normal move.
3158       if (isHReg(Reg) || X86::GR8_ABCD_HRegClass.hasSubClassEq(RC))
3159         return load ? X86::MOV8rm_NOREX : X86::MOV8mr_NOREX;
3160     return load ? X86::MOV8rm : X86::MOV8mr;
3161   case 2:
3162     if (X86::VK16RegClass.hasSubClassEq(RC))
3163       return load ? X86::KMOVWkm : X86::KMOVWmk;
3164     assert(X86::GR16RegClass.hasSubClassEq(RC) && "Unknown 2-byte regclass");
3165     return load ? X86::MOV16rm : X86::MOV16mr;
3166   case 4:
3167     if (X86::GR32RegClass.hasSubClassEq(RC))
3168       return load ? X86::MOV32rm : X86::MOV32mr;
3169     if (X86::FR32XRegClass.hasSubClassEq(RC))
3170       return load ?
3171         (HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm) :
3172         (HasAVX512 ? X86::VMOVSSZmr : HasAVX ? X86::VMOVSSmr : X86::MOVSSmr);
3173     if (X86::RFP32RegClass.hasSubClassEq(RC))
3174       return load ? X86::LD_Fp32m : X86::ST_Fp32m;
3175     if (X86::VK32RegClass.hasSubClassEq(RC)) {
3176       assert(STI.hasBWI() && "KMOVD requires BWI");
3177       return load ? X86::KMOVDkm : X86::KMOVDmk;
3178     }
3179     llvm_unreachable("Unknown 4-byte regclass");
3180   case 8:
3181     if (X86::GR64RegClass.hasSubClassEq(RC))
3182       return load ? X86::MOV64rm : X86::MOV64mr;
3183     if (X86::FR64XRegClass.hasSubClassEq(RC))
3184       return load ?
3185         (HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm) :
3186         (HasAVX512 ? X86::VMOVSDZmr : HasAVX ? X86::VMOVSDmr : X86::MOVSDmr);
3187     if (X86::VR64RegClass.hasSubClassEq(RC))
3188       return load ? X86::MMX_MOVQ64rm : X86::MMX_MOVQ64mr;
3189     if (X86::RFP64RegClass.hasSubClassEq(RC))
3190       return load ? X86::LD_Fp64m : X86::ST_Fp64m;
3191     if (X86::VK64RegClass.hasSubClassEq(RC)) {
3192       assert(STI.hasBWI() && "KMOVQ requires BWI");
3193       return load ? X86::KMOVQkm : X86::KMOVQmk;
3194     }
3195     llvm_unreachable("Unknown 8-byte regclass");
3196   case 10:
3197     assert(X86::RFP80RegClass.hasSubClassEq(RC) && "Unknown 10-byte regclass");
3198     return load ? X86::LD_Fp80m : X86::ST_FpP80m;
3199   case 16: {
3200     if (X86::VR128XRegClass.hasSubClassEq(RC)) {
3201       // If stack is realigned we can use aligned stores.
3202       if (isStackAligned)
3203         return load ?
3204           (HasVLX    ? X86::VMOVAPSZ128rm :
3205            HasAVX512 ? X86::VMOVAPSZ128rm_NOVLX :
3206            HasAVX    ? X86::VMOVAPSrm :
3207                        X86::MOVAPSrm):
3208           (HasVLX    ? X86::VMOVAPSZ128mr :
3209            HasAVX512 ? X86::VMOVAPSZ128mr_NOVLX :
3210            HasAVX    ? X86::VMOVAPSmr :
3211                        X86::MOVAPSmr);
3212       else
3213         return load ?
3214           (HasVLX    ? X86::VMOVUPSZ128rm :
3215            HasAVX512 ? X86::VMOVUPSZ128rm_NOVLX :
3216            HasAVX    ? X86::VMOVUPSrm :
3217                        X86::MOVUPSrm):
3218           (HasVLX    ? X86::VMOVUPSZ128mr :
3219            HasAVX512 ? X86::VMOVUPSZ128mr_NOVLX :
3220            HasAVX    ? X86::VMOVUPSmr :
3221                        X86::MOVUPSmr);
3222     }
3223     if (X86::BNDRRegClass.hasSubClassEq(RC)) {
3224       if (STI.is64Bit())
3225         return load ? X86::BNDMOV64rm : X86::BNDMOV64mr;
3226       else
3227         return load ? X86::BNDMOV32rm : X86::BNDMOV32mr;
3228     }
3229     llvm_unreachable("Unknown 16-byte regclass");
3230   }
3231   case 32:
3232     assert(X86::VR256XRegClass.hasSubClassEq(RC) && "Unknown 32-byte regclass");
3233     // If stack is realigned we can use aligned stores.
3234     if (isStackAligned)
3235       return load ?
3236         (HasVLX    ? X86::VMOVAPSZ256rm :
3237          HasAVX512 ? X86::VMOVAPSZ256rm_NOVLX :
3238                      X86::VMOVAPSYrm) :
3239         (HasVLX    ? X86::VMOVAPSZ256mr :
3240          HasAVX512 ? X86::VMOVAPSZ256mr_NOVLX :
3241                      X86::VMOVAPSYmr);
3242     else
3243       return load ?
3244         (HasVLX    ? X86::VMOVUPSZ256rm :
3245          HasAVX512 ? X86::VMOVUPSZ256rm_NOVLX :
3246                      X86::VMOVUPSYrm) :
3247         (HasVLX    ? X86::VMOVUPSZ256mr :
3248          HasAVX512 ? X86::VMOVUPSZ256mr_NOVLX :
3249                      X86::VMOVUPSYmr);
3250   case 64:
3251     assert(X86::VR512RegClass.hasSubClassEq(RC) && "Unknown 64-byte regclass");
3252     assert(STI.hasAVX512() && "Using 512-bit register requires AVX512");
3253     if (isStackAligned)
3254       return load ? X86::VMOVAPSZrm : X86::VMOVAPSZmr;
3255     else
3256       return load ? X86::VMOVUPSZrm : X86::VMOVUPSZmr;
3257   }
3258 }
3259 
3260 bool X86InstrInfo::getMemOpBaseRegImmOfs(MachineInstr &MemOp, unsigned &BaseReg,
3261                                          int64_t &Offset,
3262                                          const TargetRegisterInfo *TRI) const {
3263   const MCInstrDesc &Desc = MemOp.getDesc();
3264   int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
3265   if (MemRefBegin < 0)
3266     return false;
3267 
3268   MemRefBegin += X86II::getOperandBias(Desc);
3269 
3270   MachineOperand &BaseMO = MemOp.getOperand(MemRefBegin + X86::AddrBaseReg);
3271   if (!BaseMO.isReg()) // Can be an MO_FrameIndex
3272     return false;
3273 
3274   BaseReg = BaseMO.getReg();
3275   if (MemOp.getOperand(MemRefBegin + X86::AddrScaleAmt).getImm() != 1)
3276     return false;
3277 
3278   if (MemOp.getOperand(MemRefBegin + X86::AddrIndexReg).getReg() !=
3279       X86::NoRegister)
3280     return false;
3281 
3282   const MachineOperand &DispMO = MemOp.getOperand(MemRefBegin + X86::AddrDisp);
3283 
3284   // Displacement can be symbolic
3285   if (!DispMO.isImm())
3286     return false;
3287 
3288   Offset = DispMO.getImm();
3289 
3290   return true;
3291 }
3292 
3293 static unsigned getStoreRegOpcode(unsigned SrcReg,
3294                                   const TargetRegisterClass *RC,
3295                                   bool isStackAligned,
3296                                   const X86Subtarget &STI) {
3297   return getLoadStoreRegOpcode(SrcReg, RC, isStackAligned, STI, false);
3298 }
3299 
3300 
3301 static unsigned getLoadRegOpcode(unsigned DestReg,
3302                                  const TargetRegisterClass *RC,
3303                                  bool isStackAligned,
3304                                  const X86Subtarget &STI) {
3305   return getLoadStoreRegOpcode(DestReg, RC, isStackAligned, STI, true);
3306 }
3307 
3308 void X86InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
3309                                        MachineBasicBlock::iterator MI,
3310                                        unsigned SrcReg, bool isKill, int FrameIdx,
3311                                        const TargetRegisterClass *RC,
3312                                        const TargetRegisterInfo *TRI) const {
3313   const MachineFunction &MF = *MBB.getParent();
3314   assert(MF.getFrameInfo().getObjectSize(FrameIdx) >= TRI->getSpillSize(*RC) &&
3315          "Stack slot too small for store");
3316   unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
3317   bool isAligned =
3318       (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
3319       RI.canRealignStack(MF);
3320   unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
3321   addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc)), FrameIdx)
3322     .addReg(SrcReg, getKillRegState(isKill));
3323 }
3324 
3325 void X86InstrInfo::storeRegToAddr(
3326     MachineFunction &MF, unsigned SrcReg, bool isKill,
3327     SmallVectorImpl<MachineOperand> &Addr, const TargetRegisterClass *RC,
3328     ArrayRef<MachineMemOperand *> MMOs,
3329     SmallVectorImpl<MachineInstr *> &NewMIs) const {
3330   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
3331   unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
3332   bool isAligned = !MMOs.empty() && MMOs.front()->getAlignment() >= Alignment;
3333   unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
3334   DebugLoc DL;
3335   MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc));
3336   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
3337     MIB.add(Addr[i]);
3338   MIB.addReg(SrcReg, getKillRegState(isKill));
3339   MIB.setMemRefs(MMOs);
3340   NewMIs.push_back(MIB);
3341 }
3342 
3343 
3344 void X86InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
3345                                         MachineBasicBlock::iterator MI,
3346                                         unsigned DestReg, int FrameIdx,
3347                                         const TargetRegisterClass *RC,
3348                                         const TargetRegisterInfo *TRI) const {
3349   const MachineFunction &MF = *MBB.getParent();
3350   unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
3351   bool isAligned =
3352       (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
3353       RI.canRealignStack(MF);
3354   unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
3355   addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc), DestReg), FrameIdx);
3356 }
3357 
3358 void X86InstrInfo::loadRegFromAddr(
3359     MachineFunction &MF, unsigned DestReg,
3360     SmallVectorImpl<MachineOperand> &Addr, const TargetRegisterClass *RC,
3361     ArrayRef<MachineMemOperand *> MMOs,
3362     SmallVectorImpl<MachineInstr *> &NewMIs) const {
3363   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
3364   unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
3365   bool isAligned = !MMOs.empty() && MMOs.front()->getAlignment() >= Alignment;
3366   unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
3367   DebugLoc DL;
3368   MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc), DestReg);
3369   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
3370     MIB.add(Addr[i]);
3371   MIB.setMemRefs(MMOs);
3372   NewMIs.push_back(MIB);
3373 }
3374 
3375 bool X86InstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
3376                                   unsigned &SrcReg2, int &CmpMask,
3377                                   int &CmpValue) const {
3378   switch (MI.getOpcode()) {
3379   default: break;
3380   case X86::CMP64ri32:
3381   case X86::CMP64ri8:
3382   case X86::CMP32ri:
3383   case X86::CMP32ri8:
3384   case X86::CMP16ri:
3385   case X86::CMP16ri8:
3386   case X86::CMP8ri:
3387     SrcReg = MI.getOperand(0).getReg();
3388     SrcReg2 = 0;
3389     if (MI.getOperand(1).isImm()) {
3390       CmpMask = ~0;
3391       CmpValue = MI.getOperand(1).getImm();
3392     } else {
3393       CmpMask = CmpValue = 0;
3394     }
3395     return true;
3396   // A SUB can be used to perform comparison.
3397   case X86::SUB64rm:
3398   case X86::SUB32rm:
3399   case X86::SUB16rm:
3400   case X86::SUB8rm:
3401     SrcReg = MI.getOperand(1).getReg();
3402     SrcReg2 = 0;
3403     CmpMask = 0;
3404     CmpValue = 0;
3405     return true;
3406   case X86::SUB64rr:
3407   case X86::SUB32rr:
3408   case X86::SUB16rr:
3409   case X86::SUB8rr:
3410     SrcReg = MI.getOperand(1).getReg();
3411     SrcReg2 = MI.getOperand(2).getReg();
3412     CmpMask = 0;
3413     CmpValue = 0;
3414     return true;
3415   case X86::SUB64ri32:
3416   case X86::SUB64ri8:
3417   case X86::SUB32ri:
3418   case X86::SUB32ri8:
3419   case X86::SUB16ri:
3420   case X86::SUB16ri8:
3421   case X86::SUB8ri:
3422     SrcReg = MI.getOperand(1).getReg();
3423     SrcReg2 = 0;
3424     if (MI.getOperand(2).isImm()) {
3425       CmpMask = ~0;
3426       CmpValue = MI.getOperand(2).getImm();
3427     } else {
3428       CmpMask = CmpValue = 0;
3429     }
3430     return true;
3431   case X86::CMP64rr:
3432   case X86::CMP32rr:
3433   case X86::CMP16rr:
3434   case X86::CMP8rr:
3435     SrcReg = MI.getOperand(0).getReg();
3436     SrcReg2 = MI.getOperand(1).getReg();
3437     CmpMask = 0;
3438     CmpValue = 0;
3439     return true;
3440   case X86::TEST8rr:
3441   case X86::TEST16rr:
3442   case X86::TEST32rr:
3443   case X86::TEST64rr:
3444     SrcReg = MI.getOperand(0).getReg();
3445     if (MI.getOperand(1).getReg() != SrcReg)
3446       return false;
3447     // Compare against zero.
3448     SrcReg2 = 0;
3449     CmpMask = ~0;
3450     CmpValue = 0;
3451     return true;
3452   }
3453   return false;
3454 }
3455 
3456 /// Check whether the first instruction, whose only
3457 /// purpose is to update flags, can be made redundant.
3458 /// CMPrr can be made redundant by SUBrr if the operands are the same.
3459 /// This function can be extended later on.
3460 /// SrcReg, SrcRegs: register operands for FlagI.
3461 /// ImmValue: immediate for FlagI if it takes an immediate.
3462 inline static bool isRedundantFlagInstr(MachineInstr &FlagI, unsigned SrcReg,
3463                                         unsigned SrcReg2, int ImmMask,
3464                                         int ImmValue, MachineInstr &OI) {
3465   if (((FlagI.getOpcode() == X86::CMP64rr && OI.getOpcode() == X86::SUB64rr) ||
3466        (FlagI.getOpcode() == X86::CMP32rr && OI.getOpcode() == X86::SUB32rr) ||
3467        (FlagI.getOpcode() == X86::CMP16rr && OI.getOpcode() == X86::SUB16rr) ||
3468        (FlagI.getOpcode() == X86::CMP8rr && OI.getOpcode() == X86::SUB8rr)) &&
3469       ((OI.getOperand(1).getReg() == SrcReg &&
3470         OI.getOperand(2).getReg() == SrcReg2) ||
3471        (OI.getOperand(1).getReg() == SrcReg2 &&
3472         OI.getOperand(2).getReg() == SrcReg)))
3473     return true;
3474 
3475   if (ImmMask != 0 &&
3476       ((FlagI.getOpcode() == X86::CMP64ri32 &&
3477         OI.getOpcode() == X86::SUB64ri32) ||
3478        (FlagI.getOpcode() == X86::CMP64ri8 &&
3479         OI.getOpcode() == X86::SUB64ri8) ||
3480        (FlagI.getOpcode() == X86::CMP32ri && OI.getOpcode() == X86::SUB32ri) ||
3481        (FlagI.getOpcode() == X86::CMP32ri8 &&
3482         OI.getOpcode() == X86::SUB32ri8) ||
3483        (FlagI.getOpcode() == X86::CMP16ri && OI.getOpcode() == X86::SUB16ri) ||
3484        (FlagI.getOpcode() == X86::CMP16ri8 &&
3485         OI.getOpcode() == X86::SUB16ri8) ||
3486        (FlagI.getOpcode() == X86::CMP8ri && OI.getOpcode() == X86::SUB8ri)) &&
3487       OI.getOperand(1).getReg() == SrcReg &&
3488       OI.getOperand(2).getImm() == ImmValue)
3489     return true;
3490   return false;
3491 }
3492 
3493 /// Check whether the definition can be converted
3494 /// to remove a comparison against zero.
3495 inline static bool isDefConvertible(MachineInstr &MI) {
3496   switch (MI.getOpcode()) {
3497   default: return false;
3498 
3499   // The shift instructions only modify ZF if their shift count is non-zero.
3500   // N.B.: The processor truncates the shift count depending on the encoding.
3501   case X86::SAR8ri:    case X86::SAR16ri:  case X86::SAR32ri:case X86::SAR64ri:
3502   case X86::SHR8ri:    case X86::SHR16ri:  case X86::SHR32ri:case X86::SHR64ri:
3503      return getTruncatedShiftCount(MI, 2) != 0;
3504 
3505   // Some left shift instructions can be turned into LEA instructions but only
3506   // if their flags aren't used. Avoid transforming such instructions.
3507   case X86::SHL8ri:    case X86::SHL16ri:  case X86::SHL32ri:case X86::SHL64ri:{
3508     unsigned ShAmt = getTruncatedShiftCount(MI, 2);
3509     if (isTruncatedShiftCountForLEA(ShAmt)) return false;
3510     return ShAmt != 0;
3511   }
3512 
3513   case X86::SHRD16rri8:case X86::SHRD32rri8:case X86::SHRD64rri8:
3514   case X86::SHLD16rri8:case X86::SHLD32rri8:case X86::SHLD64rri8:
3515      return getTruncatedShiftCount(MI, 3) != 0;
3516 
3517   case X86::SUB64ri32: case X86::SUB64ri8: case X86::SUB32ri:
3518   case X86::SUB32ri8:  case X86::SUB16ri:  case X86::SUB16ri8:
3519   case X86::SUB8ri:    case X86::SUB64rr:  case X86::SUB32rr:
3520   case X86::SUB16rr:   case X86::SUB8rr:   case X86::SUB64rm:
3521   case X86::SUB32rm:   case X86::SUB16rm:  case X86::SUB8rm:
3522   case X86::DEC64r:    case X86::DEC32r:   case X86::DEC16r: case X86::DEC8r:
3523   case X86::ADD64ri32: case X86::ADD64ri8: case X86::ADD32ri:
3524   case X86::ADD32ri8:  case X86::ADD16ri:  case X86::ADD16ri8:
3525   case X86::ADD8ri:    case X86::ADD64rr:  case X86::ADD32rr:
3526   case X86::ADD16rr:   case X86::ADD8rr:   case X86::ADD64rm:
3527   case X86::ADD32rm:   case X86::ADD16rm:  case X86::ADD8rm:
3528   case X86::INC64r:    case X86::INC32r:   case X86::INC16r: case X86::INC8r:
3529   case X86::AND64ri32: case X86::AND64ri8: case X86::AND32ri:
3530   case X86::AND32ri8:  case X86::AND16ri:  case X86::AND16ri8:
3531   case X86::AND8ri:    case X86::AND64rr:  case X86::AND32rr:
3532   case X86::AND16rr:   case X86::AND8rr:   case X86::AND64rm:
3533   case X86::AND32rm:   case X86::AND16rm:  case X86::AND8rm:
3534   case X86::XOR64ri32: case X86::XOR64ri8: case X86::XOR32ri:
3535   case X86::XOR32ri8:  case X86::XOR16ri:  case X86::XOR16ri8:
3536   case X86::XOR8ri:    case X86::XOR64rr:  case X86::XOR32rr:
3537   case X86::XOR16rr:   case X86::XOR8rr:   case X86::XOR64rm:
3538   case X86::XOR32rm:   case X86::XOR16rm:  case X86::XOR8rm:
3539   case X86::OR64ri32:  case X86::OR64ri8:  case X86::OR32ri:
3540   case X86::OR32ri8:   case X86::OR16ri:   case X86::OR16ri8:
3541   case X86::OR8ri:     case X86::OR64rr:   case X86::OR32rr:
3542   case X86::OR16rr:    case X86::OR8rr:    case X86::OR64rm:
3543   case X86::OR32rm:    case X86::OR16rm:   case X86::OR8rm:
3544   case X86::ADC64ri32: case X86::ADC64ri8: case X86::ADC32ri:
3545   case X86::ADC32ri8:  case X86::ADC16ri:  case X86::ADC16ri8:
3546   case X86::ADC8ri:    case X86::ADC64rr:  case X86::ADC32rr:
3547   case X86::ADC16rr:   case X86::ADC8rr:   case X86::ADC64rm:
3548   case X86::ADC32rm:   case X86::ADC16rm:  case X86::ADC8rm:
3549   case X86::SBB64ri32: case X86::SBB64ri8: case X86::SBB32ri:
3550   case X86::SBB32ri8:  case X86::SBB16ri:  case X86::SBB16ri8:
3551   case X86::SBB8ri:    case X86::SBB64rr:  case X86::SBB32rr:
3552   case X86::SBB16rr:   case X86::SBB8rr:   case X86::SBB64rm:
3553   case X86::SBB32rm:   case X86::SBB16rm:  case X86::SBB8rm:
3554   case X86::NEG8r:     case X86::NEG16r:   case X86::NEG32r: case X86::NEG64r:
3555   case X86::SAR8r1:    case X86::SAR16r1:  case X86::SAR32r1:case X86::SAR64r1:
3556   case X86::SHR8r1:    case X86::SHR16r1:  case X86::SHR32r1:case X86::SHR64r1:
3557   case X86::SHL8r1:    case X86::SHL16r1:  case X86::SHL32r1:case X86::SHL64r1:
3558   case X86::ANDN32rr:  case X86::ANDN32rm:
3559   case X86::ANDN64rr:  case X86::ANDN64rm:
3560   case X86::BEXTR32rr: case X86::BEXTR64rr:
3561   case X86::BEXTR32rm: case X86::BEXTR64rm:
3562   case X86::BLSI32rr:  case X86::BLSI32rm:
3563   case X86::BLSI64rr:  case X86::BLSI64rm:
3564   case X86::BLSMSK32rr:case X86::BLSMSK32rm:
3565   case X86::BLSMSK64rr:case X86::BLSMSK64rm:
3566   case X86::BLSR32rr:  case X86::BLSR32rm:
3567   case X86::BLSR64rr:  case X86::BLSR64rm:
3568   case X86::BZHI32rr:  case X86::BZHI32rm:
3569   case X86::BZHI64rr:  case X86::BZHI64rm:
3570   case X86::LZCNT16rr: case X86::LZCNT16rm:
3571   case X86::LZCNT32rr: case X86::LZCNT32rm:
3572   case X86::LZCNT64rr: case X86::LZCNT64rm:
3573   case X86::POPCNT16rr:case X86::POPCNT16rm:
3574   case X86::POPCNT32rr:case X86::POPCNT32rm:
3575   case X86::POPCNT64rr:case X86::POPCNT64rm:
3576   case X86::TZCNT16rr: case X86::TZCNT16rm:
3577   case X86::TZCNT32rr: case X86::TZCNT32rm:
3578   case X86::TZCNT64rr: case X86::TZCNT64rm:
3579   case X86::BEXTRI32ri:  case X86::BEXTRI32mi:
3580   case X86::BEXTRI64ri:  case X86::BEXTRI64mi:
3581   case X86::BLCFILL32rr: case X86::BLCFILL32rm:
3582   case X86::BLCFILL64rr: case X86::BLCFILL64rm:
3583   case X86::BLCI32rr:    case X86::BLCI32rm:
3584   case X86::BLCI64rr:    case X86::BLCI64rm:
3585   case X86::BLCIC32rr:   case X86::BLCIC32rm:
3586   case X86::BLCIC64rr:   case X86::BLCIC64rm:
3587   case X86::BLCMSK32rr:  case X86::BLCMSK32rm:
3588   case X86::BLCMSK64rr:  case X86::BLCMSK64rm:
3589   case X86::BLCS32rr:    case X86::BLCS32rm:
3590   case X86::BLCS64rr:    case X86::BLCS64rm:
3591   case X86::BLSFILL32rr: case X86::BLSFILL32rm:
3592   case X86::BLSFILL64rr: case X86::BLSFILL64rm:
3593   case X86::BLSIC32rr:   case X86::BLSIC32rm:
3594   case X86::BLSIC64rr:   case X86::BLSIC64rm:
3595     return true;
3596   }
3597 }
3598 
3599 /// Check whether the use can be converted to remove a comparison against zero.
3600 static X86::CondCode isUseDefConvertible(MachineInstr &MI) {
3601   switch (MI.getOpcode()) {
3602   default: return X86::COND_INVALID;
3603   case X86::LZCNT16rr: case X86::LZCNT16rm:
3604   case X86::LZCNT32rr: case X86::LZCNT32rm:
3605   case X86::LZCNT64rr: case X86::LZCNT64rm:
3606     return X86::COND_B;
3607   case X86::POPCNT16rr:case X86::POPCNT16rm:
3608   case X86::POPCNT32rr:case X86::POPCNT32rm:
3609   case X86::POPCNT64rr:case X86::POPCNT64rm:
3610     return X86::COND_E;
3611   case X86::TZCNT16rr: case X86::TZCNT16rm:
3612   case X86::TZCNT32rr: case X86::TZCNT32rm:
3613   case X86::TZCNT64rr: case X86::TZCNT64rm:
3614     return X86::COND_B;
3615   case X86::BSF16rr:
3616   case X86::BSF16rm:
3617   case X86::BSF32rr:
3618   case X86::BSF32rm:
3619   case X86::BSF64rr:
3620   case X86::BSF64rm:
3621     return X86::COND_E;
3622   }
3623 }
3624 
3625 /// Check if there exists an earlier instruction that
3626 /// operates on the same source operands and sets flags in the same way as
3627 /// Compare; remove Compare if possible.
3628 bool X86InstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
3629                                         unsigned SrcReg2, int CmpMask,
3630                                         int CmpValue,
3631                                         const MachineRegisterInfo *MRI) const {
3632   // Check whether we can replace SUB with CMP.
3633   unsigned NewOpcode = 0;
3634   switch (CmpInstr.getOpcode()) {
3635   default: break;
3636   case X86::SUB64ri32:
3637   case X86::SUB64ri8:
3638   case X86::SUB32ri:
3639   case X86::SUB32ri8:
3640   case X86::SUB16ri:
3641   case X86::SUB16ri8:
3642   case X86::SUB8ri:
3643   case X86::SUB64rm:
3644   case X86::SUB32rm:
3645   case X86::SUB16rm:
3646   case X86::SUB8rm:
3647   case X86::SUB64rr:
3648   case X86::SUB32rr:
3649   case X86::SUB16rr:
3650   case X86::SUB8rr: {
3651     if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
3652       return false;
3653     // There is no use of the destination register, we can replace SUB with CMP.
3654     switch (CmpInstr.getOpcode()) {
3655     default: llvm_unreachable("Unreachable!");
3656     case X86::SUB64rm:   NewOpcode = X86::CMP64rm;   break;
3657     case X86::SUB32rm:   NewOpcode = X86::CMP32rm;   break;
3658     case X86::SUB16rm:   NewOpcode = X86::CMP16rm;   break;
3659     case X86::SUB8rm:    NewOpcode = X86::CMP8rm;    break;
3660     case X86::SUB64rr:   NewOpcode = X86::CMP64rr;   break;
3661     case X86::SUB32rr:   NewOpcode = X86::CMP32rr;   break;
3662     case X86::SUB16rr:   NewOpcode = X86::CMP16rr;   break;
3663     case X86::SUB8rr:    NewOpcode = X86::CMP8rr;    break;
3664     case X86::SUB64ri32: NewOpcode = X86::CMP64ri32; break;
3665     case X86::SUB64ri8:  NewOpcode = X86::CMP64ri8;  break;
3666     case X86::SUB32ri:   NewOpcode = X86::CMP32ri;   break;
3667     case X86::SUB32ri8:  NewOpcode = X86::CMP32ri8;  break;
3668     case X86::SUB16ri:   NewOpcode = X86::CMP16ri;   break;
3669     case X86::SUB16ri8:  NewOpcode = X86::CMP16ri8;  break;
3670     case X86::SUB8ri:    NewOpcode = X86::CMP8ri;    break;
3671     }
3672     CmpInstr.setDesc(get(NewOpcode));
3673     CmpInstr.RemoveOperand(0);
3674     // Fall through to optimize Cmp if Cmp is CMPrr or CMPri.
3675     if (NewOpcode == X86::CMP64rm || NewOpcode == X86::CMP32rm ||
3676         NewOpcode == X86::CMP16rm || NewOpcode == X86::CMP8rm)
3677       return false;
3678   }
3679   }
3680 
3681   // Get the unique definition of SrcReg.
3682   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
3683   if (!MI) return false;
3684 
3685   // CmpInstr is the first instruction of the BB.
3686   MachineBasicBlock::iterator I = CmpInstr, Def = MI;
3687 
3688   // If we are comparing against zero, check whether we can use MI to update
3689   // EFLAGS. If MI is not in the same BB as CmpInstr, do not optimize.
3690   bool IsCmpZero = (CmpMask != 0 && CmpValue == 0);
3691   if (IsCmpZero && MI->getParent() != CmpInstr.getParent())
3692     return false;
3693 
3694   // If we have a use of the source register between the def and our compare
3695   // instruction we can eliminate the compare iff the use sets EFLAGS in the
3696   // right way.
3697   bool ShouldUpdateCC = false;
3698   X86::CondCode NewCC = X86::COND_INVALID;
3699   if (IsCmpZero && !isDefConvertible(*MI)) {
3700     // Scan forward from the use until we hit the use we're looking for or the
3701     // compare instruction.
3702     for (MachineBasicBlock::iterator J = MI;; ++J) {
3703       // Do we have a convertible instruction?
3704       NewCC = isUseDefConvertible(*J);
3705       if (NewCC != X86::COND_INVALID && J->getOperand(1).isReg() &&
3706           J->getOperand(1).getReg() == SrcReg) {
3707         assert(J->definesRegister(X86::EFLAGS) && "Must be an EFLAGS def!");
3708         ShouldUpdateCC = true; // Update CC later on.
3709         // This is not a def of SrcReg, but still a def of EFLAGS. Keep going
3710         // with the new def.
3711         Def = J;
3712         MI = &*Def;
3713         break;
3714       }
3715 
3716       if (J == I)
3717         return false;
3718     }
3719   }
3720 
3721   // We are searching for an earlier instruction that can make CmpInstr
3722   // redundant and that instruction will be saved in Sub.
3723   MachineInstr *Sub = nullptr;
3724   const TargetRegisterInfo *TRI = &getRegisterInfo();
3725 
3726   // We iterate backward, starting from the instruction before CmpInstr and
3727   // stop when reaching the definition of a source register or done with the BB.
3728   // RI points to the instruction before CmpInstr.
3729   // If the definition is in this basic block, RE points to the definition;
3730   // otherwise, RE is the rend of the basic block.
3731   MachineBasicBlock::reverse_iterator
3732       RI = ++I.getReverse(),
3733       RE = CmpInstr.getParent() == MI->getParent()
3734                ? Def.getReverse() /* points to MI */
3735                : CmpInstr.getParent()->rend();
3736   MachineInstr *Movr0Inst = nullptr;
3737   for (; RI != RE; ++RI) {
3738     MachineInstr &Instr = *RI;
3739     // Check whether CmpInstr can be made redundant by the current instruction.
3740     if (!IsCmpZero && isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpMask,
3741                                            CmpValue, Instr)) {
3742       Sub = &Instr;
3743       break;
3744     }
3745 
3746     if (Instr.modifiesRegister(X86::EFLAGS, TRI) ||
3747         Instr.readsRegister(X86::EFLAGS, TRI)) {
3748       // This instruction modifies or uses EFLAGS.
3749 
3750       // MOV32r0 etc. are implemented with xor which clobbers condition code.
3751       // They are safe to move up, if the definition to EFLAGS is dead and
3752       // earlier instructions do not read or write EFLAGS.
3753       if (!Movr0Inst && Instr.getOpcode() == X86::MOV32r0 &&
3754           Instr.registerDefIsDead(X86::EFLAGS, TRI)) {
3755         Movr0Inst = &Instr;
3756         continue;
3757       }
3758 
3759       // We can't remove CmpInstr.
3760       return false;
3761     }
3762   }
3763 
3764   // Return false if no candidates exist.
3765   if (!IsCmpZero && !Sub)
3766     return false;
3767 
3768   bool IsSwapped = (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
3769                     Sub->getOperand(2).getReg() == SrcReg);
3770 
3771   // Scan forward from the instruction after CmpInstr for uses of EFLAGS.
3772   // It is safe to remove CmpInstr if EFLAGS is redefined or killed.
3773   // If we are done with the basic block, we need to check whether EFLAGS is
3774   // live-out.
3775   bool IsSafe = false;
3776   SmallVector<std::pair<MachineInstr*, unsigned /*NewOpc*/>, 4> OpsToUpdate;
3777   MachineBasicBlock::iterator E = CmpInstr.getParent()->end();
3778   for (++I; I != E; ++I) {
3779     const MachineInstr &Instr = *I;
3780     bool ModifyEFLAGS = Instr.modifiesRegister(X86::EFLAGS, TRI);
3781     bool UseEFLAGS = Instr.readsRegister(X86::EFLAGS, TRI);
3782     // We should check the usage if this instruction uses and updates EFLAGS.
3783     if (!UseEFLAGS && ModifyEFLAGS) {
3784       // It is safe to remove CmpInstr if EFLAGS is updated again.
3785       IsSafe = true;
3786       break;
3787     }
3788     if (!UseEFLAGS && !ModifyEFLAGS)
3789       continue;
3790 
3791     // EFLAGS is used by this instruction.
3792     X86::CondCode OldCC = X86::COND_INVALID;
3793     bool OpcIsSET = false;
3794     if (IsCmpZero || IsSwapped) {
3795       // We decode the condition code from opcode.
3796       if (Instr.isBranch())
3797         OldCC = X86::getCondFromBranchOpc(Instr.getOpcode());
3798       else {
3799         OldCC = X86::getCondFromSETOpc(Instr.getOpcode());
3800         if (OldCC != X86::COND_INVALID)
3801           OpcIsSET = true;
3802         else
3803           OldCC = X86::getCondFromCMovOpc(Instr.getOpcode());
3804       }
3805       if (OldCC == X86::COND_INVALID) return false;
3806     }
3807     X86::CondCode ReplacementCC = X86::COND_INVALID;
3808     if (IsCmpZero) {
3809       switch (OldCC) {
3810       default: break;
3811       case X86::COND_A: case X86::COND_AE:
3812       case X86::COND_B: case X86::COND_BE:
3813       case X86::COND_G: case X86::COND_GE:
3814       case X86::COND_L: case X86::COND_LE:
3815       case X86::COND_O: case X86::COND_NO:
3816         // CF and OF are used, we can't perform this optimization.
3817         return false;
3818       }
3819 
3820       // If we're updating the condition code check if we have to reverse the
3821       // condition.
3822       if (ShouldUpdateCC)
3823         switch (OldCC) {
3824         default:
3825           return false;
3826         case X86::COND_E:
3827           ReplacementCC = NewCC;
3828           break;
3829         case X86::COND_NE:
3830           ReplacementCC = GetOppositeBranchCondition(NewCC);
3831           break;
3832         }
3833     } else if (IsSwapped) {
3834       // If we have SUB(r1, r2) and CMP(r2, r1), the condition code needs
3835       // to be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3836       // We swap the condition code and synthesize the new opcode.
3837       ReplacementCC = getSwappedCondition(OldCC);
3838       if (ReplacementCC == X86::COND_INVALID) return false;
3839     }
3840 
3841     if ((ShouldUpdateCC || IsSwapped) && ReplacementCC != OldCC) {
3842       // Synthesize the new opcode.
3843       bool HasMemoryOperand = Instr.hasOneMemOperand();
3844       unsigned NewOpc;
3845       if (Instr.isBranch())
3846         NewOpc = GetCondBranchFromCond(ReplacementCC);
3847       else if(OpcIsSET)
3848         NewOpc = getSETFromCond(ReplacementCC, HasMemoryOperand);
3849       else {
3850         unsigned DstReg = Instr.getOperand(0).getReg();
3851         const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
3852         NewOpc = getCMovFromCond(ReplacementCC, TRI->getRegSizeInBits(*DstRC)/8,
3853                                  HasMemoryOperand);
3854       }
3855 
3856       // Push the MachineInstr to OpsToUpdate.
3857       // If it is safe to remove CmpInstr, the condition code of these
3858       // instructions will be modified.
3859       OpsToUpdate.push_back(std::make_pair(&*I, NewOpc));
3860     }
3861     if (ModifyEFLAGS || Instr.killsRegister(X86::EFLAGS, TRI)) {
3862       // It is safe to remove CmpInstr if EFLAGS is updated again or killed.
3863       IsSafe = true;
3864       break;
3865     }
3866   }
3867 
3868   // If EFLAGS is not killed nor re-defined, we should check whether it is
3869   // live-out. If it is live-out, do not optimize.
3870   if ((IsCmpZero || IsSwapped) && !IsSafe) {
3871     MachineBasicBlock *MBB = CmpInstr.getParent();
3872     for (MachineBasicBlock *Successor : MBB->successors())
3873       if (Successor->isLiveIn(X86::EFLAGS))
3874         return false;
3875   }
3876 
3877   // The instruction to be updated is either Sub or MI.
3878   Sub = IsCmpZero ? MI : Sub;
3879   // Move Movr0Inst to the appropriate place before Sub.
3880   if (Movr0Inst) {
3881     // Look backwards until we find a def that doesn't use the current EFLAGS.
3882     Def = Sub;
3883     MachineBasicBlock::reverse_iterator InsertI = Def.getReverse(),
3884                                         InsertE = Sub->getParent()->rend();
3885     for (; InsertI != InsertE; ++InsertI) {
3886       MachineInstr *Instr = &*InsertI;
3887       if (!Instr->readsRegister(X86::EFLAGS, TRI) &&
3888           Instr->modifiesRegister(X86::EFLAGS, TRI)) {
3889         Sub->getParent()->remove(Movr0Inst);
3890         Instr->getParent()->insert(MachineBasicBlock::iterator(Instr),
3891                                    Movr0Inst);
3892         break;
3893       }
3894     }
3895     if (InsertI == InsertE)
3896       return false;
3897   }
3898 
3899   // Make sure Sub instruction defines EFLAGS and mark the def live.
3900   unsigned i = 0, e = Sub->getNumOperands();
3901   for (; i != e; ++i) {
3902     MachineOperand &MO = Sub->getOperand(i);
3903     if (MO.isReg() && MO.isDef() && MO.getReg() == X86::EFLAGS) {
3904       MO.setIsDead(false);
3905       break;
3906     }
3907   }
3908   assert(i != e && "Unable to locate a def EFLAGS operand");
3909 
3910   CmpInstr.eraseFromParent();
3911 
3912   // Modify the condition code of instructions in OpsToUpdate.
3913   for (auto &Op : OpsToUpdate)
3914     Op.first->setDesc(get(Op.second));
3915   return true;
3916 }
3917 
3918 /// Try to remove the load by folding it to a register
3919 /// operand at the use. We fold the load instructions if load defines a virtual
3920 /// register, the virtual register is used once in the same BB, and the
3921 /// instructions in-between do not load or store, and have no side effects.
3922 MachineInstr *X86InstrInfo::optimizeLoadInstr(MachineInstr &MI,
3923                                               const MachineRegisterInfo *MRI,
3924                                               unsigned &FoldAsLoadDefReg,
3925                                               MachineInstr *&DefMI) const {
3926   // Check whether we can move DefMI here.
3927   DefMI = MRI->getVRegDef(FoldAsLoadDefReg);
3928   assert(DefMI);
3929   bool SawStore = false;
3930   if (!DefMI->isSafeToMove(nullptr, SawStore))
3931     return nullptr;
3932 
3933   // Collect information about virtual register operands of MI.
3934   SmallVector<unsigned, 1> SrcOperandIds;
3935   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3936     MachineOperand &MO = MI.getOperand(i);
3937     if (!MO.isReg())
3938       continue;
3939     unsigned Reg = MO.getReg();
3940     if (Reg != FoldAsLoadDefReg)
3941       continue;
3942     // Do not fold if we have a subreg use or a def.
3943     if (MO.getSubReg() || MO.isDef())
3944       return nullptr;
3945     SrcOperandIds.push_back(i);
3946   }
3947   if (SrcOperandIds.empty())
3948     return nullptr;
3949 
3950   // Check whether we can fold the def into SrcOperandId.
3951   if (MachineInstr *FoldMI = foldMemoryOperand(MI, SrcOperandIds, *DefMI)) {
3952     FoldAsLoadDefReg = 0;
3953     return FoldMI;
3954   }
3955 
3956   return nullptr;
3957 }
3958 
3959 /// Expand a single-def pseudo instruction to a two-addr
3960 /// instruction with two undef reads of the register being defined.
3961 /// This is used for mapping:
3962 ///   %xmm4 = V_SET0
3963 /// to:
3964 ///   %xmm4 = PXORrr undef %xmm4, undef %xmm4
3965 ///
3966 static bool Expand2AddrUndef(MachineInstrBuilder &MIB,
3967                              const MCInstrDesc &Desc) {
3968   assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
3969   unsigned Reg = MIB->getOperand(0).getReg();
3970   MIB->setDesc(Desc);
3971 
3972   // MachineInstr::addOperand() will insert explicit operands before any
3973   // implicit operands.
3974   MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
3975   // But we don't trust that.
3976   assert(MIB->getOperand(1).getReg() == Reg &&
3977          MIB->getOperand(2).getReg() == Reg && "Misplaced operand");
3978   return true;
3979 }
3980 
3981 /// Expand a single-def pseudo instruction to a two-addr
3982 /// instruction with two %k0 reads.
3983 /// This is used for mapping:
3984 ///   %k4 = K_SET1
3985 /// to:
3986 ///   %k4 = KXNORrr %k0, %k0
3987 static bool Expand2AddrKreg(MachineInstrBuilder &MIB,
3988                             const MCInstrDesc &Desc, unsigned Reg) {
3989   assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
3990   MIB->setDesc(Desc);
3991   MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
3992   return true;
3993 }
3994 
3995 static bool expandMOV32r1(MachineInstrBuilder &MIB, const TargetInstrInfo &TII,
3996                           bool MinusOne) {
3997   MachineBasicBlock &MBB = *MIB->getParent();
3998   DebugLoc DL = MIB->getDebugLoc();
3999   unsigned Reg = MIB->getOperand(0).getReg();
4000 
4001   // Insert the XOR.
4002   BuildMI(MBB, MIB.getInstr(), DL, TII.get(X86::XOR32rr), Reg)
4003       .addReg(Reg, RegState::Undef)
4004       .addReg(Reg, RegState::Undef);
4005 
4006   // Turn the pseudo into an INC or DEC.
4007   MIB->setDesc(TII.get(MinusOne ? X86::DEC32r : X86::INC32r));
4008   MIB.addReg(Reg);
4009 
4010   return true;
4011 }
4012 
4013 static bool ExpandMOVImmSExti8(MachineInstrBuilder &MIB,
4014                                const TargetInstrInfo &TII,
4015                                const X86Subtarget &Subtarget) {
4016   MachineBasicBlock &MBB = *MIB->getParent();
4017   DebugLoc DL = MIB->getDebugLoc();
4018   int64_t Imm = MIB->getOperand(1).getImm();
4019   assert(Imm != 0 && "Using push/pop for 0 is not efficient.");
4020   MachineBasicBlock::iterator I = MIB.getInstr();
4021 
4022   int StackAdjustment;
4023 
4024   if (Subtarget.is64Bit()) {
4025     assert(MIB->getOpcode() == X86::MOV64ImmSExti8 ||
4026            MIB->getOpcode() == X86::MOV32ImmSExti8);
4027 
4028     // Can't use push/pop lowering if the function might write to the red zone.
4029     X86MachineFunctionInfo *X86FI =
4030         MBB.getParent()->getInfo<X86MachineFunctionInfo>();
4031     if (X86FI->getUsesRedZone()) {
4032       MIB->setDesc(TII.get(MIB->getOpcode() ==
4033                            X86::MOV32ImmSExti8 ? X86::MOV32ri : X86::MOV64ri));
4034       return true;
4035     }
4036 
4037     // 64-bit mode doesn't have 32-bit push/pop, so use 64-bit operations and
4038     // widen the register if necessary.
4039     StackAdjustment = 8;
4040     BuildMI(MBB, I, DL, TII.get(X86::PUSH64i8)).addImm(Imm);
4041     MIB->setDesc(TII.get(X86::POP64r));
4042     MIB->getOperand(0)
4043         .setReg(getX86SubSuperRegister(MIB->getOperand(0).getReg(), 64));
4044   } else {
4045     assert(MIB->getOpcode() == X86::MOV32ImmSExti8);
4046     StackAdjustment = 4;
4047     BuildMI(MBB, I, DL, TII.get(X86::PUSH32i8)).addImm(Imm);
4048     MIB->setDesc(TII.get(X86::POP32r));
4049   }
4050 
4051   // Build CFI if necessary.
4052   MachineFunction &MF = *MBB.getParent();
4053   const X86FrameLowering *TFL = Subtarget.getFrameLowering();
4054   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
4055   bool NeedsDwarfCFI =
4056       !IsWin64Prologue &&
4057       (MF.getMMI().hasDebugInfo() || MF.getFunction().needsUnwindTableEntry());
4058   bool EmitCFI = !TFL->hasFP(MF) && NeedsDwarfCFI;
4059   if (EmitCFI) {
4060     TFL->BuildCFI(MBB, I, DL,
4061         MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
4062     TFL->BuildCFI(MBB, std::next(I), DL,
4063         MCCFIInstruction::createAdjustCfaOffset(nullptr, -StackAdjustment));
4064   }
4065 
4066   return true;
4067 }
4068 
4069 // LoadStackGuard has so far only been implemented for 64-bit MachO. Different
4070 // code sequence is needed for other targets.
4071 static void expandLoadStackGuard(MachineInstrBuilder &MIB,
4072                                  const TargetInstrInfo &TII) {
4073   MachineBasicBlock &MBB = *MIB->getParent();
4074   DebugLoc DL = MIB->getDebugLoc();
4075   unsigned Reg = MIB->getOperand(0).getReg();
4076   const GlobalValue *GV =
4077       cast<GlobalValue>((*MIB->memoperands_begin())->getValue());
4078   auto Flags = MachineMemOperand::MOLoad |
4079                MachineMemOperand::MODereferenceable |
4080                MachineMemOperand::MOInvariant;
4081   MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
4082       MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 8, 8);
4083   MachineBasicBlock::iterator I = MIB.getInstr();
4084 
4085   BuildMI(MBB, I, DL, TII.get(X86::MOV64rm), Reg).addReg(X86::RIP).addImm(1)
4086       .addReg(0).addGlobalAddress(GV, 0, X86II::MO_GOTPCREL).addReg(0)
4087       .addMemOperand(MMO);
4088   MIB->setDebugLoc(DL);
4089   MIB->setDesc(TII.get(X86::MOV64rm));
4090   MIB.addReg(Reg, RegState::Kill).addImm(1).addReg(0).addImm(0).addReg(0);
4091 }
4092 
4093 static bool expandXorFP(MachineInstrBuilder &MIB, const TargetInstrInfo &TII) {
4094   MachineBasicBlock &MBB = *MIB->getParent();
4095   MachineFunction &MF = *MBB.getParent();
4096   const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
4097   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4098   unsigned XorOp =
4099       MIB->getOpcode() == X86::XOR64_FP ? X86::XOR64rr : X86::XOR32rr;
4100   MIB->setDesc(TII.get(XorOp));
4101   MIB.addReg(TRI->getFrameRegister(MF), RegState::Undef);
4102   return true;
4103 }
4104 
4105 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4106 // but not VLX. If it uses an extended register we need to use an instruction
4107 // that loads the lower 128/256-bit, but is available with only AVX512F.
4108 static bool expandNOVLXLoad(MachineInstrBuilder &MIB,
4109                             const TargetRegisterInfo *TRI,
4110                             const MCInstrDesc &LoadDesc,
4111                             const MCInstrDesc &BroadcastDesc,
4112                             unsigned SubIdx) {
4113   unsigned DestReg = MIB->getOperand(0).getReg();
4114   // Check if DestReg is XMM16-31 or YMM16-31.
4115   if (TRI->getEncodingValue(DestReg) < 16) {
4116     // We can use a normal VEX encoded load.
4117     MIB->setDesc(LoadDesc);
4118   } else {
4119     // Use a 128/256-bit VBROADCAST instruction.
4120     MIB->setDesc(BroadcastDesc);
4121     // Change the destination to a 512-bit register.
4122     DestReg = TRI->getMatchingSuperReg(DestReg, SubIdx, &X86::VR512RegClass);
4123     MIB->getOperand(0).setReg(DestReg);
4124   }
4125   return true;
4126 }
4127 
4128 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4129 // but not VLX. If it uses an extended register we need to use an instruction
4130 // that stores the lower 128/256-bit, but is available with only AVX512F.
4131 static bool expandNOVLXStore(MachineInstrBuilder &MIB,
4132                              const TargetRegisterInfo *TRI,
4133                              const MCInstrDesc &StoreDesc,
4134                              const MCInstrDesc &ExtractDesc,
4135                              unsigned SubIdx) {
4136   unsigned SrcReg = MIB->getOperand(X86::AddrNumOperands).getReg();
4137   // Check if DestReg is XMM16-31 or YMM16-31.
4138   if (TRI->getEncodingValue(SrcReg) < 16) {
4139     // We can use a normal VEX encoded store.
4140     MIB->setDesc(StoreDesc);
4141   } else {
4142     // Use a VEXTRACTF instruction.
4143     MIB->setDesc(ExtractDesc);
4144     // Change the destination to a 512-bit register.
4145     SrcReg = TRI->getMatchingSuperReg(SrcReg, SubIdx, &X86::VR512RegClass);
4146     MIB->getOperand(X86::AddrNumOperands).setReg(SrcReg);
4147     MIB.addImm(0x0); // Append immediate to extract from the lower bits.
4148   }
4149 
4150   return true;
4151 }
4152 bool X86InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
4153   bool HasAVX = Subtarget.hasAVX();
4154   MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4155   switch (MI.getOpcode()) {
4156   case X86::MOV32r0:
4157     return Expand2AddrUndef(MIB, get(X86::XOR32rr));
4158   case X86::MOV32r1:
4159     return expandMOV32r1(MIB, *this, /*MinusOne=*/ false);
4160   case X86::MOV32r_1:
4161     return expandMOV32r1(MIB, *this, /*MinusOne=*/ true);
4162   case X86::MOV32ImmSExti8:
4163   case X86::MOV64ImmSExti8:
4164     return ExpandMOVImmSExti8(MIB, *this, Subtarget);
4165   case X86::SETB_C8r:
4166     return Expand2AddrUndef(MIB, get(X86::SBB8rr));
4167   case X86::SETB_C16r:
4168     return Expand2AddrUndef(MIB, get(X86::SBB16rr));
4169   case X86::SETB_C32r:
4170     return Expand2AddrUndef(MIB, get(X86::SBB32rr));
4171   case X86::SETB_C64r:
4172     return Expand2AddrUndef(MIB, get(X86::SBB64rr));
4173   case X86::MMX_SET0:
4174     return Expand2AddrUndef(MIB, get(X86::MMX_PXORirr));
4175   case X86::V_SET0:
4176   case X86::FsFLD0SS:
4177   case X86::FsFLD0SD:
4178     return Expand2AddrUndef(MIB, get(HasAVX ? X86::VXORPSrr : X86::XORPSrr));
4179   case X86::AVX_SET0: {
4180     assert(HasAVX && "AVX not supported");
4181     const TargetRegisterInfo *TRI = &getRegisterInfo();
4182     unsigned SrcReg = MIB->getOperand(0).getReg();
4183     unsigned XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
4184     MIB->getOperand(0).setReg(XReg);
4185     Expand2AddrUndef(MIB, get(X86::VXORPSrr));
4186     MIB.addReg(SrcReg, RegState::ImplicitDefine);
4187     return true;
4188   }
4189   case X86::AVX512_128_SET0:
4190   case X86::AVX512_FsFLD0SS:
4191   case X86::AVX512_FsFLD0SD: {
4192     bool HasVLX = Subtarget.hasVLX();
4193     unsigned SrcReg = MIB->getOperand(0).getReg();
4194     const TargetRegisterInfo *TRI = &getRegisterInfo();
4195     if (HasVLX || TRI->getEncodingValue(SrcReg) < 16)
4196       return Expand2AddrUndef(MIB,
4197                               get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
4198     // Extended register without VLX. Use a larger XOR.
4199     SrcReg =
4200         TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm, &X86::VR512RegClass);
4201     MIB->getOperand(0).setReg(SrcReg);
4202     return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
4203   }
4204   case X86::AVX512_256_SET0:
4205   case X86::AVX512_512_SET0: {
4206     bool HasVLX = Subtarget.hasVLX();
4207     unsigned SrcReg = MIB->getOperand(0).getReg();
4208     const TargetRegisterInfo *TRI = &getRegisterInfo();
4209     if (HasVLX || TRI->getEncodingValue(SrcReg) < 16) {
4210       unsigned XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
4211       MIB->getOperand(0).setReg(XReg);
4212       Expand2AddrUndef(MIB,
4213                        get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
4214       MIB.addReg(SrcReg, RegState::ImplicitDefine);
4215       return true;
4216     }
4217     return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
4218   }
4219   case X86::V_SETALLONES:
4220     return Expand2AddrUndef(MIB, get(HasAVX ? X86::VPCMPEQDrr : X86::PCMPEQDrr));
4221   case X86::AVX2_SETALLONES:
4222     return Expand2AddrUndef(MIB, get(X86::VPCMPEQDYrr));
4223   case X86::AVX1_SETALLONES: {
4224     unsigned Reg = MIB->getOperand(0).getReg();
4225     // VCMPPSYrri with an immediate 0xf should produce VCMPTRUEPS.
4226     MIB->setDesc(get(X86::VCMPPSYrri));
4227     MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xf);
4228     return true;
4229   }
4230   case X86::AVX512_512_SETALLONES: {
4231     unsigned Reg = MIB->getOperand(0).getReg();
4232     MIB->setDesc(get(X86::VPTERNLOGDZrri));
4233     // VPTERNLOGD needs 3 register inputs and an immediate.
4234     // 0xff will return 1s for any input.
4235     MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef)
4236        .addReg(Reg, RegState::Undef).addImm(0xff);
4237     return true;
4238   }
4239   case X86::AVX512_512_SEXT_MASK_32:
4240   case X86::AVX512_512_SEXT_MASK_64: {
4241     unsigned Reg = MIB->getOperand(0).getReg();
4242     unsigned MaskReg = MIB->getOperand(1).getReg();
4243     unsigned MaskState = getRegState(MIB->getOperand(1));
4244     unsigned Opc = (MI.getOpcode() == X86::AVX512_512_SEXT_MASK_64) ?
4245                    X86::VPTERNLOGQZrrikz : X86::VPTERNLOGDZrrikz;
4246     MI.RemoveOperand(1);
4247     MIB->setDesc(get(Opc));
4248     // VPTERNLOG needs 3 register inputs and an immediate.
4249     // 0xff will return 1s for any input.
4250     MIB.addReg(Reg, RegState::Undef).addReg(MaskReg, MaskState)
4251        .addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xff);
4252     return true;
4253   }
4254   case X86::VMOVAPSZ128rm_NOVLX:
4255     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSrm),
4256                            get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
4257   case X86::VMOVUPSZ128rm_NOVLX:
4258     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSrm),
4259                            get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
4260   case X86::VMOVAPSZ256rm_NOVLX:
4261     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSYrm),
4262                            get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
4263   case X86::VMOVUPSZ256rm_NOVLX:
4264     return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSYrm),
4265                            get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
4266   case X86::VMOVAPSZ128mr_NOVLX:
4267     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSmr),
4268                             get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
4269   case X86::VMOVUPSZ128mr_NOVLX:
4270     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSmr),
4271                             get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
4272   case X86::VMOVAPSZ256mr_NOVLX:
4273     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSYmr),
4274                             get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
4275   case X86::VMOVUPSZ256mr_NOVLX:
4276     return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSYmr),
4277                             get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
4278   case X86::MOV32ri64: {
4279     unsigned Reg = MIB->getOperand(0).getReg();
4280     unsigned Reg32 = RI.getSubReg(Reg, X86::sub_32bit);
4281     MI.setDesc(get(X86::MOV32ri));
4282     MIB->getOperand(0).setReg(Reg32);
4283     MIB.addReg(Reg, RegState::ImplicitDefine);
4284     return true;
4285   }
4286 
4287   // KNL does not recognize dependency-breaking idioms for mask registers,
4288   // so kxnor %k1, %k1, %k2 has a RAW dependence on %k1.
4289   // Using %k0 as the undef input register is a performance heuristic based
4290   // on the assumption that %k0 is used less frequently than the other mask
4291   // registers, since it is not usable as a write mask.
4292   // FIXME: A more advanced approach would be to choose the best input mask
4293   // register based on context.
4294   case X86::KSET0W: return Expand2AddrKreg(MIB, get(X86::KXORWrr), X86::K0);
4295   case X86::KSET0D: return Expand2AddrKreg(MIB, get(X86::KXORDrr), X86::K0);
4296   case X86::KSET0Q: return Expand2AddrKreg(MIB, get(X86::KXORQrr), X86::K0);
4297   case X86::KSET1W: return Expand2AddrKreg(MIB, get(X86::KXNORWrr), X86::K0);
4298   case X86::KSET1D: return Expand2AddrKreg(MIB, get(X86::KXNORDrr), X86::K0);
4299   case X86::KSET1Q: return Expand2AddrKreg(MIB, get(X86::KXNORQrr), X86::K0);
4300   case TargetOpcode::LOAD_STACK_GUARD:
4301     expandLoadStackGuard(MIB, *this);
4302     return true;
4303   case X86::XOR64_FP:
4304   case X86::XOR32_FP:
4305     return expandXorFP(MIB, *this);
4306   }
4307   return false;
4308 }
4309 
4310 /// Return true for all instructions that only update
4311 /// the first 32 or 64-bits of the destination register and leave the rest
4312 /// unmodified. This can be used to avoid folding loads if the instructions
4313 /// only update part of the destination register, and the non-updated part is
4314 /// not needed. e.g. cvtss2sd, sqrtss. Unfolding the load from these
4315 /// instructions breaks the partial register dependency and it can improve
4316 /// performance. e.g.:
4317 ///
4318 ///   movss (%rdi), %xmm0
4319 ///   cvtss2sd %xmm0, %xmm0
4320 ///
4321 /// Instead of
4322 ///   cvtss2sd (%rdi), %xmm0
4323 ///
4324 /// FIXME: This should be turned into a TSFlags.
4325 ///
4326 static bool hasPartialRegUpdate(unsigned Opcode,
4327                                 const X86Subtarget &Subtarget) {
4328   switch (Opcode) {
4329   case X86::CVTSI2SSrr:
4330   case X86::CVTSI2SSrm:
4331   case X86::CVTSI642SSrr:
4332   case X86::CVTSI642SSrm:
4333   case X86::CVTSI2SDrr:
4334   case X86::CVTSI2SDrm:
4335   case X86::CVTSI642SDrr:
4336   case X86::CVTSI642SDrm:
4337   case X86::CVTSD2SSrr:
4338   case X86::CVTSD2SSrm:
4339   case X86::CVTSS2SDrr:
4340   case X86::CVTSS2SDrm:
4341   case X86::MOVHPDrm:
4342   case X86::MOVHPSrm:
4343   case X86::MOVLPDrm:
4344   case X86::MOVLPSrm:
4345   case X86::RCPSSr:
4346   case X86::RCPSSm:
4347   case X86::RCPSSr_Int:
4348   case X86::RCPSSm_Int:
4349   case X86::ROUNDSDr:
4350   case X86::ROUNDSDm:
4351   case X86::ROUNDSSr:
4352   case X86::ROUNDSSm:
4353   case X86::RSQRTSSr:
4354   case X86::RSQRTSSm:
4355   case X86::RSQRTSSr_Int:
4356   case X86::RSQRTSSm_Int:
4357   case X86::SQRTSSr:
4358   case X86::SQRTSSm:
4359   case X86::SQRTSSr_Int:
4360   case X86::SQRTSSm_Int:
4361   case X86::SQRTSDr:
4362   case X86::SQRTSDm:
4363   case X86::SQRTSDr_Int:
4364   case X86::SQRTSDm_Int:
4365     return true;
4366   // GPR
4367   case X86::POPCNT32rm:
4368   case X86::POPCNT32rr:
4369   case X86::POPCNT64rm:
4370   case X86::POPCNT64rr:
4371     return Subtarget.hasPOPCNTFalseDeps();
4372   case X86::LZCNT32rm:
4373   case X86::LZCNT32rr:
4374   case X86::LZCNT64rm:
4375   case X86::LZCNT64rr:
4376   case X86::TZCNT32rm:
4377   case X86::TZCNT32rr:
4378   case X86::TZCNT64rm:
4379   case X86::TZCNT64rr:
4380     return Subtarget.hasLZCNTFalseDeps();
4381   }
4382 
4383   return false;
4384 }
4385 
4386 /// Inform the BreakFalseDeps pass how many idle
4387 /// instructions we would like before a partial register update.
4388 unsigned X86InstrInfo::getPartialRegUpdateClearance(
4389     const MachineInstr &MI, unsigned OpNum,
4390     const TargetRegisterInfo *TRI) const {
4391   if (OpNum != 0 || !hasPartialRegUpdate(MI.getOpcode(), Subtarget))
4392     return 0;
4393 
4394   // If MI is marked as reading Reg, the partial register update is wanted.
4395   const MachineOperand &MO = MI.getOperand(0);
4396   unsigned Reg = MO.getReg();
4397   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
4398     if (MO.readsReg() || MI.readsVirtualRegister(Reg))
4399       return 0;
4400   } else {
4401     if (MI.readsRegister(Reg, TRI))
4402       return 0;
4403   }
4404 
4405   // If any instructions in the clearance range are reading Reg, insert a
4406   // dependency breaking instruction, which is inexpensive and is likely to
4407   // be hidden in other instruction's cycles.
4408   return PartialRegUpdateClearance;
4409 }
4410 
4411 // Return true for any instruction the copies the high bits of the first source
4412 // operand into the unused high bits of the destination operand.
4413 static bool hasUndefRegUpdate(unsigned Opcode) {
4414   switch (Opcode) {
4415   case X86::VCVTSI2SSrr:
4416   case X86::VCVTSI2SSrm:
4417   case X86::VCVTSI2SSrr_Int:
4418   case X86::VCVTSI2SSrm_Int:
4419   case X86::VCVTSI642SSrr:
4420   case X86::VCVTSI642SSrm:
4421   case X86::VCVTSI642SSrr_Int:
4422   case X86::VCVTSI642SSrm_Int:
4423   case X86::VCVTSI2SDrr:
4424   case X86::VCVTSI2SDrm:
4425   case X86::VCVTSI2SDrr_Int:
4426   case X86::VCVTSI2SDrm_Int:
4427   case X86::VCVTSI642SDrr:
4428   case X86::VCVTSI642SDrm:
4429   case X86::VCVTSI642SDrr_Int:
4430   case X86::VCVTSI642SDrm_Int:
4431   case X86::VCVTSD2SSrr:
4432   case X86::VCVTSD2SSrm:
4433   case X86::VCVTSD2SSrr_Int:
4434   case X86::VCVTSD2SSrm_Int:
4435   case X86::VCVTSS2SDrr:
4436   case X86::VCVTSS2SDrm:
4437   case X86::VCVTSS2SDrr_Int:
4438   case X86::VCVTSS2SDrm_Int:
4439   case X86::VRCPSSr:
4440   case X86::VRCPSSr_Int:
4441   case X86::VRCPSSm:
4442   case X86::VRCPSSm_Int:
4443   case X86::VROUNDSDr:
4444   case X86::VROUNDSDm:
4445   case X86::VROUNDSDr_Int:
4446   case X86::VROUNDSDm_Int:
4447   case X86::VROUNDSSr:
4448   case X86::VROUNDSSm:
4449   case X86::VROUNDSSr_Int:
4450   case X86::VROUNDSSm_Int:
4451   case X86::VRSQRTSSr:
4452   case X86::VRSQRTSSr_Int:
4453   case X86::VRSQRTSSm:
4454   case X86::VRSQRTSSm_Int:
4455   case X86::VSQRTSSr:
4456   case X86::VSQRTSSr_Int:
4457   case X86::VSQRTSSm:
4458   case X86::VSQRTSSm_Int:
4459   case X86::VSQRTSDr:
4460   case X86::VSQRTSDr_Int:
4461   case X86::VSQRTSDm:
4462   case X86::VSQRTSDm_Int:
4463   // AVX-512
4464   case X86::VCVTSI2SSZrr:
4465   case X86::VCVTSI2SSZrm:
4466   case X86::VCVTSI2SSZrr_Int:
4467   case X86::VCVTSI2SSZrrb_Int:
4468   case X86::VCVTSI2SSZrm_Int:
4469   case X86::VCVTSI642SSZrr:
4470   case X86::VCVTSI642SSZrm:
4471   case X86::VCVTSI642SSZrr_Int:
4472   case X86::VCVTSI642SSZrrb_Int:
4473   case X86::VCVTSI642SSZrm_Int:
4474   case X86::VCVTSI2SDZrr:
4475   case X86::VCVTSI2SDZrm:
4476   case X86::VCVTSI2SDZrr_Int:
4477   case X86::VCVTSI2SDZrrb_Int:
4478   case X86::VCVTSI2SDZrm_Int:
4479   case X86::VCVTSI642SDZrr:
4480   case X86::VCVTSI642SDZrm:
4481   case X86::VCVTSI642SDZrr_Int:
4482   case X86::VCVTSI642SDZrrb_Int:
4483   case X86::VCVTSI642SDZrm_Int:
4484   case X86::VCVTUSI2SSZrr:
4485   case X86::VCVTUSI2SSZrm:
4486   case X86::VCVTUSI2SSZrr_Int:
4487   case X86::VCVTUSI2SSZrrb_Int:
4488   case X86::VCVTUSI2SSZrm_Int:
4489   case X86::VCVTUSI642SSZrr:
4490   case X86::VCVTUSI642SSZrm:
4491   case X86::VCVTUSI642SSZrr_Int:
4492   case X86::VCVTUSI642SSZrrb_Int:
4493   case X86::VCVTUSI642SSZrm_Int:
4494   case X86::VCVTUSI2SDZrr:
4495   case X86::VCVTUSI2SDZrm:
4496   case X86::VCVTUSI2SDZrr_Int:
4497   case X86::VCVTUSI2SDZrm_Int:
4498   case X86::VCVTUSI642SDZrr:
4499   case X86::VCVTUSI642SDZrm:
4500   case X86::VCVTUSI642SDZrr_Int:
4501   case X86::VCVTUSI642SDZrrb_Int:
4502   case X86::VCVTUSI642SDZrm_Int:
4503   case X86::VCVTSD2SSZrr:
4504   case X86::VCVTSD2SSZrr_Int:
4505   case X86::VCVTSD2SSZrrb_Int:
4506   case X86::VCVTSD2SSZrm:
4507   case X86::VCVTSD2SSZrm_Int:
4508   case X86::VCVTSS2SDZrr:
4509   case X86::VCVTSS2SDZrr_Int:
4510   case X86::VCVTSS2SDZrrb_Int:
4511   case X86::VCVTSS2SDZrm:
4512   case X86::VCVTSS2SDZrm_Int:
4513   case X86::VGETEXPSDZr:
4514   case X86::VGETEXPSDZrb:
4515   case X86::VGETEXPSDZm:
4516   case X86::VGETEXPSSZr:
4517   case X86::VGETEXPSSZrb:
4518   case X86::VGETEXPSSZm:
4519   case X86::VGETMANTSDZrri:
4520   case X86::VGETMANTSDZrrib:
4521   case X86::VGETMANTSDZrmi:
4522   case X86::VGETMANTSSZrri:
4523   case X86::VGETMANTSSZrrib:
4524   case X86::VGETMANTSSZrmi:
4525   case X86::VRNDSCALESDZr:
4526   case X86::VRNDSCALESDZr_Int:
4527   case X86::VRNDSCALESDZrb_Int:
4528   case X86::VRNDSCALESDZm:
4529   case X86::VRNDSCALESDZm_Int:
4530   case X86::VRNDSCALESSZr:
4531   case X86::VRNDSCALESSZr_Int:
4532   case X86::VRNDSCALESSZrb_Int:
4533   case X86::VRNDSCALESSZm:
4534   case X86::VRNDSCALESSZm_Int:
4535   case X86::VRCP14SDZrr:
4536   case X86::VRCP14SDZrm:
4537   case X86::VRCP14SSZrr:
4538   case X86::VRCP14SSZrm:
4539   case X86::VRCP28SDZr:
4540   case X86::VRCP28SDZrb:
4541   case X86::VRCP28SDZm:
4542   case X86::VRCP28SSZr:
4543   case X86::VRCP28SSZrb:
4544   case X86::VRCP28SSZm:
4545   case X86::VREDUCESSZrmi:
4546   case X86::VREDUCESSZrri:
4547   case X86::VREDUCESSZrrib:
4548   case X86::VRSQRT14SDZrr:
4549   case X86::VRSQRT14SDZrm:
4550   case X86::VRSQRT14SSZrr:
4551   case X86::VRSQRT14SSZrm:
4552   case X86::VRSQRT28SDZr:
4553   case X86::VRSQRT28SDZrb:
4554   case X86::VRSQRT28SDZm:
4555   case X86::VRSQRT28SSZr:
4556   case X86::VRSQRT28SSZrb:
4557   case X86::VRSQRT28SSZm:
4558   case X86::VSQRTSSZr:
4559   case X86::VSQRTSSZr_Int:
4560   case X86::VSQRTSSZrb_Int:
4561   case X86::VSQRTSSZm:
4562   case X86::VSQRTSSZm_Int:
4563   case X86::VSQRTSDZr:
4564   case X86::VSQRTSDZr_Int:
4565   case X86::VSQRTSDZrb_Int:
4566   case X86::VSQRTSDZm:
4567   case X86::VSQRTSDZm_Int:
4568     return true;
4569   }
4570 
4571   return false;
4572 }
4573 
4574 /// Inform the BreakFalseDeps pass how many idle instructions we would like
4575 /// before certain undef register reads.
4576 ///
4577 /// This catches the VCVTSI2SD family of instructions:
4578 ///
4579 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
4580 ///
4581 /// We should to be careful *not* to catch VXOR idioms which are presumably
4582 /// handled specially in the pipeline:
4583 ///
4584 /// vxorps undef %xmm1, undef %xmm1, %xmm1
4585 ///
4586 /// Like getPartialRegUpdateClearance, this makes a strong assumption that the
4587 /// high bits that are passed-through are not live.
4588 unsigned
4589 X86InstrInfo::getUndefRegClearance(const MachineInstr &MI, unsigned &OpNum,
4590                                    const TargetRegisterInfo *TRI) const {
4591   if (!hasUndefRegUpdate(MI.getOpcode()))
4592     return 0;
4593 
4594   // Set the OpNum parameter to the first source operand.
4595   OpNum = 1;
4596 
4597   const MachineOperand &MO = MI.getOperand(OpNum);
4598   if (MO.isUndef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
4599     return UndefRegClearance;
4600   }
4601   return 0;
4602 }
4603 
4604 void X86InstrInfo::breakPartialRegDependency(
4605     MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
4606   unsigned Reg = MI.getOperand(OpNum).getReg();
4607   // If MI kills this register, the false dependence is already broken.
4608   if (MI.killsRegister(Reg, TRI))
4609     return;
4610 
4611   if (X86::VR128RegClass.contains(Reg)) {
4612     // These instructions are all floating point domain, so xorps is the best
4613     // choice.
4614     unsigned Opc = Subtarget.hasAVX() ? X86::VXORPSrr : X86::XORPSrr;
4615     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(Opc), Reg)
4616         .addReg(Reg, RegState::Undef)
4617         .addReg(Reg, RegState::Undef);
4618     MI.addRegisterKilled(Reg, TRI, true);
4619   } else if (X86::VR256RegClass.contains(Reg)) {
4620     // Use vxorps to clear the full ymm register.
4621     // It wants to read and write the xmm sub-register.
4622     unsigned XReg = TRI->getSubReg(Reg, X86::sub_xmm);
4623     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::VXORPSrr), XReg)
4624         .addReg(XReg, RegState::Undef)
4625         .addReg(XReg, RegState::Undef)
4626         .addReg(Reg, RegState::ImplicitDefine);
4627     MI.addRegisterKilled(Reg, TRI, true);
4628   } else if (X86::GR64RegClass.contains(Reg)) {
4629     // Using XOR32rr because it has shorter encoding and zeros up the upper bits
4630     // as well.
4631     unsigned XReg = TRI->getSubReg(Reg, X86::sub_32bit);
4632     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), XReg)
4633         .addReg(XReg, RegState::Undef)
4634         .addReg(XReg, RegState::Undef)
4635         .addReg(Reg, RegState::ImplicitDefine);
4636     MI.addRegisterKilled(Reg, TRI, true);
4637   } else if (X86::GR32RegClass.contains(Reg)) {
4638     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), Reg)
4639         .addReg(Reg, RegState::Undef)
4640         .addReg(Reg, RegState::Undef);
4641     MI.addRegisterKilled(Reg, TRI, true);
4642   }
4643 }
4644 
4645 static void addOperands(MachineInstrBuilder &MIB, ArrayRef<MachineOperand> MOs,
4646                         int PtrOffset = 0) {
4647   unsigned NumAddrOps = MOs.size();
4648 
4649   if (NumAddrOps < 4) {
4650     // FrameIndex only - add an immediate offset (whether its zero or not).
4651     for (unsigned i = 0; i != NumAddrOps; ++i)
4652       MIB.add(MOs[i]);
4653     addOffset(MIB, PtrOffset);
4654   } else {
4655     // General Memory Addressing - we need to add any offset to an existing
4656     // offset.
4657     assert(MOs.size() == 5 && "Unexpected memory operand list length");
4658     for (unsigned i = 0; i != NumAddrOps; ++i) {
4659       const MachineOperand &MO = MOs[i];
4660       if (i == 3 && PtrOffset != 0) {
4661         MIB.addDisp(MO, PtrOffset);
4662       } else {
4663         MIB.add(MO);
4664       }
4665     }
4666   }
4667 }
4668 
4669 static void updateOperandRegConstraints(MachineFunction &MF,
4670                                         MachineInstr &NewMI,
4671                                         const TargetInstrInfo &TII) {
4672   MachineRegisterInfo &MRI = MF.getRegInfo();
4673   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
4674 
4675   for (int Idx : llvm::seq<int>(0, NewMI.getNumOperands())) {
4676     MachineOperand &MO = NewMI.getOperand(Idx);
4677     // We only need to update constraints on virtual register operands.
4678     if (!MO.isReg())
4679       continue;
4680     unsigned Reg = MO.getReg();
4681     if (!TRI.isVirtualRegister(Reg))
4682       continue;
4683 
4684     auto *NewRC = MRI.constrainRegClass(
4685         Reg, TII.getRegClass(NewMI.getDesc(), Idx, &TRI, MF));
4686     if (!NewRC) {
4687       LLVM_DEBUG(
4688           dbgs() << "WARNING: Unable to update register constraint for operand "
4689                  << Idx << " of instruction:\n";
4690           NewMI.dump(); dbgs() << "\n");
4691     }
4692   }
4693 }
4694 
4695 static MachineInstr *FuseTwoAddrInst(MachineFunction &MF, unsigned Opcode,
4696                                      ArrayRef<MachineOperand> MOs,
4697                                      MachineBasicBlock::iterator InsertPt,
4698                                      MachineInstr &MI,
4699                                      const TargetInstrInfo &TII) {
4700   // Create the base instruction with the memory operand as the first part.
4701   // Omit the implicit operands, something BuildMI can't do.
4702   MachineInstr *NewMI =
4703       MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
4704   MachineInstrBuilder MIB(MF, NewMI);
4705   addOperands(MIB, MOs);
4706 
4707   // Loop over the rest of the ri operands, converting them over.
4708   unsigned NumOps = MI.getDesc().getNumOperands() - 2;
4709   for (unsigned i = 0; i != NumOps; ++i) {
4710     MachineOperand &MO = MI.getOperand(i + 2);
4711     MIB.add(MO);
4712   }
4713   for (unsigned i = NumOps + 2, e = MI.getNumOperands(); i != e; ++i) {
4714     MachineOperand &MO = MI.getOperand(i);
4715     MIB.add(MO);
4716   }
4717 
4718   updateOperandRegConstraints(MF, *NewMI, TII);
4719 
4720   MachineBasicBlock *MBB = InsertPt->getParent();
4721   MBB->insert(InsertPt, NewMI);
4722 
4723   return MIB;
4724 }
4725 
4726 static MachineInstr *FuseInst(MachineFunction &MF, unsigned Opcode,
4727                               unsigned OpNo, ArrayRef<MachineOperand> MOs,
4728                               MachineBasicBlock::iterator InsertPt,
4729                               MachineInstr &MI, const TargetInstrInfo &TII,
4730                               int PtrOffset = 0) {
4731   // Omit the implicit operands, something BuildMI can't do.
4732   MachineInstr *NewMI =
4733       MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
4734   MachineInstrBuilder MIB(MF, NewMI);
4735 
4736   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4737     MachineOperand &MO = MI.getOperand(i);
4738     if (i == OpNo) {
4739       assert(MO.isReg() && "Expected to fold into reg operand!");
4740       addOperands(MIB, MOs, PtrOffset);
4741     } else {
4742       MIB.add(MO);
4743     }
4744   }
4745 
4746   updateOperandRegConstraints(MF, *NewMI, TII);
4747 
4748   MachineBasicBlock *MBB = InsertPt->getParent();
4749   MBB->insert(InsertPt, NewMI);
4750 
4751   return MIB;
4752 }
4753 
4754 static MachineInstr *MakeM0Inst(const TargetInstrInfo &TII, unsigned Opcode,
4755                                 ArrayRef<MachineOperand> MOs,
4756                                 MachineBasicBlock::iterator InsertPt,
4757                                 MachineInstr &MI) {
4758   MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
4759                                     MI.getDebugLoc(), TII.get(Opcode));
4760   addOperands(MIB, MOs);
4761   return MIB.addImm(0);
4762 }
4763 
4764 MachineInstr *X86InstrInfo::foldMemoryOperandCustom(
4765     MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
4766     ArrayRef<MachineOperand> MOs, MachineBasicBlock::iterator InsertPt,
4767     unsigned Size, unsigned Align) const {
4768   switch (MI.getOpcode()) {
4769   case X86::INSERTPSrr:
4770   case X86::VINSERTPSrr:
4771   case X86::VINSERTPSZrr:
4772     // Attempt to convert the load of inserted vector into a fold load
4773     // of a single float.
4774     if (OpNum == 2) {
4775       unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm();
4776       unsigned ZMask = Imm & 15;
4777       unsigned DstIdx = (Imm >> 4) & 3;
4778       unsigned SrcIdx = (Imm >> 6) & 3;
4779 
4780       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
4781       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4782       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4783       if (Size <= RCSize && 4 <= Align) {
4784         int PtrOffset = SrcIdx * 4;
4785         unsigned NewImm = (DstIdx << 4) | ZMask;
4786         unsigned NewOpCode =
4787             (MI.getOpcode() == X86::VINSERTPSZrr) ? X86::VINSERTPSZrm :
4788             (MI.getOpcode() == X86::VINSERTPSrr)  ? X86::VINSERTPSrm  :
4789                                                     X86::INSERTPSrm;
4790         MachineInstr *NewMI =
4791             FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, PtrOffset);
4792         NewMI->getOperand(NewMI->getNumOperands() - 1).setImm(NewImm);
4793         return NewMI;
4794       }
4795     }
4796     break;
4797   case X86::MOVHLPSrr:
4798   case X86::VMOVHLPSrr:
4799   case X86::VMOVHLPSZrr:
4800     // Move the upper 64-bits of the second operand to the lower 64-bits.
4801     // To fold the load, adjust the pointer to the upper and use (V)MOVLPS.
4802     // TODO: In most cases AVX doesn't have a 8-byte alignment requirement.
4803     if (OpNum == 2) {
4804       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
4805       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4806       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4807       if (Size <= RCSize && 8 <= Align) {
4808         unsigned NewOpCode =
4809             (MI.getOpcode() == X86::VMOVHLPSZrr) ? X86::VMOVLPSZ128rm :
4810             (MI.getOpcode() == X86::VMOVHLPSrr)  ? X86::VMOVLPSrm     :
4811                                                    X86::MOVLPSrm;
4812         MachineInstr *NewMI =
4813             FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, 8);
4814         return NewMI;
4815       }
4816     }
4817     break;
4818   };
4819 
4820   return nullptr;
4821 }
4822 
4823 static bool shouldPreventUndefRegUpdateMemFold(MachineFunction &MF, MachineInstr &MI) {
4824   if (MF.getFunction().optForSize() || !hasUndefRegUpdate(MI.getOpcode()) ||
4825       !MI.getOperand(1).isReg())
4826     return false;
4827 
4828   // The are two cases we need to handle depending on where in the pipeline
4829   // the folding attempt is being made.
4830   // -Register has the undef flag set.
4831   // -Register is produced by the IMPLICIT_DEF instruction.
4832 
4833   if (MI.getOperand(1).isUndef())
4834     return true;
4835 
4836   MachineRegisterInfo &RegInfo = MF.getRegInfo();
4837   MachineInstr *VRegDef = RegInfo.getUniqueVRegDef(MI.getOperand(1).getReg());
4838   return VRegDef && VRegDef->isImplicitDef();
4839 }
4840 
4841 
4842 MachineInstr *X86InstrInfo::foldMemoryOperandImpl(
4843     MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
4844     ArrayRef<MachineOperand> MOs, MachineBasicBlock::iterator InsertPt,
4845     unsigned Size, unsigned Align, bool AllowCommute) const {
4846   bool isSlowTwoMemOps = Subtarget.slowTwoMemOps();
4847   bool isTwoAddrFold = false;
4848 
4849   // For CPUs that favor the register form of a call or push,
4850   // do not fold loads into calls or pushes, unless optimizing for size
4851   // aggressively.
4852   if (isSlowTwoMemOps && !MF.getFunction().optForMinSize() &&
4853       (MI.getOpcode() == X86::CALL32r || MI.getOpcode() == X86::CALL64r ||
4854        MI.getOpcode() == X86::PUSH16r || MI.getOpcode() == X86::PUSH32r ||
4855        MI.getOpcode() == X86::PUSH64r))
4856     return nullptr;
4857 
4858   // Avoid partial and undef register update stalls unless optimizing for size.
4859   if (!MF.getFunction().optForSize() &&
4860       (hasPartialRegUpdate(MI.getOpcode(), Subtarget) ||
4861        shouldPreventUndefRegUpdateMemFold(MF, MI)))
4862     return nullptr;
4863 
4864   unsigned NumOps = MI.getDesc().getNumOperands();
4865   bool isTwoAddr =
4866       NumOps > 1 && MI.getDesc().getOperandConstraint(1, MCOI::TIED_TO) != -1;
4867 
4868   // FIXME: AsmPrinter doesn't know how to handle
4869   // X86II::MO_GOT_ABSOLUTE_ADDRESS after folding.
4870   if (MI.getOpcode() == X86::ADD32ri &&
4871       MI.getOperand(2).getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS)
4872     return nullptr;
4873 
4874   // GOTTPOFF relocation loads can only be folded into add instructions.
4875   // FIXME: Need to exclude other relocations that only support specific
4876   // instructions.
4877   if (MOs.size() == X86::AddrNumOperands &&
4878       MOs[X86::AddrDisp].getTargetFlags() == X86II::MO_GOTTPOFF &&
4879       MI.getOpcode() != X86::ADD64rr)
4880     return nullptr;
4881 
4882   MachineInstr *NewMI = nullptr;
4883 
4884   // Attempt to fold any custom cases we have.
4885   if (MachineInstr *CustomMI =
4886           foldMemoryOperandCustom(MF, MI, OpNum, MOs, InsertPt, Size, Align))
4887     return CustomMI;
4888 
4889   const X86MemoryFoldTableEntry *I = nullptr;
4890 
4891   // Folding a memory location into the two-address part of a two-address
4892   // instruction is different than folding it other places.  It requires
4893   // replacing the *two* registers with the memory location.
4894   if (isTwoAddr && NumOps >= 2 && OpNum < 2 && MI.getOperand(0).isReg() &&
4895       MI.getOperand(1).isReg() &&
4896       MI.getOperand(0).getReg() == MI.getOperand(1).getReg()) {
4897     I = lookupTwoAddrFoldTable(MI.getOpcode());
4898     isTwoAddrFold = true;
4899   } else {
4900     if (OpNum == 0) {
4901       if (MI.getOpcode() == X86::MOV32r0) {
4902         NewMI = MakeM0Inst(*this, X86::MOV32mi, MOs, InsertPt, MI);
4903         if (NewMI)
4904           return NewMI;
4905       }
4906     }
4907 
4908     I = lookupFoldTable(MI.getOpcode(), OpNum);
4909   }
4910 
4911   if (I != nullptr) {
4912     unsigned Opcode = I->DstOp;
4913     unsigned MinAlign = (I->Flags & TB_ALIGN_MASK) >> TB_ALIGN_SHIFT;
4914     if (Align < MinAlign)
4915       return nullptr;
4916     bool NarrowToMOV32rm = false;
4917     if (Size) {
4918       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
4919       const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum,
4920                                                   &RI, MF);
4921       unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4922       if (Size < RCSize) {
4923         // Check if it's safe to fold the load. If the size of the object is
4924         // narrower than the load width, then it's not.
4925         if (Opcode != X86::MOV64rm || RCSize != 8 || Size != 4)
4926           return nullptr;
4927         // If this is a 64-bit load, but the spill slot is 32, then we can do
4928         // a 32-bit load which is implicitly zero-extended. This likely is
4929         // due to live interval analysis remat'ing a load from stack slot.
4930         if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
4931           return nullptr;
4932         Opcode = X86::MOV32rm;
4933         NarrowToMOV32rm = true;
4934       }
4935     }
4936 
4937     if (isTwoAddrFold)
4938       NewMI = FuseTwoAddrInst(MF, Opcode, MOs, InsertPt, MI, *this);
4939     else
4940       NewMI = FuseInst(MF, Opcode, OpNum, MOs, InsertPt, MI, *this);
4941 
4942     if (NarrowToMOV32rm) {
4943       // If this is the special case where we use a MOV32rm to load a 32-bit
4944       // value and zero-extend the top bits. Change the destination register
4945       // to a 32-bit one.
4946       unsigned DstReg = NewMI->getOperand(0).getReg();
4947       if (TargetRegisterInfo::isPhysicalRegister(DstReg))
4948         NewMI->getOperand(0).setReg(RI.getSubReg(DstReg, X86::sub_32bit));
4949       else
4950         NewMI->getOperand(0).setSubReg(X86::sub_32bit);
4951     }
4952     return NewMI;
4953   }
4954 
4955   // If the instruction and target operand are commutable, commute the
4956   // instruction and try again.
4957   if (AllowCommute) {
4958     unsigned CommuteOpIdx1 = OpNum, CommuteOpIdx2 = CommuteAnyOperandIndex;
4959     if (findCommutedOpIndices(MI, CommuteOpIdx1, CommuteOpIdx2)) {
4960       bool HasDef = MI.getDesc().getNumDefs();
4961       unsigned Reg0 = HasDef ? MI.getOperand(0).getReg() : 0;
4962       unsigned Reg1 = MI.getOperand(CommuteOpIdx1).getReg();
4963       unsigned Reg2 = MI.getOperand(CommuteOpIdx2).getReg();
4964       bool Tied1 =
4965           0 == MI.getDesc().getOperandConstraint(CommuteOpIdx1, MCOI::TIED_TO);
4966       bool Tied2 =
4967           0 == MI.getDesc().getOperandConstraint(CommuteOpIdx2, MCOI::TIED_TO);
4968 
4969       // If either of the commutable operands are tied to the destination
4970       // then we can not commute + fold.
4971       if ((HasDef && Reg0 == Reg1 && Tied1) ||
4972           (HasDef && Reg0 == Reg2 && Tied2))
4973         return nullptr;
4974 
4975       MachineInstr *CommutedMI =
4976           commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
4977       if (!CommutedMI) {
4978         // Unable to commute.
4979         return nullptr;
4980       }
4981       if (CommutedMI != &MI) {
4982         // New instruction. We can't fold from this.
4983         CommutedMI->eraseFromParent();
4984         return nullptr;
4985       }
4986 
4987       // Attempt to fold with the commuted version of the instruction.
4988       NewMI = foldMemoryOperandImpl(MF, MI, CommuteOpIdx2, MOs, InsertPt,
4989                                     Size, Align, /*AllowCommute=*/false);
4990       if (NewMI)
4991         return NewMI;
4992 
4993       // Folding failed again - undo the commute before returning.
4994       MachineInstr *UncommutedMI =
4995           commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
4996       if (!UncommutedMI) {
4997         // Unable to commute.
4998         return nullptr;
4999       }
5000       if (UncommutedMI != &MI) {
5001         // New instruction. It doesn't need to be kept.
5002         UncommutedMI->eraseFromParent();
5003         return nullptr;
5004       }
5005 
5006       // Return here to prevent duplicate fuse failure report.
5007       return nullptr;
5008     }
5009   }
5010 
5011   // No fusion
5012   if (PrintFailedFusing && !MI.isCopy())
5013     dbgs() << "We failed to fuse operand " << OpNum << " in " << MI;
5014   return nullptr;
5015 }
5016 
5017 MachineInstr *
5018 X86InstrInfo::foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
5019                                     ArrayRef<unsigned> Ops,
5020                                     MachineBasicBlock::iterator InsertPt,
5021                                     int FrameIndex, LiveIntervals *LIS) const {
5022   // Check switch flag
5023   if (NoFusing)
5024     return nullptr;
5025 
5026   // Avoid partial and undef register update stalls unless optimizing for size.
5027   if (!MF.getFunction().optForSize() &&
5028       (hasPartialRegUpdate(MI.getOpcode(), Subtarget) ||
5029        shouldPreventUndefRegUpdateMemFold(MF, MI)))
5030     return nullptr;
5031 
5032   // Don't fold subreg spills, or reloads that use a high subreg.
5033   for (auto Op : Ops) {
5034     MachineOperand &MO = MI.getOperand(Op);
5035     auto SubReg = MO.getSubReg();
5036     if (SubReg && (MO.isDef() || SubReg == X86::sub_8bit_hi))
5037       return nullptr;
5038   }
5039 
5040   const MachineFrameInfo &MFI = MF.getFrameInfo();
5041   unsigned Size = MFI.getObjectSize(FrameIndex);
5042   unsigned Alignment = MFI.getObjectAlignment(FrameIndex);
5043   // If the function stack isn't realigned we don't want to fold instructions
5044   // that need increased alignment.
5045   if (!RI.needsStackRealignment(MF))
5046     Alignment =
5047         std::min(Alignment, Subtarget.getFrameLowering()->getStackAlignment());
5048   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
5049     unsigned NewOpc = 0;
5050     unsigned RCSize = 0;
5051     switch (MI.getOpcode()) {
5052     default: return nullptr;
5053     case X86::TEST8rr:  NewOpc = X86::CMP8ri; RCSize = 1; break;
5054     case X86::TEST16rr: NewOpc = X86::CMP16ri8; RCSize = 2; break;
5055     case X86::TEST32rr: NewOpc = X86::CMP32ri8; RCSize = 4; break;
5056     case X86::TEST64rr: NewOpc = X86::CMP64ri8; RCSize = 8; break;
5057     }
5058     // Check if it's safe to fold the load. If the size of the object is
5059     // narrower than the load width, then it's not.
5060     if (Size < RCSize)
5061       return nullptr;
5062     // Change to CMPXXri r, 0 first.
5063     MI.setDesc(get(NewOpc));
5064     MI.getOperand(1).ChangeToImmediate(0);
5065   } else if (Ops.size() != 1)
5066     return nullptr;
5067 
5068   return foldMemoryOperandImpl(MF, MI, Ops[0],
5069                                MachineOperand::CreateFI(FrameIndex), InsertPt,
5070                                Size, Alignment, /*AllowCommute=*/true);
5071 }
5072 
5073 /// Check if \p LoadMI is a partial register load that we can't fold into \p MI
5074 /// because the latter uses contents that wouldn't be defined in the folded
5075 /// version.  For instance, this transformation isn't legal:
5076 ///   movss (%rdi), %xmm0
5077 ///   addps %xmm0, %xmm0
5078 /// ->
5079 ///   addps (%rdi), %xmm0
5080 ///
5081 /// But this one is:
5082 ///   movss (%rdi), %xmm0
5083 ///   addss %xmm0, %xmm0
5084 /// ->
5085 ///   addss (%rdi), %xmm0
5086 ///
5087 static bool isNonFoldablePartialRegisterLoad(const MachineInstr &LoadMI,
5088                                              const MachineInstr &UserMI,
5089                                              const MachineFunction &MF) {
5090   unsigned Opc = LoadMI.getOpcode();
5091   unsigned UserOpc = UserMI.getOpcode();
5092   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
5093   const TargetRegisterClass *RC =
5094       MF.getRegInfo().getRegClass(LoadMI.getOperand(0).getReg());
5095   unsigned RegSize = TRI.getRegSizeInBits(*RC);
5096 
5097   if ((Opc == X86::MOVSSrm || Opc == X86::VMOVSSrm || Opc == X86::VMOVSSZrm) &&
5098       RegSize > 32) {
5099     // These instructions only load 32 bits, we can't fold them if the
5100     // destination register is wider than 32 bits (4 bytes), and its user
5101     // instruction isn't scalar (SS).
5102     switch (UserOpc) {
5103     case X86::ADDSSrr_Int: case X86::VADDSSrr_Int: case X86::VADDSSZrr_Int:
5104     case X86::CMPSSrr_Int: case X86::VCMPSSrr_Int: case X86::VCMPSSZrr_Int:
5105     case X86::DIVSSrr_Int: case X86::VDIVSSrr_Int: case X86::VDIVSSZrr_Int:
5106     case X86::MAXSSrr_Int: case X86::VMAXSSrr_Int: case X86::VMAXSSZrr_Int:
5107     case X86::MINSSrr_Int: case X86::VMINSSrr_Int: case X86::VMINSSZrr_Int:
5108     case X86::MULSSrr_Int: case X86::VMULSSrr_Int: case X86::VMULSSZrr_Int:
5109     case X86::SUBSSrr_Int: case X86::VSUBSSrr_Int: case X86::VSUBSSZrr_Int:
5110     case X86::VADDSSZrr_Intk: case X86::VADDSSZrr_Intkz:
5111     case X86::VDIVSSZrr_Intk: case X86::VDIVSSZrr_Intkz:
5112     case X86::VMAXSSZrr_Intk: case X86::VMAXSSZrr_Intkz:
5113     case X86::VMINSSZrr_Intk: case X86::VMINSSZrr_Intkz:
5114     case X86::VMULSSZrr_Intk: case X86::VMULSSZrr_Intkz:
5115     case X86::VSUBSSZrr_Intk: case X86::VSUBSSZrr_Intkz:
5116     case X86::VFMADDSS4rr_Int:   case X86::VFNMADDSS4rr_Int:
5117     case X86::VFMSUBSS4rr_Int:   case X86::VFNMSUBSS4rr_Int:
5118     case X86::VFMADD132SSr_Int:  case X86::VFNMADD132SSr_Int:
5119     case X86::VFMADD213SSr_Int:  case X86::VFNMADD213SSr_Int:
5120     case X86::VFMADD231SSr_Int:  case X86::VFNMADD231SSr_Int:
5121     case X86::VFMSUB132SSr_Int:  case X86::VFNMSUB132SSr_Int:
5122     case X86::VFMSUB213SSr_Int:  case X86::VFNMSUB213SSr_Int:
5123     case X86::VFMSUB231SSr_Int:  case X86::VFNMSUB231SSr_Int:
5124     case X86::VFMADD132SSZr_Int: case X86::VFNMADD132SSZr_Int:
5125     case X86::VFMADD213SSZr_Int: case X86::VFNMADD213SSZr_Int:
5126     case X86::VFMADD231SSZr_Int: case X86::VFNMADD231SSZr_Int:
5127     case X86::VFMSUB132SSZr_Int: case X86::VFNMSUB132SSZr_Int:
5128     case X86::VFMSUB213SSZr_Int: case X86::VFNMSUB213SSZr_Int:
5129     case X86::VFMSUB231SSZr_Int: case X86::VFNMSUB231SSZr_Int:
5130     case X86::VFMADD132SSZr_Intk: case X86::VFNMADD132SSZr_Intk:
5131     case X86::VFMADD213SSZr_Intk: case X86::VFNMADD213SSZr_Intk:
5132     case X86::VFMADD231SSZr_Intk: case X86::VFNMADD231SSZr_Intk:
5133     case X86::VFMSUB132SSZr_Intk: case X86::VFNMSUB132SSZr_Intk:
5134     case X86::VFMSUB213SSZr_Intk: case X86::VFNMSUB213SSZr_Intk:
5135     case X86::VFMSUB231SSZr_Intk: case X86::VFNMSUB231SSZr_Intk:
5136     case X86::VFMADD132SSZr_Intkz: case X86::VFNMADD132SSZr_Intkz:
5137     case X86::VFMADD213SSZr_Intkz: case X86::VFNMADD213SSZr_Intkz:
5138     case X86::VFMADD231SSZr_Intkz: case X86::VFNMADD231SSZr_Intkz:
5139     case X86::VFMSUB132SSZr_Intkz: case X86::VFNMSUB132SSZr_Intkz:
5140     case X86::VFMSUB213SSZr_Intkz: case X86::VFNMSUB213SSZr_Intkz:
5141     case X86::VFMSUB231SSZr_Intkz: case X86::VFNMSUB231SSZr_Intkz:
5142       return false;
5143     default:
5144       return true;
5145     }
5146   }
5147 
5148   if ((Opc == X86::MOVSDrm || Opc == X86::VMOVSDrm || Opc == X86::VMOVSDZrm) &&
5149       RegSize > 64) {
5150     // These instructions only load 64 bits, we can't fold them if the
5151     // destination register is wider than 64 bits (8 bytes), and its user
5152     // instruction isn't scalar (SD).
5153     switch (UserOpc) {
5154     case X86::ADDSDrr_Int: case X86::VADDSDrr_Int: case X86::VADDSDZrr_Int:
5155     case X86::CMPSDrr_Int: case X86::VCMPSDrr_Int: case X86::VCMPSDZrr_Int:
5156     case X86::DIVSDrr_Int: case X86::VDIVSDrr_Int: case X86::VDIVSDZrr_Int:
5157     case X86::MAXSDrr_Int: case X86::VMAXSDrr_Int: case X86::VMAXSDZrr_Int:
5158     case X86::MINSDrr_Int: case X86::VMINSDrr_Int: case X86::VMINSDZrr_Int:
5159     case X86::MULSDrr_Int: case X86::VMULSDrr_Int: case X86::VMULSDZrr_Int:
5160     case X86::SUBSDrr_Int: case X86::VSUBSDrr_Int: case X86::VSUBSDZrr_Int:
5161     case X86::VADDSDZrr_Intk: case X86::VADDSDZrr_Intkz:
5162     case X86::VDIVSDZrr_Intk: case X86::VDIVSDZrr_Intkz:
5163     case X86::VMAXSDZrr_Intk: case X86::VMAXSDZrr_Intkz:
5164     case X86::VMINSDZrr_Intk: case X86::VMINSDZrr_Intkz:
5165     case X86::VMULSDZrr_Intk: case X86::VMULSDZrr_Intkz:
5166     case X86::VSUBSDZrr_Intk: case X86::VSUBSDZrr_Intkz:
5167     case X86::VFMADDSD4rr_Int:   case X86::VFNMADDSD4rr_Int:
5168     case X86::VFMSUBSD4rr_Int:   case X86::VFNMSUBSD4rr_Int:
5169     case X86::VFMADD132SDr_Int:  case X86::VFNMADD132SDr_Int:
5170     case X86::VFMADD213SDr_Int:  case X86::VFNMADD213SDr_Int:
5171     case X86::VFMADD231SDr_Int:  case X86::VFNMADD231SDr_Int:
5172     case X86::VFMSUB132SDr_Int:  case X86::VFNMSUB132SDr_Int:
5173     case X86::VFMSUB213SDr_Int:  case X86::VFNMSUB213SDr_Int:
5174     case X86::VFMSUB231SDr_Int:  case X86::VFNMSUB231SDr_Int:
5175     case X86::VFMADD132SDZr_Int: case X86::VFNMADD132SDZr_Int:
5176     case X86::VFMADD213SDZr_Int: case X86::VFNMADD213SDZr_Int:
5177     case X86::VFMADD231SDZr_Int: case X86::VFNMADD231SDZr_Int:
5178     case X86::VFMSUB132SDZr_Int: case X86::VFNMSUB132SDZr_Int:
5179     case X86::VFMSUB213SDZr_Int: case X86::VFNMSUB213SDZr_Int:
5180     case X86::VFMSUB231SDZr_Int: case X86::VFNMSUB231SDZr_Int:
5181     case X86::VFMADD132SDZr_Intk: case X86::VFNMADD132SDZr_Intk:
5182     case X86::VFMADD213SDZr_Intk: case X86::VFNMADD213SDZr_Intk:
5183     case X86::VFMADD231SDZr_Intk: case X86::VFNMADD231SDZr_Intk:
5184     case X86::VFMSUB132SDZr_Intk: case X86::VFNMSUB132SDZr_Intk:
5185     case X86::VFMSUB213SDZr_Intk: case X86::VFNMSUB213SDZr_Intk:
5186     case X86::VFMSUB231SDZr_Intk: case X86::VFNMSUB231SDZr_Intk:
5187     case X86::VFMADD132SDZr_Intkz: case X86::VFNMADD132SDZr_Intkz:
5188     case X86::VFMADD213SDZr_Intkz: case X86::VFNMADD213SDZr_Intkz:
5189     case X86::VFMADD231SDZr_Intkz: case X86::VFNMADD231SDZr_Intkz:
5190     case X86::VFMSUB132SDZr_Intkz: case X86::VFNMSUB132SDZr_Intkz:
5191     case X86::VFMSUB213SDZr_Intkz: case X86::VFNMSUB213SDZr_Intkz:
5192     case X86::VFMSUB231SDZr_Intkz: case X86::VFNMSUB231SDZr_Intkz:
5193       return false;
5194     default:
5195       return true;
5196     }
5197   }
5198 
5199   return false;
5200 }
5201 
5202 MachineInstr *X86InstrInfo::foldMemoryOperandImpl(
5203     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
5204     MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
5205     LiveIntervals *LIS) const {
5206 
5207   // TODO: Support the case where LoadMI loads a wide register, but MI
5208   // only uses a subreg.
5209   for (auto Op : Ops) {
5210     if (MI.getOperand(Op).getSubReg())
5211       return nullptr;
5212   }
5213 
5214   // If loading from a FrameIndex, fold directly from the FrameIndex.
5215   unsigned NumOps = LoadMI.getDesc().getNumOperands();
5216   int FrameIndex;
5217   if (isLoadFromStackSlot(LoadMI, FrameIndex)) {
5218     if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
5219       return nullptr;
5220     return foldMemoryOperandImpl(MF, MI, Ops, InsertPt, FrameIndex, LIS);
5221   }
5222 
5223   // Check switch flag
5224   if (NoFusing) return nullptr;
5225 
5226   // Avoid partial and undef register update stalls unless optimizing for size.
5227   if (!MF.getFunction().optForSize() &&
5228       (hasPartialRegUpdate(MI.getOpcode(), Subtarget) ||
5229        shouldPreventUndefRegUpdateMemFold(MF, MI)))
5230     return nullptr;
5231 
5232   // Determine the alignment of the load.
5233   unsigned Alignment = 0;
5234   if (LoadMI.hasOneMemOperand())
5235     Alignment = (*LoadMI.memoperands_begin())->getAlignment();
5236   else
5237     switch (LoadMI.getOpcode()) {
5238     case X86::AVX512_512_SET0:
5239     case X86::AVX512_512_SETALLONES:
5240       Alignment = 64;
5241       break;
5242     case X86::AVX2_SETALLONES:
5243     case X86::AVX1_SETALLONES:
5244     case X86::AVX_SET0:
5245     case X86::AVX512_256_SET0:
5246       Alignment = 32;
5247       break;
5248     case X86::V_SET0:
5249     case X86::V_SETALLONES:
5250     case X86::AVX512_128_SET0:
5251       Alignment = 16;
5252       break;
5253     case X86::MMX_SET0:
5254     case X86::FsFLD0SD:
5255     case X86::AVX512_FsFLD0SD:
5256       Alignment = 8;
5257       break;
5258     case X86::FsFLD0SS:
5259     case X86::AVX512_FsFLD0SS:
5260       Alignment = 4;
5261       break;
5262     default:
5263       return nullptr;
5264     }
5265   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
5266     unsigned NewOpc = 0;
5267     switch (MI.getOpcode()) {
5268     default: return nullptr;
5269     case X86::TEST8rr:  NewOpc = X86::CMP8ri; break;
5270     case X86::TEST16rr: NewOpc = X86::CMP16ri8; break;
5271     case X86::TEST32rr: NewOpc = X86::CMP32ri8; break;
5272     case X86::TEST64rr: NewOpc = X86::CMP64ri8; break;
5273     }
5274     // Change to CMPXXri r, 0 first.
5275     MI.setDesc(get(NewOpc));
5276     MI.getOperand(1).ChangeToImmediate(0);
5277   } else if (Ops.size() != 1)
5278     return nullptr;
5279 
5280   // Make sure the subregisters match.
5281   // Otherwise we risk changing the size of the load.
5282   if (LoadMI.getOperand(0).getSubReg() != MI.getOperand(Ops[0]).getSubReg())
5283     return nullptr;
5284 
5285   SmallVector<MachineOperand,X86::AddrNumOperands> MOs;
5286   switch (LoadMI.getOpcode()) {
5287   case X86::MMX_SET0:
5288   case X86::V_SET0:
5289   case X86::V_SETALLONES:
5290   case X86::AVX2_SETALLONES:
5291   case X86::AVX1_SETALLONES:
5292   case X86::AVX_SET0:
5293   case X86::AVX512_128_SET0:
5294   case X86::AVX512_256_SET0:
5295   case X86::AVX512_512_SET0:
5296   case X86::AVX512_512_SETALLONES:
5297   case X86::FsFLD0SD:
5298   case X86::AVX512_FsFLD0SD:
5299   case X86::FsFLD0SS:
5300   case X86::AVX512_FsFLD0SS: {
5301     // Folding a V_SET0 or V_SETALLONES as a load, to ease register pressure.
5302     // Create a constant-pool entry and operands to load from it.
5303 
5304     // Medium and large mode can't fold loads this way.
5305     if (MF.getTarget().getCodeModel() != CodeModel::Small &&
5306         MF.getTarget().getCodeModel() != CodeModel::Kernel)
5307       return nullptr;
5308 
5309     // x86-32 PIC requires a PIC base register for constant pools.
5310     unsigned PICBase = 0;
5311     if (MF.getTarget().isPositionIndependent()) {
5312       if (Subtarget.is64Bit())
5313         PICBase = X86::RIP;
5314       else
5315         // FIXME: PICBase = getGlobalBaseReg(&MF);
5316         // This doesn't work for several reasons.
5317         // 1. GlobalBaseReg may have been spilled.
5318         // 2. It may not be live at MI.
5319         return nullptr;
5320     }
5321 
5322     // Create a constant-pool entry.
5323     MachineConstantPool &MCP = *MF.getConstantPool();
5324     Type *Ty;
5325     unsigned Opc = LoadMI.getOpcode();
5326     if (Opc == X86::FsFLD0SS || Opc == X86::AVX512_FsFLD0SS)
5327       Ty = Type::getFloatTy(MF.getFunction().getContext());
5328     else if (Opc == X86::FsFLD0SD || Opc == X86::AVX512_FsFLD0SD)
5329       Ty = Type::getDoubleTy(MF.getFunction().getContext());
5330     else if (Opc == X86::AVX512_512_SET0 || Opc == X86::AVX512_512_SETALLONES)
5331       Ty = VectorType::get(Type::getInt32Ty(MF.getFunction().getContext()),16);
5332     else if (Opc == X86::AVX2_SETALLONES || Opc == X86::AVX_SET0 ||
5333              Opc == X86::AVX512_256_SET0 || Opc == X86::AVX1_SETALLONES)
5334       Ty = VectorType::get(Type::getInt32Ty(MF.getFunction().getContext()), 8);
5335     else if (Opc == X86::MMX_SET0)
5336       Ty = VectorType::get(Type::getInt32Ty(MF.getFunction().getContext()), 2);
5337     else
5338       Ty = VectorType::get(Type::getInt32Ty(MF.getFunction().getContext()), 4);
5339 
5340     bool IsAllOnes = (Opc == X86::V_SETALLONES || Opc == X86::AVX2_SETALLONES ||
5341                       Opc == X86::AVX512_512_SETALLONES ||
5342                       Opc == X86::AVX1_SETALLONES);
5343     const Constant *C = IsAllOnes ? Constant::getAllOnesValue(Ty) :
5344                                     Constant::getNullValue(Ty);
5345     unsigned CPI = MCP.getConstantPoolIndex(C, Alignment);
5346 
5347     // Create operands to load from the constant pool entry.
5348     MOs.push_back(MachineOperand::CreateReg(PICBase, false));
5349     MOs.push_back(MachineOperand::CreateImm(1));
5350     MOs.push_back(MachineOperand::CreateReg(0, false));
5351     MOs.push_back(MachineOperand::CreateCPI(CPI, 0));
5352     MOs.push_back(MachineOperand::CreateReg(0, false));
5353     break;
5354   }
5355   default: {
5356     if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
5357       return nullptr;
5358 
5359     // Folding a normal load. Just copy the load's address operands.
5360     MOs.append(LoadMI.operands_begin() + NumOps - X86::AddrNumOperands,
5361                LoadMI.operands_begin() + NumOps);
5362     break;
5363   }
5364   }
5365   return foldMemoryOperandImpl(MF, MI, Ops[0], MOs, InsertPt,
5366                                /*Size=*/0, Alignment, /*AllowCommute=*/true);
5367 }
5368 
5369 static SmallVector<MachineMemOperand *, 2>
5370 extractLoadMMOs(ArrayRef<MachineMemOperand *> MMOs, MachineFunction &MF) {
5371   SmallVector<MachineMemOperand *, 2> LoadMMOs;
5372 
5373   for (MachineMemOperand *MMO : MMOs) {
5374     if (!MMO->isLoad())
5375       continue;
5376 
5377     if (!MMO->isStore()) {
5378       // Reuse the MMO.
5379       LoadMMOs.push_back(MMO);
5380     } else {
5381       // Clone the MMO and unset the store flag.
5382       LoadMMOs.push_back(MF.getMachineMemOperand(
5383           MMO->getPointerInfo(), MMO->getFlags() & ~MachineMemOperand::MOStore,
5384           MMO->getSize(), MMO->getBaseAlignment(), MMO->getAAInfo(), nullptr,
5385           MMO->getSyncScopeID(), MMO->getOrdering(),
5386           MMO->getFailureOrdering()));
5387     }
5388   }
5389 
5390   return LoadMMOs;
5391 }
5392 
5393 static SmallVector<MachineMemOperand *, 2>
5394 extractStoreMMOs(ArrayRef<MachineMemOperand *> MMOs, MachineFunction &MF) {
5395   SmallVector<MachineMemOperand *, 2> StoreMMOs;
5396 
5397   for (MachineMemOperand *MMO : MMOs) {
5398     if (!MMO->isStore())
5399       continue;
5400 
5401     if (!MMO->isLoad()) {
5402       // Reuse the MMO.
5403       StoreMMOs.push_back(MMO);
5404     } else {
5405       // Clone the MMO and unset the load flag.
5406       StoreMMOs.push_back(MF.getMachineMemOperand(
5407           MMO->getPointerInfo(), MMO->getFlags() & ~MachineMemOperand::MOLoad,
5408           MMO->getSize(), MMO->getBaseAlignment(), MMO->getAAInfo(), nullptr,
5409           MMO->getSyncScopeID(), MMO->getOrdering(),
5410           MMO->getFailureOrdering()));
5411     }
5412   }
5413 
5414   return StoreMMOs;
5415 }
5416 
5417 bool X86InstrInfo::unfoldMemoryOperand(
5418     MachineFunction &MF, MachineInstr &MI, unsigned Reg, bool UnfoldLoad,
5419     bool UnfoldStore, SmallVectorImpl<MachineInstr *> &NewMIs) const {
5420   const X86MemoryFoldTableEntry *I = lookupUnfoldTable(MI.getOpcode());
5421   if (I == nullptr)
5422     return false;
5423   unsigned Opc = I->DstOp;
5424   unsigned Index = I->Flags & TB_INDEX_MASK;
5425   bool FoldedLoad = I->Flags & TB_FOLDED_LOAD;
5426   bool FoldedStore = I->Flags & TB_FOLDED_STORE;
5427   if (UnfoldLoad && !FoldedLoad)
5428     return false;
5429   UnfoldLoad &= FoldedLoad;
5430   if (UnfoldStore && !FoldedStore)
5431     return false;
5432   UnfoldStore &= FoldedStore;
5433 
5434   const MCInstrDesc &MCID = get(Opc);
5435   const TargetRegisterClass *RC = getRegClass(MCID, Index, &RI, MF);
5436   // TODO: Check if 32-byte or greater accesses are slow too?
5437   if (!MI.hasOneMemOperand() && RC == &X86::VR128RegClass &&
5438       Subtarget.isUnalignedMem16Slow())
5439     // Without memoperands, loadRegFromAddr and storeRegToStackSlot will
5440     // conservatively assume the address is unaligned. That's bad for
5441     // performance.
5442     return false;
5443   SmallVector<MachineOperand, X86::AddrNumOperands> AddrOps;
5444   SmallVector<MachineOperand,2> BeforeOps;
5445   SmallVector<MachineOperand,2> AfterOps;
5446   SmallVector<MachineOperand,4> ImpOps;
5447   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
5448     MachineOperand &Op = MI.getOperand(i);
5449     if (i >= Index && i < Index + X86::AddrNumOperands)
5450       AddrOps.push_back(Op);
5451     else if (Op.isReg() && Op.isImplicit())
5452       ImpOps.push_back(Op);
5453     else if (i < Index)
5454       BeforeOps.push_back(Op);
5455     else if (i > Index)
5456       AfterOps.push_back(Op);
5457   }
5458 
5459   // Emit the load instruction.
5460   if (UnfoldLoad) {
5461     auto MMOs = extractLoadMMOs(MI.memoperands(), MF);
5462     loadRegFromAddr(MF, Reg, AddrOps, RC, MMOs, NewMIs);
5463     if (UnfoldStore) {
5464       // Address operands cannot be marked isKill.
5465       for (unsigned i = 1; i != 1 + X86::AddrNumOperands; ++i) {
5466         MachineOperand &MO = NewMIs[0]->getOperand(i);
5467         if (MO.isReg())
5468           MO.setIsKill(false);
5469       }
5470     }
5471   }
5472 
5473   // Emit the data processing instruction.
5474   MachineInstr *DataMI = MF.CreateMachineInstr(MCID, MI.getDebugLoc(), true);
5475   MachineInstrBuilder MIB(MF, DataMI);
5476 
5477   if (FoldedStore)
5478     MIB.addReg(Reg, RegState::Define);
5479   for (MachineOperand &BeforeOp : BeforeOps)
5480     MIB.add(BeforeOp);
5481   if (FoldedLoad)
5482     MIB.addReg(Reg);
5483   for (MachineOperand &AfterOp : AfterOps)
5484     MIB.add(AfterOp);
5485   for (MachineOperand &ImpOp : ImpOps) {
5486     MIB.addReg(ImpOp.getReg(),
5487                getDefRegState(ImpOp.isDef()) |
5488                RegState::Implicit |
5489                getKillRegState(ImpOp.isKill()) |
5490                getDeadRegState(ImpOp.isDead()) |
5491                getUndefRegState(ImpOp.isUndef()));
5492   }
5493   // Change CMP32ri r, 0 back to TEST32rr r, r, etc.
5494   switch (DataMI->getOpcode()) {
5495   default: break;
5496   case X86::CMP64ri32:
5497   case X86::CMP64ri8:
5498   case X86::CMP32ri:
5499   case X86::CMP32ri8:
5500   case X86::CMP16ri:
5501   case X86::CMP16ri8:
5502   case X86::CMP8ri: {
5503     MachineOperand &MO0 = DataMI->getOperand(0);
5504     MachineOperand &MO1 = DataMI->getOperand(1);
5505     if (MO1.getImm() == 0) {
5506       unsigned NewOpc;
5507       switch (DataMI->getOpcode()) {
5508       default: llvm_unreachable("Unreachable!");
5509       case X86::CMP64ri8:
5510       case X86::CMP64ri32: NewOpc = X86::TEST64rr; break;
5511       case X86::CMP32ri8:
5512       case X86::CMP32ri:   NewOpc = X86::TEST32rr; break;
5513       case X86::CMP16ri8:
5514       case X86::CMP16ri:   NewOpc = X86::TEST16rr; break;
5515       case X86::CMP8ri:    NewOpc = X86::TEST8rr; break;
5516       }
5517       DataMI->setDesc(get(NewOpc));
5518       MO1.ChangeToRegister(MO0.getReg(), false);
5519     }
5520   }
5521   }
5522   NewMIs.push_back(DataMI);
5523 
5524   // Emit the store instruction.
5525   if (UnfoldStore) {
5526     const TargetRegisterClass *DstRC = getRegClass(MCID, 0, &RI, MF);
5527     auto MMOs = extractStoreMMOs(MI.memoperands(), MF);
5528     storeRegToAddr(MF, Reg, true, AddrOps, DstRC, MMOs, NewMIs);
5529   }
5530 
5531   return true;
5532 }
5533 
5534 bool
5535 X86InstrInfo::unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
5536                                   SmallVectorImpl<SDNode*> &NewNodes) const {
5537   if (!N->isMachineOpcode())
5538     return false;
5539 
5540   const X86MemoryFoldTableEntry *I = lookupUnfoldTable(N->getMachineOpcode());
5541   if (I == nullptr)
5542     return false;
5543   unsigned Opc = I->DstOp;
5544   unsigned Index = I->Flags & TB_INDEX_MASK;
5545   bool FoldedLoad = I->Flags & TB_FOLDED_LOAD;
5546   bool FoldedStore = I->Flags & TB_FOLDED_STORE;
5547   const MCInstrDesc &MCID = get(Opc);
5548   MachineFunction &MF = DAG.getMachineFunction();
5549   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
5550   const TargetRegisterClass *RC = getRegClass(MCID, Index, &RI, MF);
5551   unsigned NumDefs = MCID.NumDefs;
5552   std::vector<SDValue> AddrOps;
5553   std::vector<SDValue> BeforeOps;
5554   std::vector<SDValue> AfterOps;
5555   SDLoc dl(N);
5556   unsigned NumOps = N->getNumOperands();
5557   for (unsigned i = 0; i != NumOps-1; ++i) {
5558     SDValue Op = N->getOperand(i);
5559     if (i >= Index-NumDefs && i < Index-NumDefs + X86::AddrNumOperands)
5560       AddrOps.push_back(Op);
5561     else if (i < Index-NumDefs)
5562       BeforeOps.push_back(Op);
5563     else if (i > Index-NumDefs)
5564       AfterOps.push_back(Op);
5565   }
5566   SDValue Chain = N->getOperand(NumOps-1);
5567   AddrOps.push_back(Chain);
5568 
5569   // Emit the load instruction.
5570   SDNode *Load = nullptr;
5571   if (FoldedLoad) {
5572     EVT VT = *TRI.legalclasstypes_begin(*RC);
5573     auto MMOs = extractLoadMMOs(cast<MachineSDNode>(N)->memoperands(), MF);
5574     if (MMOs.empty() && RC == &X86::VR128RegClass &&
5575         Subtarget.isUnalignedMem16Slow())
5576       // Do not introduce a slow unaligned load.
5577       return false;
5578     // FIXME: If a VR128 can have size 32, we should be checking if a 32-byte
5579     // memory access is slow above.
5580     unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
5581     bool isAligned = !MMOs.empty() && MMOs.front()->getAlignment() >= Alignment;
5582     Load = DAG.getMachineNode(getLoadRegOpcode(0, RC, isAligned, Subtarget), dl,
5583                               VT, MVT::Other, AddrOps);
5584     NewNodes.push_back(Load);
5585 
5586     // Preserve memory reference information.
5587     DAG.setNodeMemRefs(cast<MachineSDNode>(Load), MMOs);
5588   }
5589 
5590   // Emit the data processing instruction.
5591   std::vector<EVT> VTs;
5592   const TargetRegisterClass *DstRC = nullptr;
5593   if (MCID.getNumDefs() > 0) {
5594     DstRC = getRegClass(MCID, 0, &RI, MF);
5595     VTs.push_back(*TRI.legalclasstypes_begin(*DstRC));
5596   }
5597   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
5598     EVT VT = N->getValueType(i);
5599     if (VT != MVT::Other && i >= (unsigned)MCID.getNumDefs())
5600       VTs.push_back(VT);
5601   }
5602   if (Load)
5603     BeforeOps.push_back(SDValue(Load, 0));
5604   BeforeOps.insert(BeforeOps.end(), AfterOps.begin(), AfterOps.end());
5605   // Change CMP32ri r, 0 back to TEST32rr r, r, etc.
5606   switch (Opc) {
5607     default: break;
5608     case X86::CMP64ri32:
5609     case X86::CMP64ri8:
5610     case X86::CMP32ri:
5611     case X86::CMP32ri8:
5612     case X86::CMP16ri:
5613     case X86::CMP16ri8:
5614     case X86::CMP8ri:
5615       if (isNullConstant(BeforeOps[1])) {
5616         switch (Opc) {
5617           default: llvm_unreachable("Unreachable!");
5618           case X86::CMP64ri8:
5619           case X86::CMP64ri32: Opc = X86::TEST64rr; break;
5620           case X86::CMP32ri8:
5621           case X86::CMP32ri:   Opc = X86::TEST32rr; break;
5622           case X86::CMP16ri8:
5623           case X86::CMP16ri:   Opc = X86::TEST16rr; break;
5624           case X86::CMP8ri:    Opc = X86::TEST8rr; break;
5625         }
5626         BeforeOps[1] = BeforeOps[0];
5627       }
5628   }
5629   SDNode *NewNode= DAG.getMachineNode(Opc, dl, VTs, BeforeOps);
5630   NewNodes.push_back(NewNode);
5631 
5632   // Emit the store instruction.
5633   if (FoldedStore) {
5634     AddrOps.pop_back();
5635     AddrOps.push_back(SDValue(NewNode, 0));
5636     AddrOps.push_back(Chain);
5637     auto MMOs = extractStoreMMOs(cast<MachineSDNode>(N)->memoperands(), MF);
5638     if (MMOs.empty() && RC == &X86::VR128RegClass &&
5639         Subtarget.isUnalignedMem16Slow())
5640       // Do not introduce a slow unaligned store.
5641       return false;
5642     // FIXME: If a VR128 can have size 32, we should be checking if a 32-byte
5643     // memory access is slow above.
5644     unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
5645     bool isAligned = !MMOs.empty() && MMOs.front()->getAlignment() >= Alignment;
5646     SDNode *Store =
5647         DAG.getMachineNode(getStoreRegOpcode(0, DstRC, isAligned, Subtarget),
5648                            dl, MVT::Other, AddrOps);
5649     NewNodes.push_back(Store);
5650 
5651     // Preserve memory reference information.
5652     DAG.setNodeMemRefs(cast<MachineSDNode>(Store), MMOs);
5653   }
5654 
5655   return true;
5656 }
5657 
5658 unsigned X86InstrInfo::getOpcodeAfterMemoryUnfold(unsigned Opc,
5659                                       bool UnfoldLoad, bool UnfoldStore,
5660                                       unsigned *LoadRegIndex) const {
5661   const X86MemoryFoldTableEntry *I = lookupUnfoldTable(Opc);
5662   if (I == nullptr)
5663     return 0;
5664   bool FoldedLoad = I->Flags & TB_FOLDED_LOAD;
5665   bool FoldedStore = I->Flags & TB_FOLDED_STORE;
5666   if (UnfoldLoad && !FoldedLoad)
5667     return 0;
5668   if (UnfoldStore && !FoldedStore)
5669     return 0;
5670   if (LoadRegIndex)
5671     *LoadRegIndex = I->Flags & TB_INDEX_MASK;
5672   return I->DstOp;
5673 }
5674 
5675 bool
5676 X86InstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
5677                                      int64_t &Offset1, int64_t &Offset2) const {
5678   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
5679     return false;
5680   unsigned Opc1 = Load1->getMachineOpcode();
5681   unsigned Opc2 = Load2->getMachineOpcode();
5682   switch (Opc1) {
5683   default: return false;
5684   case X86::MOV8rm:
5685   case X86::MOV16rm:
5686   case X86::MOV32rm:
5687   case X86::MOV64rm:
5688   case X86::LD_Fp32m:
5689   case X86::LD_Fp64m:
5690   case X86::LD_Fp80m:
5691   case X86::MOVSSrm:
5692   case X86::MOVSDrm:
5693   case X86::MMX_MOVD64rm:
5694   case X86::MMX_MOVQ64rm:
5695   case X86::MOVAPSrm:
5696   case X86::MOVUPSrm:
5697   case X86::MOVAPDrm:
5698   case X86::MOVUPDrm:
5699   case X86::MOVDQArm:
5700   case X86::MOVDQUrm:
5701   // AVX load instructions
5702   case X86::VMOVSSrm:
5703   case X86::VMOVSDrm:
5704   case X86::VMOVAPSrm:
5705   case X86::VMOVUPSrm:
5706   case X86::VMOVAPDrm:
5707   case X86::VMOVUPDrm:
5708   case X86::VMOVDQArm:
5709   case X86::VMOVDQUrm:
5710   case X86::VMOVAPSYrm:
5711   case X86::VMOVUPSYrm:
5712   case X86::VMOVAPDYrm:
5713   case X86::VMOVUPDYrm:
5714   case X86::VMOVDQAYrm:
5715   case X86::VMOVDQUYrm:
5716   // AVX512 load instructions
5717   case X86::VMOVSSZrm:
5718   case X86::VMOVSDZrm:
5719   case X86::VMOVAPSZ128rm:
5720   case X86::VMOVUPSZ128rm:
5721   case X86::VMOVAPSZ128rm_NOVLX:
5722   case X86::VMOVUPSZ128rm_NOVLX:
5723   case X86::VMOVAPDZ128rm:
5724   case X86::VMOVUPDZ128rm:
5725   case X86::VMOVDQU8Z128rm:
5726   case X86::VMOVDQU16Z128rm:
5727   case X86::VMOVDQA32Z128rm:
5728   case X86::VMOVDQU32Z128rm:
5729   case X86::VMOVDQA64Z128rm:
5730   case X86::VMOVDQU64Z128rm:
5731   case X86::VMOVAPSZ256rm:
5732   case X86::VMOVUPSZ256rm:
5733   case X86::VMOVAPSZ256rm_NOVLX:
5734   case X86::VMOVUPSZ256rm_NOVLX:
5735   case X86::VMOVAPDZ256rm:
5736   case X86::VMOVUPDZ256rm:
5737   case X86::VMOVDQU8Z256rm:
5738   case X86::VMOVDQU16Z256rm:
5739   case X86::VMOVDQA32Z256rm:
5740   case X86::VMOVDQU32Z256rm:
5741   case X86::VMOVDQA64Z256rm:
5742   case X86::VMOVDQU64Z256rm:
5743   case X86::VMOVAPSZrm:
5744   case X86::VMOVUPSZrm:
5745   case X86::VMOVAPDZrm:
5746   case X86::VMOVUPDZrm:
5747   case X86::VMOVDQU8Zrm:
5748   case X86::VMOVDQU16Zrm:
5749   case X86::VMOVDQA32Zrm:
5750   case X86::VMOVDQU32Zrm:
5751   case X86::VMOVDQA64Zrm:
5752   case X86::VMOVDQU64Zrm:
5753   case X86::KMOVBkm:
5754   case X86::KMOVWkm:
5755   case X86::KMOVDkm:
5756   case X86::KMOVQkm:
5757     break;
5758   }
5759   switch (Opc2) {
5760   default: return false;
5761   case X86::MOV8rm:
5762   case X86::MOV16rm:
5763   case X86::MOV32rm:
5764   case X86::MOV64rm:
5765   case X86::LD_Fp32m:
5766   case X86::LD_Fp64m:
5767   case X86::LD_Fp80m:
5768   case X86::MOVSSrm:
5769   case X86::MOVSDrm:
5770   case X86::MMX_MOVD64rm:
5771   case X86::MMX_MOVQ64rm:
5772   case X86::MOVAPSrm:
5773   case X86::MOVUPSrm:
5774   case X86::MOVAPDrm:
5775   case X86::MOVUPDrm:
5776   case X86::MOVDQArm:
5777   case X86::MOVDQUrm:
5778   // AVX load instructions
5779   case X86::VMOVSSrm:
5780   case X86::VMOVSDrm:
5781   case X86::VMOVAPSrm:
5782   case X86::VMOVUPSrm:
5783   case X86::VMOVAPDrm:
5784   case X86::VMOVUPDrm:
5785   case X86::VMOVDQArm:
5786   case X86::VMOVDQUrm:
5787   case X86::VMOVAPSYrm:
5788   case X86::VMOVUPSYrm:
5789   case X86::VMOVAPDYrm:
5790   case X86::VMOVUPDYrm:
5791   case X86::VMOVDQAYrm:
5792   case X86::VMOVDQUYrm:
5793   // AVX512 load instructions
5794   case X86::VMOVSSZrm:
5795   case X86::VMOVSDZrm:
5796   case X86::VMOVAPSZ128rm:
5797   case X86::VMOVUPSZ128rm:
5798   case X86::VMOVAPSZ128rm_NOVLX:
5799   case X86::VMOVUPSZ128rm_NOVLX:
5800   case X86::VMOVAPDZ128rm:
5801   case X86::VMOVUPDZ128rm:
5802   case X86::VMOVDQU8Z128rm:
5803   case X86::VMOVDQU16Z128rm:
5804   case X86::VMOVDQA32Z128rm:
5805   case X86::VMOVDQU32Z128rm:
5806   case X86::VMOVDQA64Z128rm:
5807   case X86::VMOVDQU64Z128rm:
5808   case X86::VMOVAPSZ256rm:
5809   case X86::VMOVUPSZ256rm:
5810   case X86::VMOVAPSZ256rm_NOVLX:
5811   case X86::VMOVUPSZ256rm_NOVLX:
5812   case X86::VMOVAPDZ256rm:
5813   case X86::VMOVUPDZ256rm:
5814   case X86::VMOVDQU8Z256rm:
5815   case X86::VMOVDQU16Z256rm:
5816   case X86::VMOVDQA32Z256rm:
5817   case X86::VMOVDQU32Z256rm:
5818   case X86::VMOVDQA64Z256rm:
5819   case X86::VMOVDQU64Z256rm:
5820   case X86::VMOVAPSZrm:
5821   case X86::VMOVUPSZrm:
5822   case X86::VMOVAPDZrm:
5823   case X86::VMOVUPDZrm:
5824   case X86::VMOVDQU8Zrm:
5825   case X86::VMOVDQU16Zrm:
5826   case X86::VMOVDQA32Zrm:
5827   case X86::VMOVDQU32Zrm:
5828   case X86::VMOVDQA64Zrm:
5829   case X86::VMOVDQU64Zrm:
5830   case X86::KMOVBkm:
5831   case X86::KMOVWkm:
5832   case X86::KMOVDkm:
5833   case X86::KMOVQkm:
5834     break;
5835   }
5836 
5837   // Lambda to check if both the loads have the same value for an operand index.
5838   auto HasSameOp = [&](int I) {
5839     return Load1->getOperand(I) == Load2->getOperand(I);
5840   };
5841 
5842   // All operands except the displacement should match.
5843   if (!HasSameOp(X86::AddrBaseReg) || !HasSameOp(X86::AddrScaleAmt) ||
5844       !HasSameOp(X86::AddrIndexReg) || !HasSameOp(X86::AddrSegmentReg))
5845     return false;
5846 
5847   // Chain Operand must be the same.
5848   if (!HasSameOp(5))
5849     return false;
5850 
5851   // Now let's examine if the displacements are constants.
5852   auto Disp1 = dyn_cast<ConstantSDNode>(Load1->getOperand(X86::AddrDisp));
5853   auto Disp2 = dyn_cast<ConstantSDNode>(Load2->getOperand(X86::AddrDisp));
5854   if (!Disp1 || !Disp2)
5855     return false;
5856 
5857   Offset1 = Disp1->getSExtValue();
5858   Offset2 = Disp2->getSExtValue();
5859   return true;
5860 }
5861 
5862 bool X86InstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
5863                                            int64_t Offset1, int64_t Offset2,
5864                                            unsigned NumLoads) const {
5865   assert(Offset2 > Offset1);
5866   if ((Offset2 - Offset1) / 8 > 64)
5867     return false;
5868 
5869   unsigned Opc1 = Load1->getMachineOpcode();
5870   unsigned Opc2 = Load2->getMachineOpcode();
5871   if (Opc1 != Opc2)
5872     return false;  // FIXME: overly conservative?
5873 
5874   switch (Opc1) {
5875   default: break;
5876   case X86::LD_Fp32m:
5877   case X86::LD_Fp64m:
5878   case X86::LD_Fp80m:
5879   case X86::MMX_MOVD64rm:
5880   case X86::MMX_MOVQ64rm:
5881     return false;
5882   }
5883 
5884   EVT VT = Load1->getValueType(0);
5885   switch (VT.getSimpleVT().SimpleTy) {
5886   default:
5887     // XMM registers. In 64-bit mode we can be a bit more aggressive since we
5888     // have 16 of them to play with.
5889     if (Subtarget.is64Bit()) {
5890       if (NumLoads >= 3)
5891         return false;
5892     } else if (NumLoads) {
5893       return false;
5894     }
5895     break;
5896   case MVT::i8:
5897   case MVT::i16:
5898   case MVT::i32:
5899   case MVT::i64:
5900   case MVT::f32:
5901   case MVT::f64:
5902     if (NumLoads)
5903       return false;
5904     break;
5905   }
5906 
5907   return true;
5908 }
5909 
5910 bool X86InstrInfo::
5911 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
5912   assert(Cond.size() == 1 && "Invalid X86 branch condition!");
5913   X86::CondCode CC = static_cast<X86::CondCode>(Cond[0].getImm());
5914   Cond[0].setImm(GetOppositeBranchCondition(CC));
5915   return false;
5916 }
5917 
5918 bool X86InstrInfo::
5919 isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
5920   // FIXME: Return false for x87 stack register classes for now. We can't
5921   // allow any loads of these registers before FpGet_ST0_80.
5922   return !(RC == &X86::CCRRegClass || RC == &X86::DFCCRRegClass ||
5923            RC == &X86::RFP32RegClass || RC == &X86::RFP64RegClass ||
5924            RC == &X86::RFP80RegClass);
5925 }
5926 
5927 /// Return a virtual register initialized with the
5928 /// the global base register value. Output instructions required to
5929 /// initialize the register in the function entry block, if necessary.
5930 ///
5931 /// TODO: Eliminate this and move the code to X86MachineFunctionInfo.
5932 ///
5933 unsigned X86InstrInfo::getGlobalBaseReg(MachineFunction *MF) const {
5934   assert((!Subtarget.is64Bit() ||
5935           MF->getTarget().getCodeModel() == CodeModel::Medium ||
5936           MF->getTarget().getCodeModel() == CodeModel::Large) &&
5937          "X86-64 PIC uses RIP relative addressing");
5938 
5939   X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
5940   unsigned GlobalBaseReg = X86FI->getGlobalBaseReg();
5941   if (GlobalBaseReg != 0)
5942     return GlobalBaseReg;
5943 
5944   // Create the register. The code to initialize it is inserted
5945   // later, by the CGBR pass (below).
5946   MachineRegisterInfo &RegInfo = MF->getRegInfo();
5947   GlobalBaseReg = RegInfo.createVirtualRegister(
5948       Subtarget.is64Bit() ? &X86::GR64_NOSPRegClass : &X86::GR32_NOSPRegClass);
5949   X86FI->setGlobalBaseReg(GlobalBaseReg);
5950   return GlobalBaseReg;
5951 }
5952 
5953 // These are the replaceable SSE instructions. Some of these have Int variants
5954 // that we don't include here. We don't want to replace instructions selected
5955 // by intrinsics.
5956 static const uint16_t ReplaceableInstrs[][3] = {
5957   //PackedSingle     PackedDouble    PackedInt
5958   { X86::MOVAPSmr,   X86::MOVAPDmr,  X86::MOVDQAmr  },
5959   { X86::MOVAPSrm,   X86::MOVAPDrm,  X86::MOVDQArm  },
5960   { X86::MOVAPSrr,   X86::MOVAPDrr,  X86::MOVDQArr  },
5961   { X86::MOVUPSmr,   X86::MOVUPDmr,  X86::MOVDQUmr  },
5962   { X86::MOVUPSrm,   X86::MOVUPDrm,  X86::MOVDQUrm  },
5963   { X86::MOVLPSmr,   X86::MOVLPDmr,  X86::MOVPQI2QImr },
5964   { X86::MOVSDmr,    X86::MOVSDmr,   X86::MOVPQI2QImr },
5965   { X86::MOVSSmr,    X86::MOVSSmr,   X86::MOVPDI2DImr },
5966   { X86::MOVSDrm,    X86::MOVSDrm,   X86::MOVQI2PQIrm },
5967   { X86::MOVSSrm,    X86::MOVSSrm,   X86::MOVDI2PDIrm },
5968   { X86::MOVNTPSmr,  X86::MOVNTPDmr, X86::MOVNTDQmr },
5969   { X86::ANDNPSrm,   X86::ANDNPDrm,  X86::PANDNrm   },
5970   { X86::ANDNPSrr,   X86::ANDNPDrr,  X86::PANDNrr   },
5971   { X86::ANDPSrm,    X86::ANDPDrm,   X86::PANDrm    },
5972   { X86::ANDPSrr,    X86::ANDPDrr,   X86::PANDrr    },
5973   { X86::ORPSrm,     X86::ORPDrm,    X86::PORrm     },
5974   { X86::ORPSrr,     X86::ORPDrr,    X86::PORrr     },
5975   { X86::XORPSrm,    X86::XORPDrm,   X86::PXORrm    },
5976   { X86::XORPSrr,    X86::XORPDrr,   X86::PXORrr    },
5977   { X86::UNPCKLPDrm, X86::UNPCKLPDrm, X86::PUNPCKLQDQrm },
5978   { X86::MOVLHPSrr,  X86::UNPCKLPDrr, X86::PUNPCKLQDQrr },
5979   { X86::UNPCKHPDrm, X86::UNPCKHPDrm, X86::PUNPCKHQDQrm },
5980   { X86::UNPCKHPDrr, X86::UNPCKHPDrr, X86::PUNPCKHQDQrr },
5981   { X86::UNPCKLPSrm, X86::UNPCKLPSrm, X86::PUNPCKLDQrm },
5982   { X86::UNPCKLPSrr, X86::UNPCKLPSrr, X86::PUNPCKLDQrr },
5983   { X86::UNPCKHPSrm, X86::UNPCKHPSrm, X86::PUNPCKHDQrm },
5984   { X86::UNPCKHPSrr, X86::UNPCKHPSrr, X86::PUNPCKHDQrr },
5985   { X86::EXTRACTPSmr, X86::EXTRACTPSmr, X86::PEXTRDmr },
5986   { X86::EXTRACTPSrr, X86::EXTRACTPSrr, X86::PEXTRDrr },
5987   // AVX 128-bit support
5988   { X86::VMOVAPSmr,  X86::VMOVAPDmr,  X86::VMOVDQAmr  },
5989   { X86::VMOVAPSrm,  X86::VMOVAPDrm,  X86::VMOVDQArm  },
5990   { X86::VMOVAPSrr,  X86::VMOVAPDrr,  X86::VMOVDQArr  },
5991   { X86::VMOVUPSmr,  X86::VMOVUPDmr,  X86::VMOVDQUmr  },
5992   { X86::VMOVUPSrm,  X86::VMOVUPDrm,  X86::VMOVDQUrm  },
5993   { X86::VMOVLPSmr,  X86::VMOVLPDmr,  X86::VMOVPQI2QImr },
5994   { X86::VMOVSDmr,   X86::VMOVSDmr,   X86::VMOVPQI2QImr },
5995   { X86::VMOVSSmr,   X86::VMOVSSmr,   X86::VMOVPDI2DImr },
5996   { X86::VMOVSDrm,   X86::VMOVSDrm,   X86::VMOVQI2PQIrm },
5997   { X86::VMOVSSrm,   X86::VMOVSSrm,   X86::VMOVDI2PDIrm },
5998   { X86::VMOVNTPSmr, X86::VMOVNTPDmr, X86::VMOVNTDQmr },
5999   { X86::VANDNPSrm,  X86::VANDNPDrm,  X86::VPANDNrm   },
6000   { X86::VANDNPSrr,  X86::VANDNPDrr,  X86::VPANDNrr   },
6001   { X86::VANDPSrm,   X86::VANDPDrm,   X86::VPANDrm    },
6002   { X86::VANDPSrr,   X86::VANDPDrr,   X86::VPANDrr    },
6003   { X86::VORPSrm,    X86::VORPDrm,    X86::VPORrm     },
6004   { X86::VORPSrr,    X86::VORPDrr,    X86::VPORrr     },
6005   { X86::VXORPSrm,   X86::VXORPDrm,   X86::VPXORrm    },
6006   { X86::VXORPSrr,   X86::VXORPDrr,   X86::VPXORrr    },
6007   { X86::VUNPCKLPDrm, X86::VUNPCKLPDrm, X86::VPUNPCKLQDQrm },
6008   { X86::VMOVLHPSrr,  X86::VUNPCKLPDrr, X86::VPUNPCKLQDQrr },
6009   { X86::VUNPCKHPDrm, X86::VUNPCKHPDrm, X86::VPUNPCKHQDQrm },
6010   { X86::VUNPCKHPDrr, X86::VUNPCKHPDrr, X86::VPUNPCKHQDQrr },
6011   { X86::VUNPCKLPSrm, X86::VUNPCKLPSrm, X86::VPUNPCKLDQrm },
6012   { X86::VUNPCKLPSrr, X86::VUNPCKLPSrr, X86::VPUNPCKLDQrr },
6013   { X86::VUNPCKHPSrm, X86::VUNPCKHPSrm, X86::VPUNPCKHDQrm },
6014   { X86::VUNPCKHPSrr, X86::VUNPCKHPSrr, X86::VPUNPCKHDQrr },
6015   { X86::VEXTRACTPSmr, X86::VEXTRACTPSmr, X86::VPEXTRDmr },
6016   { X86::VEXTRACTPSrr, X86::VEXTRACTPSrr, X86::VPEXTRDrr },
6017   // AVX 256-bit support
6018   { X86::VMOVAPSYmr,   X86::VMOVAPDYmr,   X86::VMOVDQAYmr  },
6019   { X86::VMOVAPSYrm,   X86::VMOVAPDYrm,   X86::VMOVDQAYrm  },
6020   { X86::VMOVAPSYrr,   X86::VMOVAPDYrr,   X86::VMOVDQAYrr  },
6021   { X86::VMOVUPSYmr,   X86::VMOVUPDYmr,   X86::VMOVDQUYmr  },
6022   { X86::VMOVUPSYrm,   X86::VMOVUPDYrm,   X86::VMOVDQUYrm  },
6023   { X86::VMOVNTPSYmr,  X86::VMOVNTPDYmr,  X86::VMOVNTDQYmr },
6024   { X86::VPERMPSYrm,   X86::VPERMPSYrm,   X86::VPERMDYrm },
6025   { X86::VPERMPSYrr,   X86::VPERMPSYrr,   X86::VPERMDYrr },
6026   { X86::VPERMPDYmi,   X86::VPERMPDYmi,   X86::VPERMQYmi },
6027   { X86::VPERMPDYri,   X86::VPERMPDYri,   X86::VPERMQYri },
6028   // AVX512 support
6029   { X86::VMOVLPSZ128mr,  X86::VMOVLPDZ128mr,  X86::VMOVPQI2QIZmr  },
6030   { X86::VMOVNTPSZ128mr, X86::VMOVNTPDZ128mr, X86::VMOVNTDQZ128mr },
6031   { X86::VMOVNTPSZ256mr, X86::VMOVNTPDZ256mr, X86::VMOVNTDQZ256mr },
6032   { X86::VMOVNTPSZmr,    X86::VMOVNTPDZmr,    X86::VMOVNTDQZmr    },
6033   { X86::VMOVSDZmr,      X86::VMOVSDZmr,      X86::VMOVPQI2QIZmr  },
6034   { X86::VMOVSSZmr,      X86::VMOVSSZmr,      X86::VMOVPDI2DIZmr  },
6035   { X86::VMOVSDZrm,      X86::VMOVSDZrm,      X86::VMOVQI2PQIZrm  },
6036   { X86::VMOVSSZrm,      X86::VMOVSSZrm,      X86::VMOVDI2PDIZrm  },
6037   { X86::VBROADCASTSSZ128r, X86::VBROADCASTSSZ128r, X86::VPBROADCASTDZ128r },
6038   { X86::VBROADCASTSSZ128m, X86::VBROADCASTSSZ128m, X86::VPBROADCASTDZ128m },
6039   { X86::VBROADCASTSSZ256r, X86::VBROADCASTSSZ256r, X86::VPBROADCASTDZ256r },
6040   { X86::VBROADCASTSSZ256m, X86::VBROADCASTSSZ256m, X86::VPBROADCASTDZ256m },
6041   { X86::VBROADCASTSSZr,    X86::VBROADCASTSSZr,    X86::VPBROADCASTDZr },
6042   { X86::VBROADCASTSSZm,    X86::VBROADCASTSSZm,    X86::VPBROADCASTDZm },
6043   { X86::VBROADCASTSDZ256r, X86::VBROADCASTSDZ256r, X86::VPBROADCASTQZ256r },
6044   { X86::VBROADCASTSDZ256m, X86::VBROADCASTSDZ256m, X86::VPBROADCASTQZ256m },
6045   { X86::VBROADCASTSDZr,    X86::VBROADCASTSDZr,    X86::VPBROADCASTQZr },
6046   { X86::VBROADCASTSDZm,    X86::VBROADCASTSDZm,    X86::VPBROADCASTQZm },
6047   { X86::VINSERTF32x4Zrr,   X86::VINSERTF32x4Zrr,   X86::VINSERTI32x4Zrr },
6048   { X86::VINSERTF32x4Zrm,   X86::VINSERTF32x4Zrm,   X86::VINSERTI32x4Zrm },
6049   { X86::VINSERTF32x8Zrr,   X86::VINSERTF32x8Zrr,   X86::VINSERTI32x8Zrr },
6050   { X86::VINSERTF32x8Zrm,   X86::VINSERTF32x8Zrm,   X86::VINSERTI32x8Zrm },
6051   { X86::VINSERTF64x2Zrr,   X86::VINSERTF64x2Zrr,   X86::VINSERTI64x2Zrr },
6052   { X86::VINSERTF64x2Zrm,   X86::VINSERTF64x2Zrm,   X86::VINSERTI64x2Zrm },
6053   { X86::VINSERTF64x4Zrr,   X86::VINSERTF64x4Zrr,   X86::VINSERTI64x4Zrr },
6054   { X86::VINSERTF64x4Zrm,   X86::VINSERTF64x4Zrm,   X86::VINSERTI64x4Zrm },
6055   { X86::VINSERTF32x4Z256rr,X86::VINSERTF32x4Z256rr,X86::VINSERTI32x4Z256rr },
6056   { X86::VINSERTF32x4Z256rm,X86::VINSERTF32x4Z256rm,X86::VINSERTI32x4Z256rm },
6057   { X86::VINSERTF64x2Z256rr,X86::VINSERTF64x2Z256rr,X86::VINSERTI64x2Z256rr },
6058   { X86::VINSERTF64x2Z256rm,X86::VINSERTF64x2Z256rm,X86::VINSERTI64x2Z256rm },
6059   { X86::VEXTRACTF32x4Zrr,   X86::VEXTRACTF32x4Zrr,   X86::VEXTRACTI32x4Zrr },
6060   { X86::VEXTRACTF32x4Zmr,   X86::VEXTRACTF32x4Zmr,   X86::VEXTRACTI32x4Zmr },
6061   { X86::VEXTRACTF32x8Zrr,   X86::VEXTRACTF32x8Zrr,   X86::VEXTRACTI32x8Zrr },
6062   { X86::VEXTRACTF32x8Zmr,   X86::VEXTRACTF32x8Zmr,   X86::VEXTRACTI32x8Zmr },
6063   { X86::VEXTRACTF64x2Zrr,   X86::VEXTRACTF64x2Zrr,   X86::VEXTRACTI64x2Zrr },
6064   { X86::VEXTRACTF64x2Zmr,   X86::VEXTRACTF64x2Zmr,   X86::VEXTRACTI64x2Zmr },
6065   { X86::VEXTRACTF64x4Zrr,   X86::VEXTRACTF64x4Zrr,   X86::VEXTRACTI64x4Zrr },
6066   { X86::VEXTRACTF64x4Zmr,   X86::VEXTRACTF64x4Zmr,   X86::VEXTRACTI64x4Zmr },
6067   { X86::VEXTRACTF32x4Z256rr,X86::VEXTRACTF32x4Z256rr,X86::VEXTRACTI32x4Z256rr },
6068   { X86::VEXTRACTF32x4Z256mr,X86::VEXTRACTF32x4Z256mr,X86::VEXTRACTI32x4Z256mr },
6069   { X86::VEXTRACTF64x2Z256rr,X86::VEXTRACTF64x2Z256rr,X86::VEXTRACTI64x2Z256rr },
6070   { X86::VEXTRACTF64x2Z256mr,X86::VEXTRACTF64x2Z256mr,X86::VEXTRACTI64x2Z256mr },
6071   { X86::VPERMILPSmi,        X86::VPERMILPSmi,        X86::VPSHUFDmi },
6072   { X86::VPERMILPSri,        X86::VPERMILPSri,        X86::VPSHUFDri },
6073   { X86::VPERMILPSZ128mi,    X86::VPERMILPSZ128mi,    X86::VPSHUFDZ128mi },
6074   { X86::VPERMILPSZ128ri,    X86::VPERMILPSZ128ri,    X86::VPSHUFDZ128ri },
6075   { X86::VPERMILPSZ256mi,    X86::VPERMILPSZ256mi,    X86::VPSHUFDZ256mi },
6076   { X86::VPERMILPSZ256ri,    X86::VPERMILPSZ256ri,    X86::VPSHUFDZ256ri },
6077   { X86::VPERMILPSZmi,       X86::VPERMILPSZmi,       X86::VPSHUFDZmi },
6078   { X86::VPERMILPSZri,       X86::VPERMILPSZri,       X86::VPSHUFDZri },
6079   { X86::VPERMPSZ256rm,      X86::VPERMPSZ256rm,      X86::VPERMDZ256rm },
6080   { X86::VPERMPSZ256rr,      X86::VPERMPSZ256rr,      X86::VPERMDZ256rr },
6081   { X86::VPERMPDZ256mi,      X86::VPERMPDZ256mi,      X86::VPERMQZ256mi },
6082   { X86::VPERMPDZ256ri,      X86::VPERMPDZ256ri,      X86::VPERMQZ256ri },
6083   { X86::VPERMPDZ256rm,      X86::VPERMPDZ256rm,      X86::VPERMQZ256rm },
6084   { X86::VPERMPDZ256rr,      X86::VPERMPDZ256rr,      X86::VPERMQZ256rr },
6085   { X86::VPERMPSZrm,         X86::VPERMPSZrm,         X86::VPERMDZrm },
6086   { X86::VPERMPSZrr,         X86::VPERMPSZrr,         X86::VPERMDZrr },
6087   { X86::VPERMPDZmi,         X86::VPERMPDZmi,         X86::VPERMQZmi },
6088   { X86::VPERMPDZri,         X86::VPERMPDZri,         X86::VPERMQZri },
6089   { X86::VPERMPDZrm,         X86::VPERMPDZrm,         X86::VPERMQZrm },
6090   { X86::VPERMPDZrr,         X86::VPERMPDZrr,         X86::VPERMQZrr },
6091   { X86::VUNPCKLPDZ256rm,    X86::VUNPCKLPDZ256rm,    X86::VPUNPCKLQDQZ256rm },
6092   { X86::VUNPCKLPDZ256rr,    X86::VUNPCKLPDZ256rr,    X86::VPUNPCKLQDQZ256rr },
6093   { X86::VUNPCKHPDZ256rm,    X86::VUNPCKHPDZ256rm,    X86::VPUNPCKHQDQZ256rm },
6094   { X86::VUNPCKHPDZ256rr,    X86::VUNPCKHPDZ256rr,    X86::VPUNPCKHQDQZ256rr },
6095   { X86::VUNPCKLPSZ256rm,    X86::VUNPCKLPSZ256rm,    X86::VPUNPCKLDQZ256rm },
6096   { X86::VUNPCKLPSZ256rr,    X86::VUNPCKLPSZ256rr,    X86::VPUNPCKLDQZ256rr },
6097   { X86::VUNPCKHPSZ256rm,    X86::VUNPCKHPSZ256rm,    X86::VPUNPCKHDQZ256rm },
6098   { X86::VUNPCKHPSZ256rr,    X86::VUNPCKHPSZ256rr,    X86::VPUNPCKHDQZ256rr },
6099   { X86::VUNPCKLPDZ128rm,    X86::VUNPCKLPDZ128rm,    X86::VPUNPCKLQDQZ128rm },
6100   { X86::VMOVLHPSZrr,        X86::VUNPCKLPDZ128rr,    X86::VPUNPCKLQDQZ128rr },
6101   { X86::VUNPCKHPDZ128rm,    X86::VUNPCKHPDZ128rm,    X86::VPUNPCKHQDQZ128rm },
6102   { X86::VUNPCKHPDZ128rr,    X86::VUNPCKHPDZ128rr,    X86::VPUNPCKHQDQZ128rr },
6103   { X86::VUNPCKLPSZ128rm,    X86::VUNPCKLPSZ128rm,    X86::VPUNPCKLDQZ128rm },
6104   { X86::VUNPCKLPSZ128rr,    X86::VUNPCKLPSZ128rr,    X86::VPUNPCKLDQZ128rr },
6105   { X86::VUNPCKHPSZ128rm,    X86::VUNPCKHPSZ128rm,    X86::VPUNPCKHDQZ128rm },
6106   { X86::VUNPCKHPSZ128rr,    X86::VUNPCKHPSZ128rr,    X86::VPUNPCKHDQZ128rr },
6107   { X86::VUNPCKLPDZrm,       X86::VUNPCKLPDZrm,       X86::VPUNPCKLQDQZrm },
6108   { X86::VUNPCKLPDZrr,       X86::VUNPCKLPDZrr,       X86::VPUNPCKLQDQZrr },
6109   { X86::VUNPCKHPDZrm,       X86::VUNPCKHPDZrm,       X86::VPUNPCKHQDQZrm },
6110   { X86::VUNPCKHPDZrr,       X86::VUNPCKHPDZrr,       X86::VPUNPCKHQDQZrr },
6111   { X86::VUNPCKLPSZrm,       X86::VUNPCKLPSZrm,       X86::VPUNPCKLDQZrm },
6112   { X86::VUNPCKLPSZrr,       X86::VUNPCKLPSZrr,       X86::VPUNPCKLDQZrr },
6113   { X86::VUNPCKHPSZrm,       X86::VUNPCKHPSZrm,       X86::VPUNPCKHDQZrm },
6114   { X86::VUNPCKHPSZrr,       X86::VUNPCKHPSZrr,       X86::VPUNPCKHDQZrr },
6115   { X86::VEXTRACTPSZmr,      X86::VEXTRACTPSZmr,      X86::VPEXTRDZmr },
6116   { X86::VEXTRACTPSZrr,      X86::VEXTRACTPSZrr,      X86::VPEXTRDZrr },
6117 };
6118 
6119 static const uint16_t ReplaceableInstrsAVX2[][3] = {
6120   //PackedSingle       PackedDouble       PackedInt
6121   { X86::VANDNPSYrm,   X86::VANDNPDYrm,   X86::VPANDNYrm   },
6122   { X86::VANDNPSYrr,   X86::VANDNPDYrr,   X86::VPANDNYrr   },
6123   { X86::VANDPSYrm,    X86::VANDPDYrm,    X86::VPANDYrm    },
6124   { X86::VANDPSYrr,    X86::VANDPDYrr,    X86::VPANDYrr    },
6125   { X86::VORPSYrm,     X86::VORPDYrm,     X86::VPORYrm     },
6126   { X86::VORPSYrr,     X86::VORPDYrr,     X86::VPORYrr     },
6127   { X86::VXORPSYrm,    X86::VXORPDYrm,    X86::VPXORYrm    },
6128   { X86::VXORPSYrr,    X86::VXORPDYrr,    X86::VPXORYrr    },
6129   { X86::VPERM2F128rm,   X86::VPERM2F128rm,   X86::VPERM2I128rm },
6130   { X86::VPERM2F128rr,   X86::VPERM2F128rr,   X86::VPERM2I128rr },
6131   { X86::VBROADCASTSSrm, X86::VBROADCASTSSrm, X86::VPBROADCASTDrm},
6132   { X86::VBROADCASTSSrr, X86::VBROADCASTSSrr, X86::VPBROADCASTDrr},
6133   { X86::VBROADCASTSSYrr, X86::VBROADCASTSSYrr, X86::VPBROADCASTDYrr},
6134   { X86::VBROADCASTSSYrm, X86::VBROADCASTSSYrm, X86::VPBROADCASTDYrm},
6135   { X86::VBROADCASTSDYrr, X86::VBROADCASTSDYrr, X86::VPBROADCASTQYrr},
6136   { X86::VBROADCASTSDYrm, X86::VBROADCASTSDYrm, X86::VPBROADCASTQYrm},
6137   { X86::VBROADCASTF128,  X86::VBROADCASTF128,  X86::VBROADCASTI128 },
6138   { X86::VBLENDPSYrri,    X86::VBLENDPSYrri,    X86::VPBLENDDYrri },
6139   { X86::VBLENDPSYrmi,    X86::VBLENDPSYrmi,    X86::VPBLENDDYrmi },
6140   { X86::VPERMILPSYmi,    X86::VPERMILPSYmi,    X86::VPSHUFDYmi },
6141   { X86::VPERMILPSYri,    X86::VPERMILPSYri,    X86::VPSHUFDYri },
6142   { X86::VUNPCKLPDYrm,    X86::VUNPCKLPDYrm,    X86::VPUNPCKLQDQYrm },
6143   { X86::VUNPCKLPDYrr,    X86::VUNPCKLPDYrr,    X86::VPUNPCKLQDQYrr },
6144   { X86::VUNPCKHPDYrm,    X86::VUNPCKHPDYrm,    X86::VPUNPCKHQDQYrm },
6145   { X86::VUNPCKHPDYrr,    X86::VUNPCKHPDYrr,    X86::VPUNPCKHQDQYrr },
6146   { X86::VUNPCKLPSYrm,    X86::VUNPCKLPSYrm,    X86::VPUNPCKLDQYrm },
6147   { X86::VUNPCKLPSYrr,    X86::VUNPCKLPSYrr,    X86::VPUNPCKLDQYrr },
6148   { X86::VUNPCKHPSYrm,    X86::VUNPCKHPSYrm,    X86::VPUNPCKHDQYrm },
6149   { X86::VUNPCKHPSYrr,    X86::VUNPCKHPSYrr,    X86::VPUNPCKHDQYrr },
6150 };
6151 
6152 static const uint16_t ReplaceableInstrsAVX2InsertExtract[][3] = {
6153   //PackedSingle       PackedDouble       PackedInt
6154   { X86::VEXTRACTF128mr, X86::VEXTRACTF128mr, X86::VEXTRACTI128mr },
6155   { X86::VEXTRACTF128rr, X86::VEXTRACTF128rr, X86::VEXTRACTI128rr },
6156   { X86::VINSERTF128rm,  X86::VINSERTF128rm,  X86::VINSERTI128rm },
6157   { X86::VINSERTF128rr,  X86::VINSERTF128rr,  X86::VINSERTI128rr },
6158 };
6159 
6160 static const uint16_t ReplaceableInstrsAVX512[][4] = {
6161   // Two integer columns for 64-bit and 32-bit elements.
6162   //PackedSingle        PackedDouble        PackedInt             PackedInt
6163   { X86::VMOVAPSZ128mr, X86::VMOVAPDZ128mr, X86::VMOVDQA64Z128mr, X86::VMOVDQA32Z128mr  },
6164   { X86::VMOVAPSZ128rm, X86::VMOVAPDZ128rm, X86::VMOVDQA64Z128rm, X86::VMOVDQA32Z128rm  },
6165   { X86::VMOVAPSZ128rr, X86::VMOVAPDZ128rr, X86::VMOVDQA64Z128rr, X86::VMOVDQA32Z128rr  },
6166   { X86::VMOVUPSZ128mr, X86::VMOVUPDZ128mr, X86::VMOVDQU64Z128mr, X86::VMOVDQU32Z128mr  },
6167   { X86::VMOVUPSZ128rm, X86::VMOVUPDZ128rm, X86::VMOVDQU64Z128rm, X86::VMOVDQU32Z128rm  },
6168   { X86::VMOVAPSZ256mr, X86::VMOVAPDZ256mr, X86::VMOVDQA64Z256mr, X86::VMOVDQA32Z256mr  },
6169   { X86::VMOVAPSZ256rm, X86::VMOVAPDZ256rm, X86::VMOVDQA64Z256rm, X86::VMOVDQA32Z256rm  },
6170   { X86::VMOVAPSZ256rr, X86::VMOVAPDZ256rr, X86::VMOVDQA64Z256rr, X86::VMOVDQA32Z256rr  },
6171   { X86::VMOVUPSZ256mr, X86::VMOVUPDZ256mr, X86::VMOVDQU64Z256mr, X86::VMOVDQU32Z256mr  },
6172   { X86::VMOVUPSZ256rm, X86::VMOVUPDZ256rm, X86::VMOVDQU64Z256rm, X86::VMOVDQU32Z256rm  },
6173   { X86::VMOVAPSZmr,    X86::VMOVAPDZmr,    X86::VMOVDQA64Zmr,    X86::VMOVDQA32Zmr     },
6174   { X86::VMOVAPSZrm,    X86::VMOVAPDZrm,    X86::VMOVDQA64Zrm,    X86::VMOVDQA32Zrm     },
6175   { X86::VMOVAPSZrr,    X86::VMOVAPDZrr,    X86::VMOVDQA64Zrr,    X86::VMOVDQA32Zrr     },
6176   { X86::VMOVUPSZmr,    X86::VMOVUPDZmr,    X86::VMOVDQU64Zmr,    X86::VMOVDQU32Zmr     },
6177   { X86::VMOVUPSZrm,    X86::VMOVUPDZrm,    X86::VMOVDQU64Zrm,    X86::VMOVDQU32Zrm     },
6178 };
6179 
6180 static const uint16_t ReplaceableInstrsAVX512DQ[][4] = {
6181   // Two integer columns for 64-bit and 32-bit elements.
6182   //PackedSingle        PackedDouble        PackedInt           PackedInt
6183   { X86::VANDNPSZ128rm, X86::VANDNPDZ128rm, X86::VPANDNQZ128rm, X86::VPANDNDZ128rm },
6184   { X86::VANDNPSZ128rr, X86::VANDNPDZ128rr, X86::VPANDNQZ128rr, X86::VPANDNDZ128rr },
6185   { X86::VANDPSZ128rm,  X86::VANDPDZ128rm,  X86::VPANDQZ128rm,  X86::VPANDDZ128rm  },
6186   { X86::VANDPSZ128rr,  X86::VANDPDZ128rr,  X86::VPANDQZ128rr,  X86::VPANDDZ128rr  },
6187   { X86::VORPSZ128rm,   X86::VORPDZ128rm,   X86::VPORQZ128rm,   X86::VPORDZ128rm   },
6188   { X86::VORPSZ128rr,   X86::VORPDZ128rr,   X86::VPORQZ128rr,   X86::VPORDZ128rr   },
6189   { X86::VXORPSZ128rm,  X86::VXORPDZ128rm,  X86::VPXORQZ128rm,  X86::VPXORDZ128rm  },
6190   { X86::VXORPSZ128rr,  X86::VXORPDZ128rr,  X86::VPXORQZ128rr,  X86::VPXORDZ128rr  },
6191   { X86::VANDNPSZ256rm, X86::VANDNPDZ256rm, X86::VPANDNQZ256rm, X86::VPANDNDZ256rm },
6192   { X86::VANDNPSZ256rr, X86::VANDNPDZ256rr, X86::VPANDNQZ256rr, X86::VPANDNDZ256rr },
6193   { X86::VANDPSZ256rm,  X86::VANDPDZ256rm,  X86::VPANDQZ256rm,  X86::VPANDDZ256rm  },
6194   { X86::VANDPSZ256rr,  X86::VANDPDZ256rr,  X86::VPANDQZ256rr,  X86::VPANDDZ256rr  },
6195   { X86::VORPSZ256rm,   X86::VORPDZ256rm,   X86::VPORQZ256rm,   X86::VPORDZ256rm   },
6196   { X86::VORPSZ256rr,   X86::VORPDZ256rr,   X86::VPORQZ256rr,   X86::VPORDZ256rr   },
6197   { X86::VXORPSZ256rm,  X86::VXORPDZ256rm,  X86::VPXORQZ256rm,  X86::VPXORDZ256rm  },
6198   { X86::VXORPSZ256rr,  X86::VXORPDZ256rr,  X86::VPXORQZ256rr,  X86::VPXORDZ256rr  },
6199   { X86::VANDNPSZrm,    X86::VANDNPDZrm,    X86::VPANDNQZrm,    X86::VPANDNDZrm    },
6200   { X86::VANDNPSZrr,    X86::VANDNPDZrr,    X86::VPANDNQZrr,    X86::VPANDNDZrr    },
6201   { X86::VANDPSZrm,     X86::VANDPDZrm,     X86::VPANDQZrm,     X86::VPANDDZrm     },
6202   { X86::VANDPSZrr,     X86::VANDPDZrr,     X86::VPANDQZrr,     X86::VPANDDZrr     },
6203   { X86::VORPSZrm,      X86::VORPDZrm,      X86::VPORQZrm,      X86::VPORDZrm      },
6204   { X86::VORPSZrr,      X86::VORPDZrr,      X86::VPORQZrr,      X86::VPORDZrr      },
6205   { X86::VXORPSZrm,     X86::VXORPDZrm,     X86::VPXORQZrm,     X86::VPXORDZrm     },
6206   { X86::VXORPSZrr,     X86::VXORPDZrr,     X86::VPXORQZrr,     X86::VPXORDZrr     },
6207 };
6208 
6209 static const uint16_t ReplaceableInstrsAVX512DQMasked[][4] = {
6210   // Two integer columns for 64-bit and 32-bit elements.
6211   //PackedSingle          PackedDouble
6212   //PackedInt             PackedInt
6213   { X86::VANDNPSZ128rmk,  X86::VANDNPDZ128rmk,
6214     X86::VPANDNQZ128rmk,  X86::VPANDNDZ128rmk  },
6215   { X86::VANDNPSZ128rmkz, X86::VANDNPDZ128rmkz,
6216     X86::VPANDNQZ128rmkz, X86::VPANDNDZ128rmkz },
6217   { X86::VANDNPSZ128rrk,  X86::VANDNPDZ128rrk,
6218     X86::VPANDNQZ128rrk,  X86::VPANDNDZ128rrk  },
6219   { X86::VANDNPSZ128rrkz, X86::VANDNPDZ128rrkz,
6220     X86::VPANDNQZ128rrkz, X86::VPANDNDZ128rrkz },
6221   { X86::VANDPSZ128rmk,   X86::VANDPDZ128rmk,
6222     X86::VPANDQZ128rmk,   X86::VPANDDZ128rmk   },
6223   { X86::VANDPSZ128rmkz,  X86::VANDPDZ128rmkz,
6224     X86::VPANDQZ128rmkz,  X86::VPANDDZ128rmkz  },
6225   { X86::VANDPSZ128rrk,   X86::VANDPDZ128rrk,
6226     X86::VPANDQZ128rrk,   X86::VPANDDZ128rrk   },
6227   { X86::VANDPSZ128rrkz,  X86::VANDPDZ128rrkz,
6228     X86::VPANDQZ128rrkz,  X86::VPANDDZ128rrkz  },
6229   { X86::VORPSZ128rmk,    X86::VORPDZ128rmk,
6230     X86::VPORQZ128rmk,    X86::VPORDZ128rmk    },
6231   { X86::VORPSZ128rmkz,   X86::VORPDZ128rmkz,
6232     X86::VPORQZ128rmkz,   X86::VPORDZ128rmkz   },
6233   { X86::VORPSZ128rrk,    X86::VORPDZ128rrk,
6234     X86::VPORQZ128rrk,    X86::VPORDZ128rrk    },
6235   { X86::VORPSZ128rrkz,   X86::VORPDZ128rrkz,
6236     X86::VPORQZ128rrkz,   X86::VPORDZ128rrkz   },
6237   { X86::VXORPSZ128rmk,   X86::VXORPDZ128rmk,
6238     X86::VPXORQZ128rmk,   X86::VPXORDZ128rmk   },
6239   { X86::VXORPSZ128rmkz,  X86::VXORPDZ128rmkz,
6240     X86::VPXORQZ128rmkz,  X86::VPXORDZ128rmkz  },
6241   { X86::VXORPSZ128rrk,   X86::VXORPDZ128rrk,
6242     X86::VPXORQZ128rrk,   X86::VPXORDZ128rrk   },
6243   { X86::VXORPSZ128rrkz,  X86::VXORPDZ128rrkz,
6244     X86::VPXORQZ128rrkz,  X86::VPXORDZ128rrkz  },
6245   { X86::VANDNPSZ256rmk,  X86::VANDNPDZ256rmk,
6246     X86::VPANDNQZ256rmk,  X86::VPANDNDZ256rmk  },
6247   { X86::VANDNPSZ256rmkz, X86::VANDNPDZ256rmkz,
6248     X86::VPANDNQZ256rmkz, X86::VPANDNDZ256rmkz },
6249   { X86::VANDNPSZ256rrk,  X86::VANDNPDZ256rrk,
6250     X86::VPANDNQZ256rrk,  X86::VPANDNDZ256rrk  },
6251   { X86::VANDNPSZ256rrkz, X86::VANDNPDZ256rrkz,
6252     X86::VPANDNQZ256rrkz, X86::VPANDNDZ256rrkz },
6253   { X86::VANDPSZ256rmk,   X86::VANDPDZ256rmk,
6254     X86::VPANDQZ256rmk,   X86::VPANDDZ256rmk   },
6255   { X86::VANDPSZ256rmkz,  X86::VANDPDZ256rmkz,
6256     X86::VPANDQZ256rmkz,  X86::VPANDDZ256rmkz  },
6257   { X86::VANDPSZ256rrk,   X86::VANDPDZ256rrk,
6258     X86::VPANDQZ256rrk,   X86::VPANDDZ256rrk   },
6259   { X86::VANDPSZ256rrkz,  X86::VANDPDZ256rrkz,
6260     X86::VPANDQZ256rrkz,  X86::VPANDDZ256rrkz  },
6261   { X86::VORPSZ256rmk,    X86::VORPDZ256rmk,
6262     X86::VPORQZ256rmk,    X86::VPORDZ256rmk    },
6263   { X86::VORPSZ256rmkz,   X86::VORPDZ256rmkz,
6264     X86::VPORQZ256rmkz,   X86::VPORDZ256rmkz   },
6265   { X86::VORPSZ256rrk,    X86::VORPDZ256rrk,
6266     X86::VPORQZ256rrk,    X86::VPORDZ256rrk    },
6267   { X86::VORPSZ256rrkz,   X86::VORPDZ256rrkz,
6268     X86::VPORQZ256rrkz,   X86::VPORDZ256rrkz   },
6269   { X86::VXORPSZ256rmk,   X86::VXORPDZ256rmk,
6270     X86::VPXORQZ256rmk,   X86::VPXORDZ256rmk   },
6271   { X86::VXORPSZ256rmkz,  X86::VXORPDZ256rmkz,
6272     X86::VPXORQZ256rmkz,  X86::VPXORDZ256rmkz  },
6273   { X86::VXORPSZ256rrk,   X86::VXORPDZ256rrk,
6274     X86::VPXORQZ256rrk,   X86::VPXORDZ256rrk   },
6275   { X86::VXORPSZ256rrkz,  X86::VXORPDZ256rrkz,
6276     X86::VPXORQZ256rrkz,  X86::VPXORDZ256rrkz  },
6277   { X86::VANDNPSZrmk,     X86::VANDNPDZrmk,
6278     X86::VPANDNQZrmk,     X86::VPANDNDZrmk     },
6279   { X86::VANDNPSZrmkz,    X86::VANDNPDZrmkz,
6280     X86::VPANDNQZrmkz,    X86::VPANDNDZrmkz    },
6281   { X86::VANDNPSZrrk,     X86::VANDNPDZrrk,
6282     X86::VPANDNQZrrk,     X86::VPANDNDZrrk     },
6283   { X86::VANDNPSZrrkz,    X86::VANDNPDZrrkz,
6284     X86::VPANDNQZrrkz,    X86::VPANDNDZrrkz    },
6285   { X86::VANDPSZrmk,      X86::VANDPDZrmk,
6286     X86::VPANDQZrmk,      X86::VPANDDZrmk      },
6287   { X86::VANDPSZrmkz,     X86::VANDPDZrmkz,
6288     X86::VPANDQZrmkz,     X86::VPANDDZrmkz     },
6289   { X86::VANDPSZrrk,      X86::VANDPDZrrk,
6290     X86::VPANDQZrrk,      X86::VPANDDZrrk      },
6291   { X86::VANDPSZrrkz,     X86::VANDPDZrrkz,
6292     X86::VPANDQZrrkz,     X86::VPANDDZrrkz     },
6293   { X86::VORPSZrmk,       X86::VORPDZrmk,
6294     X86::VPORQZrmk,       X86::VPORDZrmk       },
6295   { X86::VORPSZrmkz,      X86::VORPDZrmkz,
6296     X86::VPORQZrmkz,      X86::VPORDZrmkz      },
6297   { X86::VORPSZrrk,       X86::VORPDZrrk,
6298     X86::VPORQZrrk,       X86::VPORDZrrk       },
6299   { X86::VORPSZrrkz,      X86::VORPDZrrkz,
6300     X86::VPORQZrrkz,      X86::VPORDZrrkz      },
6301   { X86::VXORPSZrmk,      X86::VXORPDZrmk,
6302     X86::VPXORQZrmk,      X86::VPXORDZrmk      },
6303   { X86::VXORPSZrmkz,     X86::VXORPDZrmkz,
6304     X86::VPXORQZrmkz,     X86::VPXORDZrmkz     },
6305   { X86::VXORPSZrrk,      X86::VXORPDZrrk,
6306     X86::VPXORQZrrk,      X86::VPXORDZrrk      },
6307   { X86::VXORPSZrrkz,     X86::VXORPDZrrkz,
6308     X86::VPXORQZrrkz,     X86::VPXORDZrrkz     },
6309   // Broadcast loads can be handled the same as masked operations to avoid
6310   // changing element size.
6311   { X86::VANDNPSZ128rmb,  X86::VANDNPDZ128rmb,
6312     X86::VPANDNQZ128rmb,  X86::VPANDNDZ128rmb  },
6313   { X86::VANDPSZ128rmb,   X86::VANDPDZ128rmb,
6314     X86::VPANDQZ128rmb,   X86::VPANDDZ128rmb   },
6315   { X86::VORPSZ128rmb,    X86::VORPDZ128rmb,
6316     X86::VPORQZ128rmb,    X86::VPORDZ128rmb    },
6317   { X86::VXORPSZ128rmb,   X86::VXORPDZ128rmb,
6318     X86::VPXORQZ128rmb,   X86::VPXORDZ128rmb   },
6319   { X86::VANDNPSZ256rmb,  X86::VANDNPDZ256rmb,
6320     X86::VPANDNQZ256rmb,  X86::VPANDNDZ256rmb  },
6321   { X86::VANDPSZ256rmb,   X86::VANDPDZ256rmb,
6322     X86::VPANDQZ256rmb,   X86::VPANDDZ256rmb   },
6323   { X86::VORPSZ256rmb,    X86::VORPDZ256rmb,
6324     X86::VPORQZ256rmb,    X86::VPORDZ256rmb    },
6325   { X86::VXORPSZ256rmb,   X86::VXORPDZ256rmb,
6326     X86::VPXORQZ256rmb,   X86::VPXORDZ256rmb   },
6327   { X86::VANDNPSZrmb,     X86::VANDNPDZrmb,
6328     X86::VPANDNQZrmb,     X86::VPANDNDZrmb     },
6329   { X86::VANDPSZrmb,      X86::VANDPDZrmb,
6330     X86::VPANDQZrmb,      X86::VPANDDZrmb      },
6331   { X86::VANDPSZrmb,      X86::VANDPDZrmb,
6332     X86::VPANDQZrmb,      X86::VPANDDZrmb      },
6333   { X86::VORPSZrmb,       X86::VORPDZrmb,
6334     X86::VPORQZrmb,       X86::VPORDZrmb       },
6335   { X86::VXORPSZrmb,      X86::VXORPDZrmb,
6336     X86::VPXORQZrmb,      X86::VPXORDZrmb      },
6337   { X86::VANDNPSZ128rmbk, X86::VANDNPDZ128rmbk,
6338     X86::VPANDNQZ128rmbk, X86::VPANDNDZ128rmbk },
6339   { X86::VANDPSZ128rmbk,  X86::VANDPDZ128rmbk,
6340     X86::VPANDQZ128rmbk,  X86::VPANDDZ128rmbk  },
6341   { X86::VORPSZ128rmbk,   X86::VORPDZ128rmbk,
6342     X86::VPORQZ128rmbk,   X86::VPORDZ128rmbk   },
6343   { X86::VXORPSZ128rmbk,  X86::VXORPDZ128rmbk,
6344     X86::VPXORQZ128rmbk,  X86::VPXORDZ128rmbk  },
6345   { X86::VANDNPSZ256rmbk, X86::VANDNPDZ256rmbk,
6346     X86::VPANDNQZ256rmbk, X86::VPANDNDZ256rmbk },
6347   { X86::VANDPSZ256rmbk,  X86::VANDPDZ256rmbk,
6348     X86::VPANDQZ256rmbk,  X86::VPANDDZ256rmbk  },
6349   { X86::VORPSZ256rmbk,   X86::VORPDZ256rmbk,
6350     X86::VPORQZ256rmbk,   X86::VPORDZ256rmbk   },
6351   { X86::VXORPSZ256rmbk,  X86::VXORPDZ256rmbk,
6352     X86::VPXORQZ256rmbk,  X86::VPXORDZ256rmbk  },
6353   { X86::VANDNPSZrmbk,    X86::VANDNPDZrmbk,
6354     X86::VPANDNQZrmbk,    X86::VPANDNDZrmbk    },
6355   { X86::VANDPSZrmbk,     X86::VANDPDZrmbk,
6356     X86::VPANDQZrmbk,     X86::VPANDDZrmbk     },
6357   { X86::VANDPSZrmbk,     X86::VANDPDZrmbk,
6358     X86::VPANDQZrmbk,     X86::VPANDDZrmbk     },
6359   { X86::VORPSZrmbk,      X86::VORPDZrmbk,
6360     X86::VPORQZrmbk,      X86::VPORDZrmbk      },
6361   { X86::VXORPSZrmbk,     X86::VXORPDZrmbk,
6362     X86::VPXORQZrmbk,     X86::VPXORDZrmbk     },
6363   { X86::VANDNPSZ128rmbkz,X86::VANDNPDZ128rmbkz,
6364     X86::VPANDNQZ128rmbkz,X86::VPANDNDZ128rmbkz},
6365   { X86::VANDPSZ128rmbkz, X86::VANDPDZ128rmbkz,
6366     X86::VPANDQZ128rmbkz, X86::VPANDDZ128rmbkz },
6367   { X86::VORPSZ128rmbkz,  X86::VORPDZ128rmbkz,
6368     X86::VPORQZ128rmbkz,  X86::VPORDZ128rmbkz  },
6369   { X86::VXORPSZ128rmbkz, X86::VXORPDZ128rmbkz,
6370     X86::VPXORQZ128rmbkz, X86::VPXORDZ128rmbkz },
6371   { X86::VANDNPSZ256rmbkz,X86::VANDNPDZ256rmbkz,
6372     X86::VPANDNQZ256rmbkz,X86::VPANDNDZ256rmbkz},
6373   { X86::VANDPSZ256rmbkz, X86::VANDPDZ256rmbkz,
6374     X86::VPANDQZ256rmbkz, X86::VPANDDZ256rmbkz },
6375   { X86::VORPSZ256rmbkz,  X86::VORPDZ256rmbkz,
6376     X86::VPORQZ256rmbkz,  X86::VPORDZ256rmbkz  },
6377   { X86::VXORPSZ256rmbkz, X86::VXORPDZ256rmbkz,
6378     X86::VPXORQZ256rmbkz, X86::VPXORDZ256rmbkz },
6379   { X86::VANDNPSZrmbkz,   X86::VANDNPDZrmbkz,
6380     X86::VPANDNQZrmbkz,   X86::VPANDNDZrmbkz   },
6381   { X86::VANDPSZrmbkz,    X86::VANDPDZrmbkz,
6382     X86::VPANDQZrmbkz,    X86::VPANDDZrmbkz    },
6383   { X86::VANDPSZrmbkz,    X86::VANDPDZrmbkz,
6384     X86::VPANDQZrmbkz,    X86::VPANDDZrmbkz    },
6385   { X86::VORPSZrmbkz,     X86::VORPDZrmbkz,
6386     X86::VPORQZrmbkz,     X86::VPORDZrmbkz     },
6387   { X86::VXORPSZrmbkz,    X86::VXORPDZrmbkz,
6388     X86::VPXORQZrmbkz,    X86::VPXORDZrmbkz    },
6389 };
6390 
6391 // NOTE: These should only be used by the custom domain methods.
6392 static const uint16_t ReplaceableCustomInstrs[][3] = {
6393   //PackedSingle             PackedDouble             PackedInt
6394   { X86::BLENDPSrmi,         X86::BLENDPDrmi,         X86::PBLENDWrmi   },
6395   { X86::BLENDPSrri,         X86::BLENDPDrri,         X86::PBLENDWrri   },
6396   { X86::VBLENDPSrmi,        X86::VBLENDPDrmi,        X86::VPBLENDWrmi  },
6397   { X86::VBLENDPSrri,        X86::VBLENDPDrri,        X86::VPBLENDWrri  },
6398   { X86::VBLENDPSYrmi,       X86::VBLENDPDYrmi,       X86::VPBLENDWYrmi },
6399   { X86::VBLENDPSYrri,       X86::VBLENDPDYrri,       X86::VPBLENDWYrri },
6400 };
6401 static const uint16_t ReplaceableCustomAVX2Instrs[][3] = {
6402   //PackedSingle             PackedDouble             PackedInt
6403   { X86::VBLENDPSrmi,        X86::VBLENDPDrmi,        X86::VPBLENDDrmi  },
6404   { X86::VBLENDPSrri,        X86::VBLENDPDrri,        X86::VPBLENDDrri  },
6405   { X86::VBLENDPSYrmi,       X86::VBLENDPDYrmi,       X86::VPBLENDDYrmi },
6406   { X86::VBLENDPSYrri,       X86::VBLENDPDYrri,       X86::VPBLENDDYrri },
6407 };
6408 
6409 // Special table for changing EVEX logic instructions to VEX.
6410 // TODO: Should we run EVEX->VEX earlier?
6411 static const uint16_t ReplaceableCustomAVX512LogicInstrs[][4] = {
6412   // Two integer columns for 64-bit and 32-bit elements.
6413   //PackedSingle     PackedDouble     PackedInt           PackedInt
6414   { X86::VANDNPSrm,  X86::VANDNPDrm,  X86::VPANDNQZ128rm, X86::VPANDNDZ128rm },
6415   { X86::VANDNPSrr,  X86::VANDNPDrr,  X86::VPANDNQZ128rr, X86::VPANDNDZ128rr },
6416   { X86::VANDPSrm,   X86::VANDPDrm,   X86::VPANDQZ128rm,  X86::VPANDDZ128rm  },
6417   { X86::VANDPSrr,   X86::VANDPDrr,   X86::VPANDQZ128rr,  X86::VPANDDZ128rr  },
6418   { X86::VORPSrm,    X86::VORPDrm,    X86::VPORQZ128rm,   X86::VPORDZ128rm   },
6419   { X86::VORPSrr,    X86::VORPDrr,    X86::VPORQZ128rr,   X86::VPORDZ128rr   },
6420   { X86::VXORPSrm,   X86::VXORPDrm,   X86::VPXORQZ128rm,  X86::VPXORDZ128rm  },
6421   { X86::VXORPSrr,   X86::VXORPDrr,   X86::VPXORQZ128rr,  X86::VPXORDZ128rr  },
6422   { X86::VANDNPSYrm, X86::VANDNPDYrm, X86::VPANDNQZ256rm, X86::VPANDNDZ256rm },
6423   { X86::VANDNPSYrr, X86::VANDNPDYrr, X86::VPANDNQZ256rr, X86::VPANDNDZ256rr },
6424   { X86::VANDPSYrm,  X86::VANDPDYrm,  X86::VPANDQZ256rm,  X86::VPANDDZ256rm  },
6425   { X86::VANDPSYrr,  X86::VANDPDYrr,  X86::VPANDQZ256rr,  X86::VPANDDZ256rr  },
6426   { X86::VORPSYrm,   X86::VORPDYrm,   X86::VPORQZ256rm,   X86::VPORDZ256rm   },
6427   { X86::VORPSYrr,   X86::VORPDYrr,   X86::VPORQZ256rr,   X86::VPORDZ256rr   },
6428   { X86::VXORPSYrm,  X86::VXORPDYrm,  X86::VPXORQZ256rm,  X86::VPXORDZ256rm  },
6429   { X86::VXORPSYrr,  X86::VXORPDYrr,  X86::VPXORQZ256rr,  X86::VPXORDZ256rr  },
6430 };
6431 
6432 // FIXME: Some shuffle and unpack instructions have equivalents in different
6433 // domains, but they require a bit more work than just switching opcodes.
6434 
6435 static const uint16_t *lookup(unsigned opcode, unsigned domain,
6436                               ArrayRef<uint16_t[3]> Table) {
6437   for (const uint16_t (&Row)[3] : Table)
6438     if (Row[domain-1] == opcode)
6439       return Row;
6440   return nullptr;
6441 }
6442 
6443 static const uint16_t *lookupAVX512(unsigned opcode, unsigned domain,
6444                                     ArrayRef<uint16_t[4]> Table) {
6445   // If this is the integer domain make sure to check both integer columns.
6446   for (const uint16_t (&Row)[4] : Table)
6447     if (Row[domain-1] == opcode || (domain == 3 && Row[3] == opcode))
6448       return Row;
6449   return nullptr;
6450 }
6451 
6452 // Helper to attempt to widen/narrow blend masks.
6453 static bool AdjustBlendMask(unsigned OldMask, unsigned OldWidth,
6454                             unsigned NewWidth, unsigned *pNewMask = nullptr) {
6455   assert(((OldWidth % NewWidth) == 0 || (NewWidth % OldWidth) == 0) &&
6456          "Illegal blend mask scale");
6457   unsigned NewMask = 0;
6458 
6459   if ((OldWidth % NewWidth) == 0) {
6460     unsigned Scale = OldWidth / NewWidth;
6461     unsigned SubMask = (1u << Scale) - 1;
6462     for (unsigned i = 0; i != NewWidth; ++i) {
6463       unsigned Sub = (OldMask >> (i * Scale)) & SubMask;
6464       if (Sub == SubMask)
6465         NewMask |= (1u << i);
6466       else if (Sub != 0x0)
6467         return false;
6468     }
6469   } else {
6470     unsigned Scale = NewWidth / OldWidth;
6471     unsigned SubMask = (1u << Scale) - 1;
6472     for (unsigned i = 0; i != OldWidth; ++i) {
6473       if (OldMask & (1 << i)) {
6474         NewMask |= (SubMask << (i * Scale));
6475       }
6476     }
6477   }
6478 
6479   if (pNewMask)
6480     *pNewMask = NewMask;
6481   return true;
6482 }
6483 
6484 uint16_t X86InstrInfo::getExecutionDomainCustom(const MachineInstr &MI) const {
6485   unsigned Opcode = MI.getOpcode();
6486   unsigned NumOperands = MI.getDesc().getNumOperands();
6487 
6488   auto GetBlendDomains = [&](unsigned ImmWidth, bool Is256) {
6489     uint16_t validDomains = 0;
6490     if (MI.getOperand(NumOperands - 1).isImm()) {
6491       unsigned Imm = MI.getOperand(NumOperands - 1).getImm();
6492       if (AdjustBlendMask(Imm, ImmWidth, Is256 ? 8 : 4))
6493         validDomains |= 0x2; // PackedSingle
6494       if (AdjustBlendMask(Imm, ImmWidth, Is256 ? 4 : 2))
6495         validDomains |= 0x4; // PackedDouble
6496       if (!Is256 || Subtarget.hasAVX2())
6497         validDomains |= 0x8; // PackedInt
6498     }
6499     return validDomains;
6500   };
6501 
6502   switch (Opcode) {
6503   case X86::BLENDPDrmi:
6504   case X86::BLENDPDrri:
6505   case X86::VBLENDPDrmi:
6506   case X86::VBLENDPDrri:
6507     return GetBlendDomains(2, false);
6508   case X86::VBLENDPDYrmi:
6509   case X86::VBLENDPDYrri:
6510     return GetBlendDomains(4, true);
6511   case X86::BLENDPSrmi:
6512   case X86::BLENDPSrri:
6513   case X86::VBLENDPSrmi:
6514   case X86::VBLENDPSrri:
6515   case X86::VPBLENDDrmi:
6516   case X86::VPBLENDDrri:
6517     return GetBlendDomains(4, false);
6518   case X86::VBLENDPSYrmi:
6519   case X86::VBLENDPSYrri:
6520   case X86::VPBLENDDYrmi:
6521   case X86::VPBLENDDYrri:
6522     return GetBlendDomains(8, true);
6523   case X86::PBLENDWrmi:
6524   case X86::PBLENDWrri:
6525   case X86::VPBLENDWrmi:
6526   case X86::VPBLENDWrri:
6527   // Treat VPBLENDWY as a 128-bit vector as it repeats the lo/hi masks.
6528   case X86::VPBLENDWYrmi:
6529   case X86::VPBLENDWYrri:
6530     return GetBlendDomains(8, false);
6531   case X86::VPANDDZ128rr:  case X86::VPANDDZ128rm:
6532   case X86::VPANDDZ256rr:  case X86::VPANDDZ256rm:
6533   case X86::VPANDQZ128rr:  case X86::VPANDQZ128rm:
6534   case X86::VPANDQZ256rr:  case X86::VPANDQZ256rm:
6535   case X86::VPANDNDZ128rr: case X86::VPANDNDZ128rm:
6536   case X86::VPANDNDZ256rr: case X86::VPANDNDZ256rm:
6537   case X86::VPANDNQZ128rr: case X86::VPANDNQZ128rm:
6538   case X86::VPANDNQZ256rr: case X86::VPANDNQZ256rm:
6539   case X86::VPORDZ128rr:   case X86::VPORDZ128rm:
6540   case X86::VPORDZ256rr:   case X86::VPORDZ256rm:
6541   case X86::VPORQZ128rr:   case X86::VPORQZ128rm:
6542   case X86::VPORQZ256rr:   case X86::VPORQZ256rm:
6543   case X86::VPXORDZ128rr:  case X86::VPXORDZ128rm:
6544   case X86::VPXORDZ256rr:  case X86::VPXORDZ256rm:
6545   case X86::VPXORQZ128rr:  case X86::VPXORQZ128rm:
6546   case X86::VPXORQZ256rr:  case X86::VPXORQZ256rm:
6547     // If we don't have DQI see if we can still switch from an EVEX integer
6548     // instruction to a VEX floating point instruction.
6549     if (Subtarget.hasDQI())
6550       return 0;
6551 
6552     if (RI.getEncodingValue(MI.getOperand(0).getReg()) >= 16)
6553       return 0;
6554     if (RI.getEncodingValue(MI.getOperand(1).getReg()) >= 16)
6555       return 0;
6556     // Register forms will have 3 operands. Memory form will have more.
6557     if (NumOperands == 3 &&
6558         RI.getEncodingValue(MI.getOperand(2).getReg()) >= 16)
6559       return 0;
6560 
6561     // All domains are valid.
6562     return 0xe;
6563   case X86::MOVHLPSrr:
6564     // We can swap domains when both inputs are the same register.
6565     // FIXME: This doesn't catch all the cases we would like. If the input
6566     // register isn't KILLed by the instruction, the two address instruction
6567     // pass puts a COPY on one input. The other input uses the original
6568     // register. This prevents the same physical register from being used by
6569     // both inputs.
6570     if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg() &&
6571         MI.getOperand(0).getSubReg() == 0 &&
6572         MI.getOperand(1).getSubReg() == 0 &&
6573         MI.getOperand(2).getSubReg() == 0)
6574       return 0x6;
6575     return 0;
6576   }
6577   return 0;
6578 }
6579 
6580 bool X86InstrInfo::setExecutionDomainCustom(MachineInstr &MI,
6581                                             unsigned Domain) const {
6582   assert(Domain > 0 && Domain < 4 && "Invalid execution domain");
6583   uint16_t dom = (MI.getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
6584   assert(dom && "Not an SSE instruction");
6585 
6586   unsigned Opcode = MI.getOpcode();
6587   unsigned NumOperands = MI.getDesc().getNumOperands();
6588 
6589   auto SetBlendDomain = [&](unsigned ImmWidth, bool Is256) {
6590     if (MI.getOperand(NumOperands - 1).isImm()) {
6591       unsigned Imm = MI.getOperand(NumOperands - 1).getImm() & 255;
6592       Imm = (ImmWidth == 16 ? ((Imm << 8) | Imm) : Imm);
6593       unsigned NewImm = Imm;
6594 
6595       const uint16_t *table = lookup(Opcode, dom, ReplaceableCustomInstrs);
6596       if (!table)
6597         table = lookup(Opcode, dom, ReplaceableCustomAVX2Instrs);
6598 
6599       if (Domain == 1) { // PackedSingle
6600         AdjustBlendMask(Imm, ImmWidth, Is256 ? 8 : 4, &NewImm);
6601       } else if (Domain == 2) { // PackedDouble
6602         AdjustBlendMask(Imm, ImmWidth, Is256 ? 4 : 2, &NewImm);
6603       } else if (Domain == 3) { // PackedInt
6604         if (Subtarget.hasAVX2()) {
6605           // If we are already VPBLENDW use that, else use VPBLENDD.
6606           if ((ImmWidth / (Is256 ? 2 : 1)) != 8) {
6607             table = lookup(Opcode, dom, ReplaceableCustomAVX2Instrs);
6608             AdjustBlendMask(Imm, ImmWidth, Is256 ? 8 : 4, &NewImm);
6609           }
6610         } else {
6611           assert(!Is256 && "128-bit vector expected");
6612           AdjustBlendMask(Imm, ImmWidth, 8, &NewImm);
6613         }
6614       }
6615 
6616       assert(table && table[Domain - 1] && "Unknown domain op");
6617       MI.setDesc(get(table[Domain - 1]));
6618       MI.getOperand(NumOperands - 1).setImm(NewImm & 255);
6619     }
6620     return true;
6621   };
6622 
6623   switch (Opcode) {
6624   case X86::BLENDPDrmi:
6625   case X86::BLENDPDrri:
6626   case X86::VBLENDPDrmi:
6627   case X86::VBLENDPDrri:
6628     return SetBlendDomain(2, false);
6629   case X86::VBLENDPDYrmi:
6630   case X86::VBLENDPDYrri:
6631     return SetBlendDomain(4, true);
6632   case X86::BLENDPSrmi:
6633   case X86::BLENDPSrri:
6634   case X86::VBLENDPSrmi:
6635   case X86::VBLENDPSrri:
6636   case X86::VPBLENDDrmi:
6637   case X86::VPBLENDDrri:
6638     return SetBlendDomain(4, false);
6639   case X86::VBLENDPSYrmi:
6640   case X86::VBLENDPSYrri:
6641   case X86::VPBLENDDYrmi:
6642   case X86::VPBLENDDYrri:
6643     return SetBlendDomain(8, true);
6644   case X86::PBLENDWrmi:
6645   case X86::PBLENDWrri:
6646   case X86::VPBLENDWrmi:
6647   case X86::VPBLENDWrri:
6648     return SetBlendDomain(8, false);
6649   case X86::VPBLENDWYrmi:
6650   case X86::VPBLENDWYrri:
6651     return SetBlendDomain(16, true);
6652   case X86::VPANDDZ128rr:  case X86::VPANDDZ128rm:
6653   case X86::VPANDDZ256rr:  case X86::VPANDDZ256rm:
6654   case X86::VPANDQZ128rr:  case X86::VPANDQZ128rm:
6655   case X86::VPANDQZ256rr:  case X86::VPANDQZ256rm:
6656   case X86::VPANDNDZ128rr: case X86::VPANDNDZ128rm:
6657   case X86::VPANDNDZ256rr: case X86::VPANDNDZ256rm:
6658   case X86::VPANDNQZ128rr: case X86::VPANDNQZ128rm:
6659   case X86::VPANDNQZ256rr: case X86::VPANDNQZ256rm:
6660   case X86::VPORDZ128rr:   case X86::VPORDZ128rm:
6661   case X86::VPORDZ256rr:   case X86::VPORDZ256rm:
6662   case X86::VPORQZ128rr:   case X86::VPORQZ128rm:
6663   case X86::VPORQZ256rr:   case X86::VPORQZ256rm:
6664   case X86::VPXORDZ128rr:  case X86::VPXORDZ128rm:
6665   case X86::VPXORDZ256rr:  case X86::VPXORDZ256rm:
6666   case X86::VPXORQZ128rr:  case X86::VPXORQZ128rm:
6667   case X86::VPXORQZ256rr:  case X86::VPXORQZ256rm: {
6668     // Without DQI, convert EVEX instructions to VEX instructions.
6669     if (Subtarget.hasDQI())
6670       return false;
6671 
6672     const uint16_t *table = lookupAVX512(MI.getOpcode(), dom,
6673                                          ReplaceableCustomAVX512LogicInstrs);
6674     assert(table && "Instruction not found in table?");
6675     // Don't change integer Q instructions to D instructions and
6676     // use D intructions if we started with a PS instruction.
6677     if (Domain == 3 && (dom == 1 || table[3] == MI.getOpcode()))
6678       Domain = 4;
6679     MI.setDesc(get(table[Domain - 1]));
6680     return true;
6681   }
6682   case X86::UNPCKHPDrr:
6683   case X86::MOVHLPSrr:
6684     // We just need to commute the instruction which will switch the domains.
6685     if (Domain != dom && Domain != 3 &&
6686         MI.getOperand(1).getReg() == MI.getOperand(2).getReg() &&
6687         MI.getOperand(0).getSubReg() == 0 &&
6688         MI.getOperand(1).getSubReg() == 0 &&
6689         MI.getOperand(2).getSubReg() == 0) {
6690       commuteInstruction(MI, false);
6691       return true;
6692     }
6693     // We must always return true for MOVHLPSrr.
6694     if (Opcode == X86::MOVHLPSrr)
6695       return true;
6696   }
6697   return false;
6698 }
6699 
6700 std::pair<uint16_t, uint16_t>
6701 X86InstrInfo::getExecutionDomain(const MachineInstr &MI) const {
6702   uint16_t domain = (MI.getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
6703   unsigned opcode = MI.getOpcode();
6704   uint16_t validDomains = 0;
6705   if (domain) {
6706     // Attempt to match for custom instructions.
6707     validDomains = getExecutionDomainCustom(MI);
6708     if (validDomains)
6709       return std::make_pair(domain, validDomains);
6710 
6711     if (lookup(opcode, domain, ReplaceableInstrs)) {
6712       validDomains = 0xe;
6713     } else if (lookup(opcode, domain, ReplaceableInstrsAVX2)) {
6714       validDomains = Subtarget.hasAVX2() ? 0xe : 0x6;
6715     } else if (lookup(opcode, domain, ReplaceableInstrsAVX2InsertExtract)) {
6716       // Insert/extract instructions should only effect domain if AVX2
6717       // is enabled.
6718       if (!Subtarget.hasAVX2())
6719         return std::make_pair(0, 0);
6720       validDomains = 0xe;
6721     } else if (lookupAVX512(opcode, domain, ReplaceableInstrsAVX512)) {
6722       validDomains = 0xe;
6723     } else if (Subtarget.hasDQI() && lookupAVX512(opcode, domain,
6724                                                   ReplaceableInstrsAVX512DQ)) {
6725       validDomains = 0xe;
6726     } else if (Subtarget.hasDQI()) {
6727       if (const uint16_t *table = lookupAVX512(opcode, domain,
6728                                              ReplaceableInstrsAVX512DQMasked)) {
6729         if (domain == 1 || (domain == 3 && table[3] == opcode))
6730           validDomains = 0xa;
6731         else
6732           validDomains = 0xc;
6733       }
6734     }
6735   }
6736   return std::make_pair(domain, validDomains);
6737 }
6738 
6739 void X86InstrInfo::setExecutionDomain(MachineInstr &MI, unsigned Domain) const {
6740   assert(Domain>0 && Domain<4 && "Invalid execution domain");
6741   uint16_t dom = (MI.getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
6742   assert(dom && "Not an SSE instruction");
6743 
6744   // Attempt to match for custom instructions.
6745   if (setExecutionDomainCustom(MI, Domain))
6746     return;
6747 
6748   const uint16_t *table = lookup(MI.getOpcode(), dom, ReplaceableInstrs);
6749   if (!table) { // try the other table
6750     assert((Subtarget.hasAVX2() || Domain < 3) &&
6751            "256-bit vector operations only available in AVX2");
6752     table = lookup(MI.getOpcode(), dom, ReplaceableInstrsAVX2);
6753   }
6754   if (!table) { // try the other table
6755     assert(Subtarget.hasAVX2() &&
6756            "256-bit insert/extract only available in AVX2");
6757     table = lookup(MI.getOpcode(), dom, ReplaceableInstrsAVX2InsertExtract);
6758   }
6759   if (!table) { // try the AVX512 table
6760     assert(Subtarget.hasAVX512() && "Requires AVX-512");
6761     table = lookupAVX512(MI.getOpcode(), dom, ReplaceableInstrsAVX512);
6762     // Don't change integer Q instructions to D instructions.
6763     if (table && Domain == 3 && table[3] == MI.getOpcode())
6764       Domain = 4;
6765   }
6766   if (!table) { // try the AVX512DQ table
6767     assert((Subtarget.hasDQI() || Domain >= 3) && "Requires AVX-512DQ");
6768     table = lookupAVX512(MI.getOpcode(), dom, ReplaceableInstrsAVX512DQ);
6769     // Don't change integer Q instructions to D instructions and
6770     // use D intructions if we started with a PS instruction.
6771     if (table && Domain == 3 && (dom == 1 || table[3] == MI.getOpcode()))
6772       Domain = 4;
6773   }
6774   if (!table) { // try the AVX512DQMasked table
6775     assert((Subtarget.hasDQI() || Domain >= 3) && "Requires AVX-512DQ");
6776     table = lookupAVX512(MI.getOpcode(), dom, ReplaceableInstrsAVX512DQMasked);
6777     if (table && Domain == 3 && (dom == 1 || table[3] == MI.getOpcode()))
6778       Domain = 4;
6779   }
6780   assert(table && "Cannot change domain");
6781   MI.setDesc(get(table[Domain - 1]));
6782 }
6783 
6784 /// Return the noop instruction to use for a noop.
6785 void X86InstrInfo::getNoop(MCInst &NopInst) const {
6786   NopInst.setOpcode(X86::NOOP);
6787 }
6788 
6789 bool X86InstrInfo::isHighLatencyDef(int opc) const {
6790   switch (opc) {
6791   default: return false;
6792   case X86::DIVPDrm:
6793   case X86::DIVPDrr:
6794   case X86::DIVPSrm:
6795   case X86::DIVPSrr:
6796   case X86::DIVSDrm:
6797   case X86::DIVSDrm_Int:
6798   case X86::DIVSDrr:
6799   case X86::DIVSDrr_Int:
6800   case X86::DIVSSrm:
6801   case X86::DIVSSrm_Int:
6802   case X86::DIVSSrr:
6803   case X86::DIVSSrr_Int:
6804   case X86::SQRTPDm:
6805   case X86::SQRTPDr:
6806   case X86::SQRTPSm:
6807   case X86::SQRTPSr:
6808   case X86::SQRTSDm:
6809   case X86::SQRTSDm_Int:
6810   case X86::SQRTSDr:
6811   case X86::SQRTSDr_Int:
6812   case X86::SQRTSSm:
6813   case X86::SQRTSSm_Int:
6814   case X86::SQRTSSr:
6815   case X86::SQRTSSr_Int:
6816   // AVX instructions with high latency
6817   case X86::VDIVPDrm:
6818   case X86::VDIVPDrr:
6819   case X86::VDIVPDYrm:
6820   case X86::VDIVPDYrr:
6821   case X86::VDIVPSrm:
6822   case X86::VDIVPSrr:
6823   case X86::VDIVPSYrm:
6824   case X86::VDIVPSYrr:
6825   case X86::VDIVSDrm:
6826   case X86::VDIVSDrm_Int:
6827   case X86::VDIVSDrr:
6828   case X86::VDIVSDrr_Int:
6829   case X86::VDIVSSrm:
6830   case X86::VDIVSSrm_Int:
6831   case X86::VDIVSSrr:
6832   case X86::VDIVSSrr_Int:
6833   case X86::VSQRTPDm:
6834   case X86::VSQRTPDr:
6835   case X86::VSQRTPDYm:
6836   case X86::VSQRTPDYr:
6837   case X86::VSQRTPSm:
6838   case X86::VSQRTPSr:
6839   case X86::VSQRTPSYm:
6840   case X86::VSQRTPSYr:
6841   case X86::VSQRTSDm:
6842   case X86::VSQRTSDm_Int:
6843   case X86::VSQRTSDr:
6844   case X86::VSQRTSDr_Int:
6845   case X86::VSQRTSSm:
6846   case X86::VSQRTSSm_Int:
6847   case X86::VSQRTSSr:
6848   case X86::VSQRTSSr_Int:
6849   // AVX512 instructions with high latency
6850   case X86::VDIVPDZ128rm:
6851   case X86::VDIVPDZ128rmb:
6852   case X86::VDIVPDZ128rmbk:
6853   case X86::VDIVPDZ128rmbkz:
6854   case X86::VDIVPDZ128rmk:
6855   case X86::VDIVPDZ128rmkz:
6856   case X86::VDIVPDZ128rr:
6857   case X86::VDIVPDZ128rrk:
6858   case X86::VDIVPDZ128rrkz:
6859   case X86::VDIVPDZ256rm:
6860   case X86::VDIVPDZ256rmb:
6861   case X86::VDIVPDZ256rmbk:
6862   case X86::VDIVPDZ256rmbkz:
6863   case X86::VDIVPDZ256rmk:
6864   case X86::VDIVPDZ256rmkz:
6865   case X86::VDIVPDZ256rr:
6866   case X86::VDIVPDZ256rrk:
6867   case X86::VDIVPDZ256rrkz:
6868   case X86::VDIVPDZrrb:
6869   case X86::VDIVPDZrrbk:
6870   case X86::VDIVPDZrrbkz:
6871   case X86::VDIVPDZrm:
6872   case X86::VDIVPDZrmb:
6873   case X86::VDIVPDZrmbk:
6874   case X86::VDIVPDZrmbkz:
6875   case X86::VDIVPDZrmk:
6876   case X86::VDIVPDZrmkz:
6877   case X86::VDIVPDZrr:
6878   case X86::VDIVPDZrrk:
6879   case X86::VDIVPDZrrkz:
6880   case X86::VDIVPSZ128rm:
6881   case X86::VDIVPSZ128rmb:
6882   case X86::VDIVPSZ128rmbk:
6883   case X86::VDIVPSZ128rmbkz:
6884   case X86::VDIVPSZ128rmk:
6885   case X86::VDIVPSZ128rmkz:
6886   case X86::VDIVPSZ128rr:
6887   case X86::VDIVPSZ128rrk:
6888   case X86::VDIVPSZ128rrkz:
6889   case X86::VDIVPSZ256rm:
6890   case X86::VDIVPSZ256rmb:
6891   case X86::VDIVPSZ256rmbk:
6892   case X86::VDIVPSZ256rmbkz:
6893   case X86::VDIVPSZ256rmk:
6894   case X86::VDIVPSZ256rmkz:
6895   case X86::VDIVPSZ256rr:
6896   case X86::VDIVPSZ256rrk:
6897   case X86::VDIVPSZ256rrkz:
6898   case X86::VDIVPSZrrb:
6899   case X86::VDIVPSZrrbk:
6900   case X86::VDIVPSZrrbkz:
6901   case X86::VDIVPSZrm:
6902   case X86::VDIVPSZrmb:
6903   case X86::VDIVPSZrmbk:
6904   case X86::VDIVPSZrmbkz:
6905   case X86::VDIVPSZrmk:
6906   case X86::VDIVPSZrmkz:
6907   case X86::VDIVPSZrr:
6908   case X86::VDIVPSZrrk:
6909   case X86::VDIVPSZrrkz:
6910   case X86::VDIVSDZrm:
6911   case X86::VDIVSDZrr:
6912   case X86::VDIVSDZrm_Int:
6913   case X86::VDIVSDZrm_Intk:
6914   case X86::VDIVSDZrm_Intkz:
6915   case X86::VDIVSDZrr_Int:
6916   case X86::VDIVSDZrr_Intk:
6917   case X86::VDIVSDZrr_Intkz:
6918   case X86::VDIVSDZrrb_Int:
6919   case X86::VDIVSDZrrb_Intk:
6920   case X86::VDIVSDZrrb_Intkz:
6921   case X86::VDIVSSZrm:
6922   case X86::VDIVSSZrr:
6923   case X86::VDIVSSZrm_Int:
6924   case X86::VDIVSSZrm_Intk:
6925   case X86::VDIVSSZrm_Intkz:
6926   case X86::VDIVSSZrr_Int:
6927   case X86::VDIVSSZrr_Intk:
6928   case X86::VDIVSSZrr_Intkz:
6929   case X86::VDIVSSZrrb_Int:
6930   case X86::VDIVSSZrrb_Intk:
6931   case X86::VDIVSSZrrb_Intkz:
6932   case X86::VSQRTPDZ128m:
6933   case X86::VSQRTPDZ128mb:
6934   case X86::VSQRTPDZ128mbk:
6935   case X86::VSQRTPDZ128mbkz:
6936   case X86::VSQRTPDZ128mk:
6937   case X86::VSQRTPDZ128mkz:
6938   case X86::VSQRTPDZ128r:
6939   case X86::VSQRTPDZ128rk:
6940   case X86::VSQRTPDZ128rkz:
6941   case X86::VSQRTPDZ256m:
6942   case X86::VSQRTPDZ256mb:
6943   case X86::VSQRTPDZ256mbk:
6944   case X86::VSQRTPDZ256mbkz:
6945   case X86::VSQRTPDZ256mk:
6946   case X86::VSQRTPDZ256mkz:
6947   case X86::VSQRTPDZ256r:
6948   case X86::VSQRTPDZ256rk:
6949   case X86::VSQRTPDZ256rkz:
6950   case X86::VSQRTPDZm:
6951   case X86::VSQRTPDZmb:
6952   case X86::VSQRTPDZmbk:
6953   case X86::VSQRTPDZmbkz:
6954   case X86::VSQRTPDZmk:
6955   case X86::VSQRTPDZmkz:
6956   case X86::VSQRTPDZr:
6957   case X86::VSQRTPDZrb:
6958   case X86::VSQRTPDZrbk:
6959   case X86::VSQRTPDZrbkz:
6960   case X86::VSQRTPDZrk:
6961   case X86::VSQRTPDZrkz:
6962   case X86::VSQRTPSZ128m:
6963   case X86::VSQRTPSZ128mb:
6964   case X86::VSQRTPSZ128mbk:
6965   case X86::VSQRTPSZ128mbkz:
6966   case X86::VSQRTPSZ128mk:
6967   case X86::VSQRTPSZ128mkz:
6968   case X86::VSQRTPSZ128r:
6969   case X86::VSQRTPSZ128rk:
6970   case X86::VSQRTPSZ128rkz:
6971   case X86::VSQRTPSZ256m:
6972   case X86::VSQRTPSZ256mb:
6973   case X86::VSQRTPSZ256mbk:
6974   case X86::VSQRTPSZ256mbkz:
6975   case X86::VSQRTPSZ256mk:
6976   case X86::VSQRTPSZ256mkz:
6977   case X86::VSQRTPSZ256r:
6978   case X86::VSQRTPSZ256rk:
6979   case X86::VSQRTPSZ256rkz:
6980   case X86::VSQRTPSZm:
6981   case X86::VSQRTPSZmb:
6982   case X86::VSQRTPSZmbk:
6983   case X86::VSQRTPSZmbkz:
6984   case X86::VSQRTPSZmk:
6985   case X86::VSQRTPSZmkz:
6986   case X86::VSQRTPSZr:
6987   case X86::VSQRTPSZrb:
6988   case X86::VSQRTPSZrbk:
6989   case X86::VSQRTPSZrbkz:
6990   case X86::VSQRTPSZrk:
6991   case X86::VSQRTPSZrkz:
6992   case X86::VSQRTSDZm:
6993   case X86::VSQRTSDZm_Int:
6994   case X86::VSQRTSDZm_Intk:
6995   case X86::VSQRTSDZm_Intkz:
6996   case X86::VSQRTSDZr:
6997   case X86::VSQRTSDZr_Int:
6998   case X86::VSQRTSDZr_Intk:
6999   case X86::VSQRTSDZr_Intkz:
7000   case X86::VSQRTSDZrb_Int:
7001   case X86::VSQRTSDZrb_Intk:
7002   case X86::VSQRTSDZrb_Intkz:
7003   case X86::VSQRTSSZm:
7004   case X86::VSQRTSSZm_Int:
7005   case X86::VSQRTSSZm_Intk:
7006   case X86::VSQRTSSZm_Intkz:
7007   case X86::VSQRTSSZr:
7008   case X86::VSQRTSSZr_Int:
7009   case X86::VSQRTSSZr_Intk:
7010   case X86::VSQRTSSZr_Intkz:
7011   case X86::VSQRTSSZrb_Int:
7012   case X86::VSQRTSSZrb_Intk:
7013   case X86::VSQRTSSZrb_Intkz:
7014 
7015   case X86::VGATHERDPDYrm:
7016   case X86::VGATHERDPDZ128rm:
7017   case X86::VGATHERDPDZ256rm:
7018   case X86::VGATHERDPDZrm:
7019   case X86::VGATHERDPDrm:
7020   case X86::VGATHERDPSYrm:
7021   case X86::VGATHERDPSZ128rm:
7022   case X86::VGATHERDPSZ256rm:
7023   case X86::VGATHERDPSZrm:
7024   case X86::VGATHERDPSrm:
7025   case X86::VGATHERPF0DPDm:
7026   case X86::VGATHERPF0DPSm:
7027   case X86::VGATHERPF0QPDm:
7028   case X86::VGATHERPF0QPSm:
7029   case X86::VGATHERPF1DPDm:
7030   case X86::VGATHERPF1DPSm:
7031   case X86::VGATHERPF1QPDm:
7032   case X86::VGATHERPF1QPSm:
7033   case X86::VGATHERQPDYrm:
7034   case X86::VGATHERQPDZ128rm:
7035   case X86::VGATHERQPDZ256rm:
7036   case X86::VGATHERQPDZrm:
7037   case X86::VGATHERQPDrm:
7038   case X86::VGATHERQPSYrm:
7039   case X86::VGATHERQPSZ128rm:
7040   case X86::VGATHERQPSZ256rm:
7041   case X86::VGATHERQPSZrm:
7042   case X86::VGATHERQPSrm:
7043   case X86::VPGATHERDDYrm:
7044   case X86::VPGATHERDDZ128rm:
7045   case X86::VPGATHERDDZ256rm:
7046   case X86::VPGATHERDDZrm:
7047   case X86::VPGATHERDDrm:
7048   case X86::VPGATHERDQYrm:
7049   case X86::VPGATHERDQZ128rm:
7050   case X86::VPGATHERDQZ256rm:
7051   case X86::VPGATHERDQZrm:
7052   case X86::VPGATHERDQrm:
7053   case X86::VPGATHERQDYrm:
7054   case X86::VPGATHERQDZ128rm:
7055   case X86::VPGATHERQDZ256rm:
7056   case X86::VPGATHERQDZrm:
7057   case X86::VPGATHERQDrm:
7058   case X86::VPGATHERQQYrm:
7059   case X86::VPGATHERQQZ128rm:
7060   case X86::VPGATHERQQZ256rm:
7061   case X86::VPGATHERQQZrm:
7062   case X86::VPGATHERQQrm:
7063   case X86::VSCATTERDPDZ128mr:
7064   case X86::VSCATTERDPDZ256mr:
7065   case X86::VSCATTERDPDZmr:
7066   case X86::VSCATTERDPSZ128mr:
7067   case X86::VSCATTERDPSZ256mr:
7068   case X86::VSCATTERDPSZmr:
7069   case X86::VSCATTERPF0DPDm:
7070   case X86::VSCATTERPF0DPSm:
7071   case X86::VSCATTERPF0QPDm:
7072   case X86::VSCATTERPF0QPSm:
7073   case X86::VSCATTERPF1DPDm:
7074   case X86::VSCATTERPF1DPSm:
7075   case X86::VSCATTERPF1QPDm:
7076   case X86::VSCATTERPF1QPSm:
7077   case X86::VSCATTERQPDZ128mr:
7078   case X86::VSCATTERQPDZ256mr:
7079   case X86::VSCATTERQPDZmr:
7080   case X86::VSCATTERQPSZ128mr:
7081   case X86::VSCATTERQPSZ256mr:
7082   case X86::VSCATTERQPSZmr:
7083   case X86::VPSCATTERDDZ128mr:
7084   case X86::VPSCATTERDDZ256mr:
7085   case X86::VPSCATTERDDZmr:
7086   case X86::VPSCATTERDQZ128mr:
7087   case X86::VPSCATTERDQZ256mr:
7088   case X86::VPSCATTERDQZmr:
7089   case X86::VPSCATTERQDZ128mr:
7090   case X86::VPSCATTERQDZ256mr:
7091   case X86::VPSCATTERQDZmr:
7092   case X86::VPSCATTERQQZ128mr:
7093   case X86::VPSCATTERQQZ256mr:
7094   case X86::VPSCATTERQQZmr:
7095     return true;
7096   }
7097 }
7098 
7099 bool X86InstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
7100                                          const MachineRegisterInfo *MRI,
7101                                          const MachineInstr &DefMI,
7102                                          unsigned DefIdx,
7103                                          const MachineInstr &UseMI,
7104                                          unsigned UseIdx) const {
7105   return isHighLatencyDef(DefMI.getOpcode());
7106 }
7107 
7108 bool X86InstrInfo::hasReassociableOperands(const MachineInstr &Inst,
7109                                            const MachineBasicBlock *MBB) const {
7110   assert((Inst.getNumOperands() == 3 || Inst.getNumOperands() == 4) &&
7111          "Reassociation needs binary operators");
7112 
7113   // Integer binary math/logic instructions have a third source operand:
7114   // the EFLAGS register. That operand must be both defined here and never
7115   // used; ie, it must be dead. If the EFLAGS operand is live, then we can
7116   // not change anything because rearranging the operands could affect other
7117   // instructions that depend on the exact status flags (zero, sign, etc.)
7118   // that are set by using these particular operands with this operation.
7119   if (Inst.getNumOperands() == 4) {
7120     assert(Inst.getOperand(3).isReg() &&
7121            Inst.getOperand(3).getReg() == X86::EFLAGS &&
7122            "Unexpected operand in reassociable instruction");
7123     if (!Inst.getOperand(3).isDead())
7124       return false;
7125   }
7126 
7127   return TargetInstrInfo::hasReassociableOperands(Inst, MBB);
7128 }
7129 
7130 // TODO: There are many more machine instruction opcodes to match:
7131 //       1. Other data types (integer, vectors)
7132 //       2. Other math / logic operations (xor, or)
7133 //       3. Other forms of the same operation (intrinsics and other variants)
7134 bool X86InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
7135   switch (Inst.getOpcode()) {
7136   case X86::AND8rr:
7137   case X86::AND16rr:
7138   case X86::AND32rr:
7139   case X86::AND64rr:
7140   case X86::OR8rr:
7141   case X86::OR16rr:
7142   case X86::OR32rr:
7143   case X86::OR64rr:
7144   case X86::XOR8rr:
7145   case X86::XOR16rr:
7146   case X86::XOR32rr:
7147   case X86::XOR64rr:
7148   case X86::IMUL16rr:
7149   case X86::IMUL32rr:
7150   case X86::IMUL64rr:
7151   case X86::PANDrr:
7152   case X86::PORrr:
7153   case X86::PXORrr:
7154   case X86::ANDPDrr:
7155   case X86::ANDPSrr:
7156   case X86::ORPDrr:
7157   case X86::ORPSrr:
7158   case X86::XORPDrr:
7159   case X86::XORPSrr:
7160   case X86::PADDBrr:
7161   case X86::PADDWrr:
7162   case X86::PADDDrr:
7163   case X86::PADDQrr:
7164   case X86::VPANDrr:
7165   case X86::VPANDYrr:
7166   case X86::VPANDDZ128rr:
7167   case X86::VPANDDZ256rr:
7168   case X86::VPANDDZrr:
7169   case X86::VPANDQZ128rr:
7170   case X86::VPANDQZ256rr:
7171   case X86::VPANDQZrr:
7172   case X86::VPORrr:
7173   case X86::VPORYrr:
7174   case X86::VPORDZ128rr:
7175   case X86::VPORDZ256rr:
7176   case X86::VPORDZrr:
7177   case X86::VPORQZ128rr:
7178   case X86::VPORQZ256rr:
7179   case X86::VPORQZrr:
7180   case X86::VPXORrr:
7181   case X86::VPXORYrr:
7182   case X86::VPXORDZ128rr:
7183   case X86::VPXORDZ256rr:
7184   case X86::VPXORDZrr:
7185   case X86::VPXORQZ128rr:
7186   case X86::VPXORQZ256rr:
7187   case X86::VPXORQZrr:
7188   case X86::VANDPDrr:
7189   case X86::VANDPSrr:
7190   case X86::VANDPDYrr:
7191   case X86::VANDPSYrr:
7192   case X86::VANDPDZ128rr:
7193   case X86::VANDPSZ128rr:
7194   case X86::VANDPDZ256rr:
7195   case X86::VANDPSZ256rr:
7196   case X86::VANDPDZrr:
7197   case X86::VANDPSZrr:
7198   case X86::VORPDrr:
7199   case X86::VORPSrr:
7200   case X86::VORPDYrr:
7201   case X86::VORPSYrr:
7202   case X86::VORPDZ128rr:
7203   case X86::VORPSZ128rr:
7204   case X86::VORPDZ256rr:
7205   case X86::VORPSZ256rr:
7206   case X86::VORPDZrr:
7207   case X86::VORPSZrr:
7208   case X86::VXORPDrr:
7209   case X86::VXORPSrr:
7210   case X86::VXORPDYrr:
7211   case X86::VXORPSYrr:
7212   case X86::VXORPDZ128rr:
7213   case X86::VXORPSZ128rr:
7214   case X86::VXORPDZ256rr:
7215   case X86::VXORPSZ256rr:
7216   case X86::VXORPDZrr:
7217   case X86::VXORPSZrr:
7218   case X86::KADDBrr:
7219   case X86::KADDWrr:
7220   case X86::KADDDrr:
7221   case X86::KADDQrr:
7222   case X86::KANDBrr:
7223   case X86::KANDWrr:
7224   case X86::KANDDrr:
7225   case X86::KANDQrr:
7226   case X86::KORBrr:
7227   case X86::KORWrr:
7228   case X86::KORDrr:
7229   case X86::KORQrr:
7230   case X86::KXORBrr:
7231   case X86::KXORWrr:
7232   case X86::KXORDrr:
7233   case X86::KXORQrr:
7234   case X86::VPADDBrr:
7235   case X86::VPADDWrr:
7236   case X86::VPADDDrr:
7237   case X86::VPADDQrr:
7238   case X86::VPADDBYrr:
7239   case X86::VPADDWYrr:
7240   case X86::VPADDDYrr:
7241   case X86::VPADDQYrr:
7242   case X86::VPADDBZ128rr:
7243   case X86::VPADDWZ128rr:
7244   case X86::VPADDDZ128rr:
7245   case X86::VPADDQZ128rr:
7246   case X86::VPADDBZ256rr:
7247   case X86::VPADDWZ256rr:
7248   case X86::VPADDDZ256rr:
7249   case X86::VPADDQZ256rr:
7250   case X86::VPADDBZrr:
7251   case X86::VPADDWZrr:
7252   case X86::VPADDDZrr:
7253   case X86::VPADDQZrr:
7254   case X86::VPMULLWrr:
7255   case X86::VPMULLWYrr:
7256   case X86::VPMULLWZ128rr:
7257   case X86::VPMULLWZ256rr:
7258   case X86::VPMULLWZrr:
7259   case X86::VPMULLDrr:
7260   case X86::VPMULLDYrr:
7261   case X86::VPMULLDZ128rr:
7262   case X86::VPMULLDZ256rr:
7263   case X86::VPMULLDZrr:
7264   case X86::VPMULLQZ128rr:
7265   case X86::VPMULLQZ256rr:
7266   case X86::VPMULLQZrr:
7267   // Normal min/max instructions are not commutative because of NaN and signed
7268   // zero semantics, but these are. Thus, there's no need to check for global
7269   // relaxed math; the instructions themselves have the properties we need.
7270   case X86::MAXCPDrr:
7271   case X86::MAXCPSrr:
7272   case X86::MAXCSDrr:
7273   case X86::MAXCSSrr:
7274   case X86::MINCPDrr:
7275   case X86::MINCPSrr:
7276   case X86::MINCSDrr:
7277   case X86::MINCSSrr:
7278   case X86::VMAXCPDrr:
7279   case X86::VMAXCPSrr:
7280   case X86::VMAXCPDYrr:
7281   case X86::VMAXCPSYrr:
7282   case X86::VMAXCPDZ128rr:
7283   case X86::VMAXCPSZ128rr:
7284   case X86::VMAXCPDZ256rr:
7285   case X86::VMAXCPSZ256rr:
7286   case X86::VMAXCPDZrr:
7287   case X86::VMAXCPSZrr:
7288   case X86::VMAXCSDrr:
7289   case X86::VMAXCSSrr:
7290   case X86::VMAXCSDZrr:
7291   case X86::VMAXCSSZrr:
7292   case X86::VMINCPDrr:
7293   case X86::VMINCPSrr:
7294   case X86::VMINCPDYrr:
7295   case X86::VMINCPSYrr:
7296   case X86::VMINCPDZ128rr:
7297   case X86::VMINCPSZ128rr:
7298   case X86::VMINCPDZ256rr:
7299   case X86::VMINCPSZ256rr:
7300   case X86::VMINCPDZrr:
7301   case X86::VMINCPSZrr:
7302   case X86::VMINCSDrr:
7303   case X86::VMINCSSrr:
7304   case X86::VMINCSDZrr:
7305   case X86::VMINCSSZrr:
7306     return true;
7307   case X86::ADDPDrr:
7308   case X86::ADDPSrr:
7309   case X86::ADDSDrr:
7310   case X86::ADDSSrr:
7311   case X86::MULPDrr:
7312   case X86::MULPSrr:
7313   case X86::MULSDrr:
7314   case X86::MULSSrr:
7315   case X86::VADDPDrr:
7316   case X86::VADDPSrr:
7317   case X86::VADDPDYrr:
7318   case X86::VADDPSYrr:
7319   case X86::VADDPDZ128rr:
7320   case X86::VADDPSZ128rr:
7321   case X86::VADDPDZ256rr:
7322   case X86::VADDPSZ256rr:
7323   case X86::VADDPDZrr:
7324   case X86::VADDPSZrr:
7325   case X86::VADDSDrr:
7326   case X86::VADDSSrr:
7327   case X86::VADDSDZrr:
7328   case X86::VADDSSZrr:
7329   case X86::VMULPDrr:
7330   case X86::VMULPSrr:
7331   case X86::VMULPDYrr:
7332   case X86::VMULPSYrr:
7333   case X86::VMULPDZ128rr:
7334   case X86::VMULPSZ128rr:
7335   case X86::VMULPDZ256rr:
7336   case X86::VMULPSZ256rr:
7337   case X86::VMULPDZrr:
7338   case X86::VMULPSZrr:
7339   case X86::VMULSDrr:
7340   case X86::VMULSSrr:
7341   case X86::VMULSDZrr:
7342   case X86::VMULSSZrr:
7343     return Inst.getParent()->getParent()->getTarget().Options.UnsafeFPMath;
7344   default:
7345     return false;
7346   }
7347 }
7348 
7349 /// This is an architecture-specific helper function of reassociateOps.
7350 /// Set special operand attributes for new instructions after reassociation.
7351 void X86InstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1,
7352                                          MachineInstr &OldMI2,
7353                                          MachineInstr &NewMI1,
7354                                          MachineInstr &NewMI2) const {
7355   // Integer instructions define an implicit EFLAGS source register operand as
7356   // the third source (fourth total) operand.
7357   if (OldMI1.getNumOperands() != 4 || OldMI2.getNumOperands() != 4)
7358     return;
7359 
7360   assert(NewMI1.getNumOperands() == 4 && NewMI2.getNumOperands() == 4 &&
7361          "Unexpected instruction type for reassociation");
7362 
7363   MachineOperand &OldOp1 = OldMI1.getOperand(3);
7364   MachineOperand &OldOp2 = OldMI2.getOperand(3);
7365   MachineOperand &NewOp1 = NewMI1.getOperand(3);
7366   MachineOperand &NewOp2 = NewMI2.getOperand(3);
7367 
7368   assert(OldOp1.isReg() && OldOp1.getReg() == X86::EFLAGS && OldOp1.isDead() &&
7369          "Must have dead EFLAGS operand in reassociable instruction");
7370   assert(OldOp2.isReg() && OldOp2.getReg() == X86::EFLAGS && OldOp2.isDead() &&
7371          "Must have dead EFLAGS operand in reassociable instruction");
7372 
7373   (void)OldOp1;
7374   (void)OldOp2;
7375 
7376   assert(NewOp1.isReg() && NewOp1.getReg() == X86::EFLAGS &&
7377          "Unexpected operand in reassociable instruction");
7378   assert(NewOp2.isReg() && NewOp2.getReg() == X86::EFLAGS &&
7379          "Unexpected operand in reassociable instruction");
7380 
7381   // Mark the new EFLAGS operands as dead to be helpful to subsequent iterations
7382   // of this pass or other passes. The EFLAGS operands must be dead in these new
7383   // instructions because the EFLAGS operands in the original instructions must
7384   // be dead in order for reassociation to occur.
7385   NewOp1.setIsDead();
7386   NewOp2.setIsDead();
7387 }
7388 
7389 std::pair<unsigned, unsigned>
7390 X86InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7391   return std::make_pair(TF, 0u);
7392 }
7393 
7394 ArrayRef<std::pair<unsigned, const char *>>
7395 X86InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7396   using namespace X86II;
7397   static const std::pair<unsigned, const char *> TargetFlags[] = {
7398       {MO_GOT_ABSOLUTE_ADDRESS, "x86-got-absolute-address"},
7399       {MO_PIC_BASE_OFFSET, "x86-pic-base-offset"},
7400       {MO_GOT, "x86-got"},
7401       {MO_GOTOFF, "x86-gotoff"},
7402       {MO_GOTPCREL, "x86-gotpcrel"},
7403       {MO_PLT, "x86-plt"},
7404       {MO_TLSGD, "x86-tlsgd"},
7405       {MO_TLSLD, "x86-tlsld"},
7406       {MO_TLSLDM, "x86-tlsldm"},
7407       {MO_GOTTPOFF, "x86-gottpoff"},
7408       {MO_INDNTPOFF, "x86-indntpoff"},
7409       {MO_TPOFF, "x86-tpoff"},
7410       {MO_DTPOFF, "x86-dtpoff"},
7411       {MO_NTPOFF, "x86-ntpoff"},
7412       {MO_GOTNTPOFF, "x86-gotntpoff"},
7413       {MO_DLLIMPORT, "x86-dllimport"},
7414       {MO_DARWIN_NONLAZY, "x86-darwin-nonlazy"},
7415       {MO_DARWIN_NONLAZY_PIC_BASE, "x86-darwin-nonlazy-pic-base"},
7416       {MO_TLVP, "x86-tlvp"},
7417       {MO_TLVP_PIC_BASE, "x86-tlvp-pic-base"},
7418       {MO_SECREL, "x86-secrel"},
7419       {MO_COFFSTUB, "x86-coffstub"}};
7420   return makeArrayRef(TargetFlags);
7421 }
7422 
7423 namespace {
7424   /// Create Global Base Reg pass. This initializes the PIC
7425   /// global base register for x86-32.
7426   struct CGBR : public MachineFunctionPass {
7427     static char ID;
7428     CGBR() : MachineFunctionPass(ID) {}
7429 
7430     bool runOnMachineFunction(MachineFunction &MF) override {
7431       const X86TargetMachine *TM =
7432         static_cast<const X86TargetMachine *>(&MF.getTarget());
7433       const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
7434 
7435       // Don't do anything in the 64-bit small and kernel code models. They use
7436       // RIP-relative addressing for everything.
7437       if (STI.is64Bit() && (TM->getCodeModel() == CodeModel::Small ||
7438                             TM->getCodeModel() == CodeModel::Kernel))
7439         return false;
7440 
7441       // Only emit a global base reg in PIC mode.
7442       if (!TM->isPositionIndependent())
7443         return false;
7444 
7445       X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
7446       unsigned GlobalBaseReg = X86FI->getGlobalBaseReg();
7447 
7448       // If we didn't need a GlobalBaseReg, don't insert code.
7449       if (GlobalBaseReg == 0)
7450         return false;
7451 
7452       // Insert the set of GlobalBaseReg into the first MBB of the function
7453       MachineBasicBlock &FirstMBB = MF.front();
7454       MachineBasicBlock::iterator MBBI = FirstMBB.begin();
7455       DebugLoc DL = FirstMBB.findDebugLoc(MBBI);
7456       MachineRegisterInfo &RegInfo = MF.getRegInfo();
7457       const X86InstrInfo *TII = STI.getInstrInfo();
7458 
7459       unsigned PC;
7460       if (STI.isPICStyleGOT())
7461         PC = RegInfo.createVirtualRegister(&X86::GR32RegClass);
7462       else
7463         PC = GlobalBaseReg;
7464 
7465       if (STI.is64Bit()) {
7466         if (TM->getCodeModel() == CodeModel::Medium) {
7467           // In the medium code model, use a RIP-relative LEA to materialize the
7468           // GOT.
7469           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::LEA64r), PC)
7470               .addReg(X86::RIP)
7471               .addImm(0)
7472               .addReg(0)
7473               .addExternalSymbol("_GLOBAL_OFFSET_TABLE_")
7474               .addReg(0);
7475         } else if (TM->getCodeModel() == CodeModel::Large) {
7476           // In the large code model, we are aiming for this code, though the
7477           // register allocation may vary:
7478           //   leaq .LN$pb(%rip), %rax
7479           //   movq $_GLOBAL_OFFSET_TABLE_ - .LN$pb, %rcx
7480           //   addq %rcx, %rax
7481           // RAX now holds address of _GLOBAL_OFFSET_TABLE_.
7482           unsigned PBReg = RegInfo.createVirtualRegister(&X86::GR64RegClass);
7483           unsigned GOTReg =
7484               RegInfo.createVirtualRegister(&X86::GR64RegClass);
7485           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::LEA64r), PBReg)
7486               .addReg(X86::RIP)
7487               .addImm(0)
7488               .addReg(0)
7489               .addSym(MF.getPICBaseSymbol())
7490               .addReg(0);
7491           std::prev(MBBI)->setPreInstrSymbol(MF, MF.getPICBaseSymbol());
7492           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::MOV64ri), GOTReg)
7493               .addExternalSymbol("_GLOBAL_OFFSET_TABLE_",
7494                                  X86II::MO_PIC_BASE_OFFSET);
7495           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::ADD64rr), PC)
7496               .addReg(PBReg, RegState::Kill)
7497               .addReg(GOTReg, RegState::Kill);
7498         } else {
7499           llvm_unreachable("unexpected code model");
7500         }
7501       } else {
7502         // Operand of MovePCtoStack is completely ignored by asm printer. It's
7503         // only used in JIT code emission as displacement to pc.
7504         BuildMI(FirstMBB, MBBI, DL, TII->get(X86::MOVPC32r), PC).addImm(0);
7505 
7506         // If we're using vanilla 'GOT' PIC style, we should use relative
7507         // addressing not to pc, but to _GLOBAL_OFFSET_TABLE_ external.
7508         if (STI.isPICStyleGOT()) {
7509           // Generate addl $__GLOBAL_OFFSET_TABLE_ + [.-piclabel],
7510           // %some_register
7511           BuildMI(FirstMBB, MBBI, DL, TII->get(X86::ADD32ri), GlobalBaseReg)
7512               .addReg(PC)
7513               .addExternalSymbol("_GLOBAL_OFFSET_TABLE_",
7514                                  X86II::MO_GOT_ABSOLUTE_ADDRESS);
7515         }
7516       }
7517 
7518       return true;
7519     }
7520 
7521     StringRef getPassName() const override {
7522       return "X86 PIC Global Base Reg Initialization";
7523     }
7524 
7525     void getAnalysisUsage(AnalysisUsage &AU) const override {
7526       AU.setPreservesCFG();
7527       MachineFunctionPass::getAnalysisUsage(AU);
7528     }
7529   };
7530 }
7531 
7532 char CGBR::ID = 0;
7533 FunctionPass*
7534 llvm::createX86GlobalBaseRegPass() { return new CGBR(); }
7535 
7536 namespace {
7537   struct LDTLSCleanup : public MachineFunctionPass {
7538     static char ID;
7539     LDTLSCleanup() : MachineFunctionPass(ID) {}
7540 
7541     bool runOnMachineFunction(MachineFunction &MF) override {
7542       if (skipFunction(MF.getFunction()))
7543         return false;
7544 
7545       X86MachineFunctionInfo *MFI = MF.getInfo<X86MachineFunctionInfo>();
7546       if (MFI->getNumLocalDynamicTLSAccesses() < 2) {
7547         // No point folding accesses if there isn't at least two.
7548         return false;
7549       }
7550 
7551       MachineDominatorTree *DT = &getAnalysis<MachineDominatorTree>();
7552       return VisitNode(DT->getRootNode(), 0);
7553     }
7554 
7555     // Visit the dominator subtree rooted at Node in pre-order.
7556     // If TLSBaseAddrReg is non-null, then use that to replace any
7557     // TLS_base_addr instructions. Otherwise, create the register
7558     // when the first such instruction is seen, and then use it
7559     // as we encounter more instructions.
7560     bool VisitNode(MachineDomTreeNode *Node, unsigned TLSBaseAddrReg) {
7561       MachineBasicBlock *BB = Node->getBlock();
7562       bool Changed = false;
7563 
7564       // Traverse the current block.
7565       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
7566            ++I) {
7567         switch (I->getOpcode()) {
7568           case X86::TLS_base_addr32:
7569           case X86::TLS_base_addr64:
7570             if (TLSBaseAddrReg)
7571               I = ReplaceTLSBaseAddrCall(*I, TLSBaseAddrReg);
7572             else
7573               I = SetRegister(*I, &TLSBaseAddrReg);
7574             Changed = true;
7575             break;
7576           default:
7577             break;
7578         }
7579       }
7580 
7581       // Visit the children of this block in the dominator tree.
7582       for (MachineDomTreeNode::iterator I = Node->begin(), E = Node->end();
7583            I != E; ++I) {
7584         Changed |= VisitNode(*I, TLSBaseAddrReg);
7585       }
7586 
7587       return Changed;
7588     }
7589 
7590     // Replace the TLS_base_addr instruction I with a copy from
7591     // TLSBaseAddrReg, returning the new instruction.
7592     MachineInstr *ReplaceTLSBaseAddrCall(MachineInstr &I,
7593                                          unsigned TLSBaseAddrReg) {
7594       MachineFunction *MF = I.getParent()->getParent();
7595       const X86Subtarget &STI = MF->getSubtarget<X86Subtarget>();
7596       const bool is64Bit = STI.is64Bit();
7597       const X86InstrInfo *TII = STI.getInstrInfo();
7598 
7599       // Insert a Copy from TLSBaseAddrReg to RAX/EAX.
7600       MachineInstr *Copy =
7601           BuildMI(*I.getParent(), I, I.getDebugLoc(),
7602                   TII->get(TargetOpcode::COPY), is64Bit ? X86::RAX : X86::EAX)
7603               .addReg(TLSBaseAddrReg);
7604 
7605       // Erase the TLS_base_addr instruction.
7606       I.eraseFromParent();
7607 
7608       return Copy;
7609     }
7610 
7611     // Create a virtual register in *TLSBaseAddrReg, and populate it by
7612     // inserting a copy instruction after I. Returns the new instruction.
7613     MachineInstr *SetRegister(MachineInstr &I, unsigned *TLSBaseAddrReg) {
7614       MachineFunction *MF = I.getParent()->getParent();
7615       const X86Subtarget &STI = MF->getSubtarget<X86Subtarget>();
7616       const bool is64Bit = STI.is64Bit();
7617       const X86InstrInfo *TII = STI.getInstrInfo();
7618 
7619       // Create a virtual register for the TLS base address.
7620       MachineRegisterInfo &RegInfo = MF->getRegInfo();
7621       *TLSBaseAddrReg = RegInfo.createVirtualRegister(is64Bit
7622                                                       ? &X86::GR64RegClass
7623                                                       : &X86::GR32RegClass);
7624 
7625       // Insert a copy from RAX/EAX to TLSBaseAddrReg.
7626       MachineInstr *Next = I.getNextNode();
7627       MachineInstr *Copy =
7628           BuildMI(*I.getParent(), Next, I.getDebugLoc(),
7629                   TII->get(TargetOpcode::COPY), *TLSBaseAddrReg)
7630               .addReg(is64Bit ? X86::RAX : X86::EAX);
7631 
7632       return Copy;
7633     }
7634 
7635     StringRef getPassName() const override {
7636       return "Local Dynamic TLS Access Clean-up";
7637     }
7638 
7639     void getAnalysisUsage(AnalysisUsage &AU) const override {
7640       AU.setPreservesCFG();
7641       AU.addRequired<MachineDominatorTree>();
7642       MachineFunctionPass::getAnalysisUsage(AU);
7643     }
7644   };
7645 }
7646 
7647 char LDTLSCleanup::ID = 0;
7648 FunctionPass*
7649 llvm::createCleanupLocalDynamicTLSPass() { return new LDTLSCleanup(); }
7650 
7651 /// Constants defining how certain sequences should be outlined.
7652 ///
7653 /// \p MachineOutlinerDefault implies that the function is called with a call
7654 /// instruction, and a return must be emitted for the outlined function frame.
7655 ///
7656 /// That is,
7657 ///
7658 /// I1                                 OUTLINED_FUNCTION:
7659 /// I2 --> call OUTLINED_FUNCTION       I1
7660 /// I3                                  I2
7661 ///                                     I3
7662 ///                                     ret
7663 ///
7664 /// * Call construction overhead: 1 (call instruction)
7665 /// * Frame construction overhead: 1 (return instruction)
7666 ///
7667 /// \p MachineOutlinerTailCall implies that the function is being tail called.
7668 /// A jump is emitted instead of a call, and the return is already present in
7669 /// the outlined sequence. That is,
7670 ///
7671 /// I1                                 OUTLINED_FUNCTION:
7672 /// I2 --> jmp OUTLINED_FUNCTION       I1
7673 /// ret                                I2
7674 ///                                    ret
7675 ///
7676 /// * Call construction overhead: 1 (jump instruction)
7677 /// * Frame construction overhead: 0 (don't need to return)
7678 ///
7679 enum MachineOutlinerClass {
7680   MachineOutlinerDefault,
7681   MachineOutlinerTailCall
7682 };
7683 
7684 outliner::OutlinedFunction X86InstrInfo::getOutliningCandidateInfo(
7685     std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
7686   unsigned SequenceSize =
7687       std::accumulate(RepeatedSequenceLocs[0].front(),
7688                       std::next(RepeatedSequenceLocs[0].back()), 0,
7689                       [](unsigned Sum, const MachineInstr &MI) {
7690                         // FIXME: x86 doesn't implement getInstSizeInBytes, so
7691                         // we can't tell the cost.  Just assume each instruction
7692                         // is one byte.
7693                         if (MI.isDebugInstr() || MI.isKill())
7694                           return Sum;
7695                         return Sum + 1;
7696                       });
7697 
7698   // FIXME: Use real size in bytes for call and ret instructions.
7699   if (RepeatedSequenceLocs[0].back()->isTerminator()) {
7700     for (outliner::Candidate &C : RepeatedSequenceLocs)
7701       C.setCallInfo(MachineOutlinerTailCall, 1);
7702 
7703     return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
7704                                       0, // Number of bytes to emit frame.
7705                                       MachineOutlinerTailCall // Type of frame.
7706     );
7707   }
7708 
7709   for (outliner::Candidate &C : RepeatedSequenceLocs)
7710     C.setCallInfo(MachineOutlinerDefault, 1);
7711 
7712   return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize, 1,
7713                                     MachineOutlinerDefault);
7714 }
7715 
7716 bool X86InstrInfo::isFunctionSafeToOutlineFrom(MachineFunction &MF,
7717                                            bool OutlineFromLinkOnceODRs) const {
7718   const Function &F = MF.getFunction();
7719 
7720   // Does the function use a red zone? If it does, then we can't risk messing
7721   // with the stack.
7722   if (!F.hasFnAttribute(Attribute::NoRedZone)) {
7723     // It could have a red zone. If it does, then we don't want to touch it.
7724     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
7725     if (!X86FI || X86FI->getUsesRedZone())
7726       return false;
7727   }
7728 
7729   // If we *don't* want to outline from things that could potentially be deduped
7730   // then return false.
7731   if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
7732       return false;
7733 
7734   // This function is viable for outlining, so return true.
7735   return true;
7736 }
7737 
7738 outliner::InstrType
7739 X86InstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,  unsigned Flags) const {
7740   MachineInstr &MI = *MIT;
7741   // Don't allow debug values to impact outlining type.
7742   if (MI.isDebugInstr() || MI.isIndirectDebugValue())
7743     return outliner::InstrType::Invisible;
7744 
7745   // At this point, KILL instructions don't really tell us much so we can go
7746   // ahead and skip over them.
7747   if (MI.isKill())
7748     return outliner::InstrType::Invisible;
7749 
7750   // Is this a tail call? If yes, we can outline as a tail call.
7751   if (isTailCall(MI))
7752     return outliner::InstrType::Legal;
7753 
7754   // Is this the terminator of a basic block?
7755   if (MI.isTerminator() || MI.isReturn()) {
7756 
7757     // Does its parent have any successors in its MachineFunction?
7758     if (MI.getParent()->succ_empty())
7759       return outliner::InstrType::Legal;
7760 
7761     // It does, so we can't tail call it.
7762     return outliner::InstrType::Illegal;
7763   }
7764 
7765   // Don't outline anything that modifies or reads from the stack pointer.
7766   //
7767   // FIXME: There are instructions which are being manually built without
7768   // explicit uses/defs so we also have to check the MCInstrDesc. We should be
7769   // able to remove the extra checks once those are fixed up. For example,
7770   // sometimes we might get something like %rax = POP64r 1. This won't be
7771   // caught by modifiesRegister or readsRegister even though the instruction
7772   // really ought to be formed so that modifiesRegister/readsRegister would
7773   // catch it.
7774   if (MI.modifiesRegister(X86::RSP, &RI) || MI.readsRegister(X86::RSP, &RI) ||
7775       MI.getDesc().hasImplicitUseOfPhysReg(X86::RSP) ||
7776       MI.getDesc().hasImplicitDefOfPhysReg(X86::RSP))
7777     return outliner::InstrType::Illegal;
7778 
7779   // Outlined calls change the instruction pointer, so don't read from it.
7780   if (MI.readsRegister(X86::RIP, &RI) ||
7781       MI.getDesc().hasImplicitUseOfPhysReg(X86::RIP) ||
7782       MI.getDesc().hasImplicitDefOfPhysReg(X86::RIP))
7783     return outliner::InstrType::Illegal;
7784 
7785   // Positions can't safely be outlined.
7786   if (MI.isPosition())
7787     return outliner::InstrType::Illegal;
7788 
7789   // Make sure none of the operands of this instruction do anything tricky.
7790   for (const MachineOperand &MOP : MI.operands())
7791     if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
7792         MOP.isTargetIndex())
7793       return outliner::InstrType::Illegal;
7794 
7795   return outliner::InstrType::Legal;
7796 }
7797 
7798 void X86InstrInfo::buildOutlinedFrame(MachineBasicBlock &MBB,
7799                                           MachineFunction &MF,
7800                                           const outliner::OutlinedFunction &OF)
7801                                           const {
7802   // If we're a tail call, we already have a return, so don't do anything.
7803   if (OF.FrameConstructionID == MachineOutlinerTailCall)
7804     return;
7805 
7806   // We're a normal call, so our sequence doesn't have a return instruction.
7807   // Add it in.
7808   MachineInstr *retq = BuildMI(MF, DebugLoc(), get(X86::RETQ));
7809   MBB.insert(MBB.end(), retq);
7810 }
7811 
7812 MachineBasicBlock::iterator
7813 X86InstrInfo::insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
7814                                  MachineBasicBlock::iterator &It,
7815                                  MachineFunction &MF,
7816                                  const outliner::Candidate &C) const {
7817   // Is it a tail call?
7818   if (C.CallConstructionID == MachineOutlinerTailCall) {
7819     // Yes, just insert a JMP.
7820     It = MBB.insert(It,
7821                   BuildMI(MF, DebugLoc(), get(X86::TAILJMPd64))
7822                       .addGlobalAddress(M.getNamedValue(MF.getName())));
7823   } else {
7824     // No, insert a call.
7825     It = MBB.insert(It,
7826                   BuildMI(MF, DebugLoc(), get(X86::CALL64pcrel32))
7827                       .addGlobalAddress(M.getNamedValue(MF.getName())));
7828   }
7829 
7830   return It;
7831 }
7832 
7833 #define GET_TII_HELPERS
7834 #include "X86GenInstrInfo.inc"
7835