LLVM  10.0.0svn
X86InstrInfo.cpp
Go to the documentation of this file.
1 //===-- X86InstrInfo.cpp - X86 Instruction Information --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the X86 implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86InstrInfo.h"
14 #include "X86.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrFoldTables.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Sequence.h"
30 #include "llvm/CodeGen/StackMaps.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/MC/MCInst.h"
38 #include "llvm/Support/Debug.h"
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "x86-instr-info"
46 
47 #define GET_INSTRINFO_CTOR_DTOR
48 #include "X86GenInstrInfo.inc"
49 
50 static cl::opt<bool>
51  NoFusing("disable-spill-fusing",
52  cl::desc("Disable fusing of spill code into instructions"),
53  cl::Hidden);
54 static cl::opt<bool>
55 PrintFailedFusing("print-failed-fuse-candidates",
56  cl::desc("Print instructions that the allocator wants to"
57  " fuse, but the X86 backend currently can't"),
58  cl::Hidden);
59 static cl::opt<bool>
60 ReMatPICStubLoad("remat-pic-stub-load",
61  cl::desc("Re-materialize load from stub in PIC mode"),
62  cl::init(false), cl::Hidden);
63 static cl::opt<unsigned>
64 PartialRegUpdateClearance("partial-reg-update-clearance",
65  cl::desc("Clearance between two register writes "
66  "for inserting XOR to avoid partial "
67  "register update"),
68  cl::init(64), cl::Hidden);
69 static cl::opt<unsigned>
70 UndefRegClearance("undef-reg-clearance",
71  cl::desc("How many idle instructions we would like before "
72  "certain undef register reads"),
73  cl::init(128), cl::Hidden);
74 
75 
76 // Pin the vtable to this file.
77 void X86InstrInfo::anchor() {}
78 
80  : X86GenInstrInfo((STI.isTarget64BitLP64() ? X86::ADJCALLSTACKDOWN64
81  : X86::ADJCALLSTACKDOWN32),
82  (STI.isTarget64BitLP64() ? X86::ADJCALLSTACKUP64
83  : X86::ADJCALLSTACKUP32),
84  X86::CATCHRET,
85  (STI.is64Bit() ? X86::RETQ : X86::RETL)),
86  Subtarget(STI), RI(STI.getTargetTriple()) {
87 }
88 
89 bool
91  unsigned &SrcReg, unsigned &DstReg,
92  unsigned &SubIdx) const {
93  switch (MI.getOpcode()) {
94  default: break;
95  case X86::MOVSX16rr8:
96  case X86::MOVZX16rr8:
97  case X86::MOVSX32rr8:
98  case X86::MOVZX32rr8:
99  case X86::MOVSX64rr8:
100  if (!Subtarget.is64Bit())
101  // It's not always legal to reference the low 8-bit of the larger
102  // register in 32-bit mode.
103  return false;
105  case X86::MOVSX32rr16:
106  case X86::MOVZX32rr16:
107  case X86::MOVSX64rr16:
108  case X86::MOVSX64rr32: {
109  if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
110  // Be conservative.
111  return false;
112  SrcReg = MI.getOperand(1).getReg();
113  DstReg = MI.getOperand(0).getReg();
114  switch (MI.getOpcode()) {
115  default: llvm_unreachable("Unreachable!");
116  case X86::MOVSX16rr8:
117  case X86::MOVZX16rr8:
118  case X86::MOVSX32rr8:
119  case X86::MOVZX32rr8:
120  case X86::MOVSX64rr8:
121  SubIdx = X86::sub_8bit;
122  break;
123  case X86::MOVSX32rr16:
124  case X86::MOVZX32rr16:
125  case X86::MOVSX64rr16:
126  SubIdx = X86::sub_16bit;
127  break;
128  case X86::MOVSX64rr32:
129  SubIdx = X86::sub_32bit;
130  break;
131  }
132  return true;
133  }
134  }
135  return false;
136 }
137 
139  const MachineFunction *MF = MI.getParent()->getParent();
141 
142  if (isFrameInstr(MI)) {
143  unsigned StackAlign = TFI->getStackAlignment();
144  int SPAdj = alignTo(getFrameSize(MI), StackAlign);
145  SPAdj -= getFrameAdjustment(MI);
146  if (!isFrameSetup(MI))
147  SPAdj = -SPAdj;
148  return SPAdj;
149  }
150 
151  // To know whether a call adjusts the stack, we need information
152  // that is bound to the following ADJCALLSTACKUP pseudo.
153  // Look for the next ADJCALLSTACKUP that follows the call.
154  if (MI.isCall()) {
155  const MachineBasicBlock *MBB = MI.getParent();
157  for (auto E = MBB->end(); I != E; ++I) {
158  if (I->getOpcode() == getCallFrameDestroyOpcode() ||
159  I->isCall())
160  break;
161  }
162 
163  // If we could not find a frame destroy opcode, then it has already
164  // been simplified, so we don't care.
165  if (I->getOpcode() != getCallFrameDestroyOpcode())
166  return 0;
167 
168  return -(I->getOperand(1).getImm());
169  }
170 
171  // Currently handle only PUSHes we can reasonably expect to see
172  // in call sequences
173  switch (MI.getOpcode()) {
174  default:
175  return 0;
176  case X86::PUSH32i8:
177  case X86::PUSH32r:
178  case X86::PUSH32rmm:
179  case X86::PUSH32rmr:
180  case X86::PUSHi32:
181  return 4;
182  case X86::PUSH64i8:
183  case X86::PUSH64r:
184  case X86::PUSH64rmm:
185  case X86::PUSH64rmr:
186  case X86::PUSH64i32:
187  return 8;
188  }
189 }
190 
191 /// Return true and the FrameIndex if the specified
192 /// operand and follow operands form a reference to the stack frame.
193 bool X86InstrInfo::isFrameOperand(const MachineInstr &MI, unsigned int Op,
194  int &FrameIndex) const {
195  if (MI.getOperand(Op + X86::AddrBaseReg).isFI() &&
196  MI.getOperand(Op + X86::AddrScaleAmt).isImm() &&
197  MI.getOperand(Op + X86::AddrIndexReg).isReg() &&
198  MI.getOperand(Op + X86::AddrDisp).isImm() &&
199  MI.getOperand(Op + X86::AddrScaleAmt).getImm() == 1 &&
200  MI.getOperand(Op + X86::AddrIndexReg).getReg() == 0 &&
201  MI.getOperand(Op + X86::AddrDisp).getImm() == 0) {
202  FrameIndex = MI.getOperand(Op + X86::AddrBaseReg).getIndex();
203  return true;
204  }
205  return false;
206 }
207 
208 static bool isFrameLoadOpcode(int Opcode, unsigned &MemBytes) {
209  switch (Opcode) {
210  default:
211  return false;
212  case X86::MOV8rm:
213  case X86::KMOVBkm:
214  MemBytes = 1;
215  return true;
216  case X86::MOV16rm:
217  case X86::KMOVWkm:
218  MemBytes = 2;
219  return true;
220  case X86::MOV32rm:
221  case X86::MOVSSrm:
222  case X86::MOVSSrm_alt:
223  case X86::VMOVSSrm:
224  case X86::VMOVSSrm_alt:
225  case X86::VMOVSSZrm:
226  case X86::VMOVSSZrm_alt:
227  case X86::KMOVDkm:
228  MemBytes = 4;
229  return true;
230  case X86::MOV64rm:
231  case X86::LD_Fp64m:
232  case X86::MOVSDrm:
233  case X86::MOVSDrm_alt:
234  case X86::VMOVSDrm:
235  case X86::VMOVSDrm_alt:
236  case X86::VMOVSDZrm:
237  case X86::VMOVSDZrm_alt:
238  case X86::MMX_MOVD64rm:
239  case X86::MMX_MOVQ64rm:
240  case X86::KMOVQkm:
241  MemBytes = 8;
242  return true;
243  case X86::MOVAPSrm:
244  case X86::MOVUPSrm:
245  case X86::MOVAPDrm:
246  case X86::MOVUPDrm:
247  case X86::MOVDQArm:
248  case X86::MOVDQUrm:
249  case X86::VMOVAPSrm:
250  case X86::VMOVUPSrm:
251  case X86::VMOVAPDrm:
252  case X86::VMOVUPDrm:
253  case X86::VMOVDQArm:
254  case X86::VMOVDQUrm:
255  case X86::VMOVAPSZ128rm:
256  case X86::VMOVUPSZ128rm:
257  case X86::VMOVAPSZ128rm_NOVLX:
258  case X86::VMOVUPSZ128rm_NOVLX:
259  case X86::VMOVAPDZ128rm:
260  case X86::VMOVUPDZ128rm:
261  case X86::VMOVDQU8Z128rm:
262  case X86::VMOVDQU16Z128rm:
263  case X86::VMOVDQA32Z128rm:
264  case X86::VMOVDQU32Z128rm:
265  case X86::VMOVDQA64Z128rm:
266  case X86::VMOVDQU64Z128rm:
267  MemBytes = 16;
268  return true;
269  case X86::VMOVAPSYrm:
270  case X86::VMOVUPSYrm:
271  case X86::VMOVAPDYrm:
272  case X86::VMOVUPDYrm:
273  case X86::VMOVDQAYrm:
274  case X86::VMOVDQUYrm:
275  case X86::VMOVAPSZ256rm:
276  case X86::VMOVUPSZ256rm:
277  case X86::VMOVAPSZ256rm_NOVLX:
278  case X86::VMOVUPSZ256rm_NOVLX:
279  case X86::VMOVAPDZ256rm:
280  case X86::VMOVUPDZ256rm:
281  case X86::VMOVDQU8Z256rm:
282  case X86::VMOVDQU16Z256rm:
283  case X86::VMOVDQA32Z256rm:
284  case X86::VMOVDQU32Z256rm:
285  case X86::VMOVDQA64Z256rm:
286  case X86::VMOVDQU64Z256rm:
287  MemBytes = 32;
288  return true;
289  case X86::VMOVAPSZrm:
290  case X86::VMOVUPSZrm:
291  case X86::VMOVAPDZrm:
292  case X86::VMOVUPDZrm:
293  case X86::VMOVDQU8Zrm:
294  case X86::VMOVDQU16Zrm:
295  case X86::VMOVDQA32Zrm:
296  case X86::VMOVDQU32Zrm:
297  case X86::VMOVDQA64Zrm:
298  case X86::VMOVDQU64Zrm:
299  MemBytes = 64;
300  return true;
301  }
302 }
303 
304 static bool isFrameStoreOpcode(int Opcode, unsigned &MemBytes) {
305  switch (Opcode) {
306  default:
307  return false;
308  case X86::MOV8mr:
309  case X86::KMOVBmk:
310  MemBytes = 1;
311  return true;
312  case X86::MOV16mr:
313  case X86::KMOVWmk:
314  MemBytes = 2;
315  return true;
316  case X86::MOV32mr:
317  case X86::MOVSSmr:
318  case X86::VMOVSSmr:
319  case X86::VMOVSSZmr:
320  case X86::KMOVDmk:
321  MemBytes = 4;
322  return true;
323  case X86::MOV64mr:
324  case X86::ST_FpP64m:
325  case X86::MOVSDmr:
326  case X86::VMOVSDmr:
327  case X86::VMOVSDZmr:
328  case X86::MMX_MOVD64mr:
329  case X86::MMX_MOVQ64mr:
330  case X86::MMX_MOVNTQmr:
331  case X86::KMOVQmk:
332  MemBytes = 8;
333  return true;
334  case X86::MOVAPSmr:
335  case X86::MOVUPSmr:
336  case X86::MOVAPDmr:
337  case X86::MOVUPDmr:
338  case X86::MOVDQAmr:
339  case X86::MOVDQUmr:
340  case X86::VMOVAPSmr:
341  case X86::VMOVUPSmr:
342  case X86::VMOVAPDmr:
343  case X86::VMOVUPDmr:
344  case X86::VMOVDQAmr:
345  case X86::VMOVDQUmr:
346  case X86::VMOVUPSZ128mr:
347  case X86::VMOVAPSZ128mr:
348  case X86::VMOVUPSZ128mr_NOVLX:
349  case X86::VMOVAPSZ128mr_NOVLX:
350  case X86::VMOVUPDZ128mr:
351  case X86::VMOVAPDZ128mr:
352  case X86::VMOVDQA32Z128mr:
353  case X86::VMOVDQU32Z128mr:
354  case X86::VMOVDQA64Z128mr:
355  case X86::VMOVDQU64Z128mr:
356  case X86::VMOVDQU8Z128mr:
357  case X86::VMOVDQU16Z128mr:
358  MemBytes = 16;
359  return true;
360  case X86::VMOVUPSYmr:
361  case X86::VMOVAPSYmr:
362  case X86::VMOVUPDYmr:
363  case X86::VMOVAPDYmr:
364  case X86::VMOVDQUYmr:
365  case X86::VMOVDQAYmr:
366  case X86::VMOVUPSZ256mr:
367  case X86::VMOVAPSZ256mr:
368  case X86::VMOVUPSZ256mr_NOVLX:
369  case X86::VMOVAPSZ256mr_NOVLX:
370  case X86::VMOVUPDZ256mr:
371  case X86::VMOVAPDZ256mr:
372  case X86::VMOVDQU8Z256mr:
373  case X86::VMOVDQU16Z256mr:
374  case X86::VMOVDQA32Z256mr:
375  case X86::VMOVDQU32Z256mr:
376  case X86::VMOVDQA64Z256mr:
377  case X86::VMOVDQU64Z256mr:
378  MemBytes = 32;
379  return true;
380  case X86::VMOVUPSZmr:
381  case X86::VMOVAPSZmr:
382  case X86::VMOVUPDZmr:
383  case X86::VMOVAPDZmr:
384  case X86::VMOVDQU8Zmr:
385  case X86::VMOVDQU16Zmr:
386  case X86::VMOVDQA32Zmr:
387  case X86::VMOVDQU32Zmr:
388  case X86::VMOVDQA64Zmr:
389  case X86::VMOVDQU64Zmr:
390  MemBytes = 64;
391  return true;
392  }
393  return false;
394 }
395 
397  int &FrameIndex) const {
398  unsigned Dummy;
399  return X86InstrInfo::isLoadFromStackSlot(MI, FrameIndex, Dummy);
400 }
401 
403  int &FrameIndex,
404  unsigned &MemBytes) const {
405  if (isFrameLoadOpcode(MI.getOpcode(), MemBytes))
406  if (MI.getOperand(0).getSubReg() == 0 && isFrameOperand(MI, 1, FrameIndex))
407  return MI.getOperand(0).getReg();
408  return 0;
409 }
410 
412  int &FrameIndex) const {
413  unsigned Dummy;
414  if (isFrameLoadOpcode(MI.getOpcode(), Dummy)) {
415  unsigned Reg;
416  if ((Reg = isLoadFromStackSlot(MI, FrameIndex)))
417  return Reg;
418  // Check for post-frame index elimination operations
420  if (hasLoadFromStackSlot(MI, Accesses)) {
421  FrameIndex =
422  cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
423  ->getFrameIndex();
424  return 1;
425  }
426  }
427  return 0;
428 }
429 
431  int &FrameIndex) const {
432  unsigned Dummy;
433  return X86InstrInfo::isStoreToStackSlot(MI, FrameIndex, Dummy);
434 }
435 
437  int &FrameIndex,
438  unsigned &MemBytes) const {
439  if (isFrameStoreOpcode(MI.getOpcode(), MemBytes))
440  if (MI.getOperand(X86::AddrNumOperands).getSubReg() == 0 &&
441  isFrameOperand(MI, 0, FrameIndex))
443  return 0;
444 }
445 
447  int &FrameIndex) const {
448  unsigned Dummy;
449  if (isFrameStoreOpcode(MI.getOpcode(), Dummy)) {
450  unsigned Reg;
451  if ((Reg = isStoreToStackSlot(MI, FrameIndex)))
452  return Reg;
453  // Check for post-frame index elimination operations
455  if (hasStoreToStackSlot(MI, Accesses)) {
456  FrameIndex =
457  cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
458  ->getFrameIndex();
459  return 1;
460  }
461  }
462  return 0;
463 }
464 
465 /// Return true if register is PIC base; i.e.g defined by X86::MOVPC32r.
466 static bool regIsPICBase(unsigned BaseReg, const MachineRegisterInfo &MRI) {
467  // Don't waste compile time scanning use-def chains of physregs.
468  if (!Register::isVirtualRegister(BaseReg))
469  return false;
470  bool isPICBase = false;
472  E = MRI.def_instr_end(); I != E; ++I) {
473  MachineInstr *DefMI = &*I;
474  if (DefMI->getOpcode() != X86::MOVPC32r)
475  return false;
476  assert(!isPICBase && "More than one PIC base?");
477  isPICBase = true;
478  }
479  return isPICBase;
480 }
481 
483  AliasAnalysis *AA) const {
484  switch (MI.getOpcode()) {
485  default:
486  // This function should only be called for opcodes with the ReMaterializable
487  // flag set.
488  llvm_unreachable("Unknown rematerializable operation!");
489  break;
490 
491  case X86::LOAD_STACK_GUARD:
492  case X86::AVX1_SETALLONES:
493  case X86::AVX2_SETALLONES:
494  case X86::AVX512_128_SET0:
495  case X86::AVX512_256_SET0:
496  case X86::AVX512_512_SET0:
497  case X86::AVX512_512_SETALLONES:
498  case X86::AVX512_FsFLD0SD:
499  case X86::AVX512_FsFLD0SS:
500  case X86::AVX512_FsFLD0F128:
501  case X86::AVX_SET0:
502  case X86::FsFLD0SD:
503  case X86::FsFLD0SS:
504  case X86::FsFLD0F128:
505  case X86::KSET0D:
506  case X86::KSET0Q:
507  case X86::KSET0W:
508  case X86::KSET1D:
509  case X86::KSET1Q:
510  case X86::KSET1W:
511  case X86::MMX_SET0:
512  case X86::MOV32ImmSExti8:
513  case X86::MOV32r0:
514  case X86::MOV32r1:
515  case X86::MOV32r_1:
516  case X86::MOV32ri64:
517  case X86::MOV64ImmSExti8:
518  case X86::V_SET0:
519  case X86::V_SETALLONES:
520  case X86::MOV16ri:
521  case X86::MOV32ri:
522  case X86::MOV64ri:
523  case X86::MOV64ri32:
524  case X86::MOV8ri:
525  return true;
526 
527  case X86::MOV8rm:
528  case X86::MOV8rm_NOREX:
529  case X86::MOV16rm:
530  case X86::MOV32rm:
531  case X86::MOV64rm:
532  case X86::MOVSSrm:
533  case X86::MOVSSrm_alt:
534  case X86::MOVSDrm:
535  case X86::MOVSDrm_alt:
536  case X86::MOVAPSrm:
537  case X86::MOVUPSrm:
538  case X86::MOVAPDrm:
539  case X86::MOVUPDrm:
540  case X86::MOVDQArm:
541  case X86::MOVDQUrm:
542  case X86::VMOVSSrm:
543  case X86::VMOVSSrm_alt:
544  case X86::VMOVSDrm:
545  case X86::VMOVSDrm_alt:
546  case X86::VMOVAPSrm:
547  case X86::VMOVUPSrm:
548  case X86::VMOVAPDrm:
549  case X86::VMOVUPDrm:
550  case X86::VMOVDQArm:
551  case X86::VMOVDQUrm:
552  case X86::VMOVAPSYrm:
553  case X86::VMOVUPSYrm:
554  case X86::VMOVAPDYrm:
555  case X86::VMOVUPDYrm:
556  case X86::VMOVDQAYrm:
557  case X86::VMOVDQUYrm:
558  case X86::MMX_MOVD64rm:
559  case X86::MMX_MOVQ64rm:
560  // AVX-512
561  case X86::VMOVSSZrm:
562  case X86::VMOVSSZrm_alt:
563  case X86::VMOVSDZrm:
564  case X86::VMOVSDZrm_alt:
565  case X86::VMOVAPDZ128rm:
566  case X86::VMOVAPDZ256rm:
567  case X86::VMOVAPDZrm:
568  case X86::VMOVAPSZ128rm:
569  case X86::VMOVAPSZ256rm:
570  case X86::VMOVAPSZ128rm_NOVLX:
571  case X86::VMOVAPSZ256rm_NOVLX:
572  case X86::VMOVAPSZrm:
573  case X86::VMOVDQA32Z128rm:
574  case X86::VMOVDQA32Z256rm:
575  case X86::VMOVDQA32Zrm:
576  case X86::VMOVDQA64Z128rm:
577  case X86::VMOVDQA64Z256rm:
578  case X86::VMOVDQA64Zrm:
579  case X86::VMOVDQU16Z128rm:
580  case X86::VMOVDQU16Z256rm:
581  case X86::VMOVDQU16Zrm:
582  case X86::VMOVDQU32Z128rm:
583  case X86::VMOVDQU32Z256rm:
584  case X86::VMOVDQU32Zrm:
585  case X86::VMOVDQU64Z128rm:
586  case X86::VMOVDQU64Z256rm:
587  case X86::VMOVDQU64Zrm:
588  case X86::VMOVDQU8Z128rm:
589  case X86::VMOVDQU8Z256rm:
590  case X86::VMOVDQU8Zrm:
591  case X86::VMOVUPDZ128rm:
592  case X86::VMOVUPDZ256rm:
593  case X86::VMOVUPDZrm:
594  case X86::VMOVUPSZ128rm:
595  case X86::VMOVUPSZ256rm:
596  case X86::VMOVUPSZ128rm_NOVLX:
597  case X86::VMOVUPSZ256rm_NOVLX:
598  case X86::VMOVUPSZrm: {
599  // Loads from constant pools are trivially rematerializable.
600  if (MI.getOperand(1 + X86::AddrBaseReg).isReg() &&
601  MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
602  MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
603  MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
605  Register BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
606  if (BaseReg == 0 || BaseReg == X86::RIP)
607  return true;
608  // Allow re-materialization of PIC load.
610  return false;
611  const MachineFunction &MF = *MI.getParent()->getParent();
612  const MachineRegisterInfo &MRI = MF.getRegInfo();
613  return regIsPICBase(BaseReg, MRI);
614  }
615  return false;
616  }
617 
618  case X86::LEA32r:
619  case X86::LEA64r: {
620  if (MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
621  MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
622  MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
623  !MI.getOperand(1 + X86::AddrDisp).isReg()) {
624  // lea fi#, lea GV, etc. are all rematerializable.
625  if (!MI.getOperand(1 + X86::AddrBaseReg).isReg())
626  return true;
627  Register BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
628  if (BaseReg == 0)
629  return true;
630  // Allow re-materialization of lea PICBase + x.
631  const MachineFunction &MF = *MI.getParent()->getParent();
632  const MachineRegisterInfo &MRI = MF.getRegInfo();
633  return regIsPICBase(BaseReg, MRI);
634  }
635  return false;
636  }
637  }
638 }
639 
642  unsigned DestReg, unsigned SubIdx,
643  const MachineInstr &Orig,
644  const TargetRegisterInfo &TRI) const {
645  bool ClobbersEFLAGS = Orig.modifiesRegister(X86::EFLAGS, &TRI);
646  if (ClobbersEFLAGS && !isSafeToClobberEFLAGS(MBB, I)) {
647  // The instruction clobbers EFLAGS. Re-materialize as MOV32ri to avoid side
648  // effects.
649  int Value;
650  switch (Orig.getOpcode()) {
651  case X86::MOV32r0: Value = 0; break;
652  case X86::MOV32r1: Value = 1; break;
653  case X86::MOV32r_1: Value = -1; break;
654  default:
655  llvm_unreachable("Unexpected instruction!");
656  }
657 
658  const DebugLoc &DL = Orig.getDebugLoc();
659  BuildMI(MBB, I, DL, get(X86::MOV32ri))
660  .add(Orig.getOperand(0))
661  .addImm(Value);
662  } else {
663  MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
664  MBB.insert(I, MI);
665  }
666 
667  MachineInstr &NewMI = *std::prev(I);
668  NewMI.substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
669 }
670 
671 /// True if MI has a condition code def, e.g. EFLAGS, that is not marked dead.
673  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
674  MachineOperand &MO = MI.getOperand(i);
675  if (MO.isReg() && MO.isDef() &&
676  MO.getReg() == X86::EFLAGS && !MO.isDead()) {
677  return true;
678  }
679  }
680  return false;
681 }
682 
683 /// Check whether the shift count for a machine operand is non-zero.
684 inline static unsigned getTruncatedShiftCount(const MachineInstr &MI,
685  unsigned ShiftAmtOperandIdx) {
686  // The shift count is six bits with the REX.W prefix and five bits without.
687  unsigned ShiftCountMask = (MI.getDesc().TSFlags & X86II::REX_W) ? 63 : 31;
688  unsigned Imm = MI.getOperand(ShiftAmtOperandIdx).getImm();
689  return Imm & ShiftCountMask;
690 }
691 
692 /// Check whether the given shift count is appropriate
693 /// can be represented by a LEA instruction.
694 inline static bool isTruncatedShiftCountForLEA(unsigned ShAmt) {
695  // Left shift instructions can be transformed into load-effective-address
696  // instructions if we can encode them appropriately.
697  // A LEA instruction utilizes a SIB byte to encode its scale factor.
698  // The SIB.scale field is two bits wide which means that we can encode any
699  // shift amount less than 4.
700  return ShAmt < 4 && ShAmt > 0;
701 }
702 
704  unsigned Opc, bool AllowSP, Register &NewSrc,
705  bool &isKill, MachineOperand &ImplicitOp,
706  LiveVariables *LV) const {
707  MachineFunction &MF = *MI.getParent()->getParent();
708  const TargetRegisterClass *RC;
709  if (AllowSP) {
710  RC = Opc != X86::LEA32r ? &X86::GR64RegClass : &X86::GR32RegClass;
711  } else {
712  RC = Opc != X86::LEA32r ?
713  &X86::GR64_NOSPRegClass : &X86::GR32_NOSPRegClass;
714  }
715  Register SrcReg = Src.getReg();
716 
717  // For both LEA64 and LEA32 the register already has essentially the right
718  // type (32-bit or 64-bit) we may just need to forbid SP.
719  if (Opc != X86::LEA64_32r) {
720  NewSrc = SrcReg;
721  isKill = Src.isKill();
722  assert(!Src.isUndef() && "Undef op doesn't need optimization");
723 
724  if (Register::isVirtualRegister(NewSrc) &&
725  !MF.getRegInfo().constrainRegClass(NewSrc, RC))
726  return false;
727 
728  return true;
729  }
730 
731  // This is for an LEA64_32r and incoming registers are 32-bit. One way or
732  // another we need to add 64-bit registers to the final MI.
733  if (Register::isPhysicalRegister(SrcReg)) {
734  ImplicitOp = Src;
735  ImplicitOp.setImplicit();
736 
737  NewSrc = getX86SubSuperRegister(Src.getReg(), 64);
738  isKill = Src.isKill();
739  assert(!Src.isUndef() && "Undef op doesn't need optimization");
740  } else {
741  // Virtual register of the wrong class, we have to create a temporary 64-bit
742  // vreg to feed into the LEA.
743  NewSrc = MF.getRegInfo().createVirtualRegister(RC);
744  MachineInstr *Copy =
745  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(TargetOpcode::COPY))
746  .addReg(NewSrc, RegState::Define | RegState::Undef, X86::sub_32bit)
747  .add(Src);
748 
749  // Which is obviously going to be dead after we're done with it.
750  isKill = true;
751 
752  if (LV)
753  LV->replaceKillInstruction(SrcReg, MI, *Copy);
754  }
755 
756  // We've set all the parameters without issue.
757  return true;
758 }
759 
760 MachineInstr *X86InstrInfo::convertToThreeAddressWithLEA(
761  unsigned MIOpc, MachineFunction::iterator &MFI, MachineInstr &MI,
762  LiveVariables *LV, bool Is8BitOp) const {
763  // We handle 8-bit adds and various 16-bit opcodes in the switch below.
764  MachineRegisterInfo &RegInfo = MFI->getParent()->getRegInfo();
765  assert((Is8BitOp || RegInfo.getTargetRegisterInfo()->getRegSizeInBits(
766  *RegInfo.getRegClass(MI.getOperand(0).getReg())) == 16) &&
767  "Unexpected type for LEA transform");
768 
769  // TODO: For a 32-bit target, we need to adjust the LEA variables with
770  // something like this:
771  // Opcode = X86::LEA32r;
772  // InRegLEA = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
773  // OutRegLEA =
774  // Is8BitOp ? RegInfo.createVirtualRegister(&X86::GR32ABCD_RegClass)
775  // : RegInfo.createVirtualRegister(&X86::GR32RegClass);
776  if (!Subtarget.is64Bit())
777  return nullptr;
778 
779  unsigned Opcode = X86::LEA64_32r;
780  Register InRegLEA = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
781  Register OutRegLEA = RegInfo.createVirtualRegister(&X86::GR32RegClass);
782 
783  // Build and insert into an implicit UNDEF value. This is OK because
784  // we will be shifting and then extracting the lower 8/16-bits.
785  // This has the potential to cause partial register stall. e.g.
786  // movw (%rbp,%rcx,2), %dx
787  // leal -65(%rdx), %esi
788  // But testing has shown this *does* help performance in 64-bit mode (at
789  // least on modern x86 machines).
791  Register Dest = MI.getOperand(0).getReg();
792  Register Src = MI.getOperand(1).getReg();
793  bool IsDead = MI.getOperand(0).isDead();
794  bool IsKill = MI.getOperand(1).isKill();
795  unsigned SubReg = Is8BitOp ? X86::sub_8bit : X86::sub_16bit;
796  assert(!MI.getOperand(1).isUndef() && "Undef op doesn't need optimization");
797  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), InRegLEA);
798  MachineInstr *InsMI =
799  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
800  .addReg(InRegLEA, RegState::Define, SubReg)
801  .addReg(Src, getKillRegState(IsKill));
802 
803  MachineInstrBuilder MIB =
804  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(Opcode), OutRegLEA);
805  switch (MIOpc) {
806  default: llvm_unreachable("Unreachable!");
807  case X86::SHL8ri:
808  case X86::SHL16ri: {
809  unsigned ShAmt = MI.getOperand(2).getImm();
810  MIB.addReg(0).addImm(1ULL << ShAmt)
811  .addReg(InRegLEA, RegState::Kill).addImm(0).addReg(0);
812  break;
813  }
814  case X86::INC8r:
815  case X86::INC16r:
816  addRegOffset(MIB, InRegLEA, true, 1);
817  break;
818  case X86::DEC8r:
819  case X86::DEC16r:
820  addRegOffset(MIB, InRegLEA, true, -1);
821  break;
822  case X86::ADD8ri:
823  case X86::ADD8ri_DB:
824  case X86::ADD16ri:
825  case X86::ADD16ri8:
826  case X86::ADD16ri_DB:
827  case X86::ADD16ri8_DB:
828  addRegOffset(MIB, InRegLEA, true, MI.getOperand(2).getImm());
829  break;
830  case X86::ADD8rr:
831  case X86::ADD8rr_DB:
832  case X86::ADD16rr:
833  case X86::ADD16rr_DB: {
834  Register Src2 = MI.getOperand(2).getReg();
835  bool IsKill2 = MI.getOperand(2).isKill();
836  assert(!MI.getOperand(2).isUndef() && "Undef op doesn't need optimization");
837  unsigned InRegLEA2 = 0;
838  MachineInstr *InsMI2 = nullptr;
839  if (Src == Src2) {
840  // ADD8rr/ADD16rr killed %reg1028, %reg1028
841  // just a single insert_subreg.
842  addRegReg(MIB, InRegLEA, true, InRegLEA, false);
843  } else {
844  if (Subtarget.is64Bit())
845  InRegLEA2 = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
846  else
847  InRegLEA2 = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
848  // Build and insert into an implicit UNDEF value. This is OK because
849  // we will be shifting and then extracting the lower 8/16-bits.
850  BuildMI(*MFI, &*MIB, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), InRegLEA2);
851  InsMI2 = BuildMI(*MFI, &*MIB, MI.getDebugLoc(), get(TargetOpcode::COPY))
852  .addReg(InRegLEA2, RegState::Define, SubReg)
853  .addReg(Src2, getKillRegState(IsKill2));
854  addRegReg(MIB, InRegLEA, true, InRegLEA2, true);
855  }
856  if (LV && IsKill2 && InsMI2)
857  LV->replaceKillInstruction(Src2, MI, *InsMI2);
858  break;
859  }
860  }
861 
862  MachineInstr *NewMI = MIB;
863  MachineInstr *ExtMI =
864  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
865  .addReg(Dest, RegState::Define | getDeadRegState(IsDead))
866  .addReg(OutRegLEA, RegState::Kill, SubReg);
867 
868  if (LV) {
869  // Update live variables.
870  LV->getVarInfo(InRegLEA).Kills.push_back(NewMI);
871  LV->getVarInfo(OutRegLEA).Kills.push_back(ExtMI);
872  if (IsKill)
873  LV->replaceKillInstruction(Src, MI, *InsMI);
874  if (IsDead)
875  LV->replaceKillInstruction(Dest, MI, *ExtMI);
876  }
877 
878  return ExtMI;
879 }
880 
881 /// This method must be implemented by targets that
882 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
883 /// may be able to convert a two-address instruction into a true
884 /// three-address instruction on demand. This allows the X86 target (for
885 /// example) to convert ADD and SHL instructions into LEA instructions if they
886 /// would require register copies due to two-addressness.
887 ///
888 /// This method returns a null pointer if the transformation cannot be
889 /// performed, otherwise it returns the new instruction.
890 ///
891 MachineInstr *
893  MachineInstr &MI, LiveVariables *LV) const {
894  // The following opcodes also sets the condition code register(s). Only
895  // convert them to equivalent lea if the condition code register def's
896  // are dead!
897  if (hasLiveCondCodeDef(MI))
898  return nullptr;
899 
900  MachineFunction &MF = *MI.getParent()->getParent();
901  // All instructions input are two-addr instructions. Get the known operands.
902  const MachineOperand &Dest = MI.getOperand(0);
903  const MachineOperand &Src = MI.getOperand(1);
904 
905  // Ideally, operations with undef should be folded before we get here, but we
906  // can't guarantee it. Bail out because optimizing undefs is a waste of time.
907  // Without this, we have to forward undef state to new register operands to
908  // avoid machine verifier errors.
909  if (Src.isUndef())
910  return nullptr;
911  if (MI.getNumOperands() > 2)
912  if (MI.getOperand(2).isReg() && MI.getOperand(2).isUndef())
913  return nullptr;
914 
915  MachineInstr *NewMI = nullptr;
916  bool Is64Bit = Subtarget.is64Bit();
917 
918  bool Is8BitOp = false;
919  unsigned MIOpc = MI.getOpcode();
920  switch (MIOpc) {
921  default: llvm_unreachable("Unreachable!");
922  case X86::SHL64ri: {
923  assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
924  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
925  if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
926 
927  // LEA can't handle RSP.
928  if (Register::isVirtualRegister(Src.getReg()) &&
929  !MF.getRegInfo().constrainRegClass(Src.getReg(),
930  &X86::GR64_NOSPRegClass))
931  return nullptr;
932 
933  NewMI = BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r))
934  .add(Dest)
935  .addReg(0)
936  .addImm(1ULL << ShAmt)
937  .add(Src)
938  .addImm(0)
939  .addReg(0);
940  break;
941  }
942  case X86::SHL32ri: {
943  assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
944  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
945  if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
946 
947  unsigned Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
948 
949  // LEA can't handle ESP.
950  bool isKill;
951  Register SrcReg;
952  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
953  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
954  SrcReg, isKill, ImplicitOp, LV))
955  return nullptr;
956 
957  MachineInstrBuilder MIB =
958  BuildMI(MF, MI.getDebugLoc(), get(Opc))
959  .add(Dest)
960  .addReg(0)
961  .addImm(1ULL << ShAmt)
962  .addReg(SrcReg, getKillRegState(isKill))
963  .addImm(0)
964  .addReg(0);
965  if (ImplicitOp.getReg() != 0)
966  MIB.add(ImplicitOp);
967  NewMI = MIB;
968 
969  break;
970  }
971  case X86::SHL8ri:
972  Is8BitOp = true;
974  case X86::SHL16ri: {
975  assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
976  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
977  if (!isTruncatedShiftCountForLEA(ShAmt))
978  return nullptr;
979  return convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV, Is8BitOp);
980  }
981  case X86::INC64r:
982  case X86::INC32r: {
983  assert(MI.getNumOperands() >= 2 && "Unknown inc instruction!");
984  unsigned Opc = MIOpc == X86::INC64r ? X86::LEA64r :
985  (Is64Bit ? X86::LEA64_32r : X86::LEA32r);
986  bool isKill;
987  Register SrcReg;
988  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
989  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false, SrcReg, isKill,
990  ImplicitOp, LV))
991  return nullptr;
992 
993  MachineInstrBuilder MIB =
994  BuildMI(MF, MI.getDebugLoc(), get(Opc))
995  .add(Dest)
996  .addReg(SrcReg, getKillRegState(isKill));
997  if (ImplicitOp.getReg() != 0)
998  MIB.add(ImplicitOp);
999 
1000  NewMI = addOffset(MIB, 1);
1001  break;
1002  }
1003  case X86::DEC64r:
1004  case X86::DEC32r: {
1005  assert(MI.getNumOperands() >= 2 && "Unknown dec instruction!");
1006  unsigned Opc = MIOpc == X86::DEC64r ? X86::LEA64r
1007  : (Is64Bit ? X86::LEA64_32r : X86::LEA32r);
1008 
1009  bool isKill;
1010  Register SrcReg;
1011  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1012  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false, SrcReg, isKill,
1013  ImplicitOp, LV))
1014  return nullptr;
1015 
1016  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1017  .add(Dest)
1018  .addReg(SrcReg, getKillRegState(isKill));
1019  if (ImplicitOp.getReg() != 0)
1020  MIB.add(ImplicitOp);
1021 
1022  NewMI = addOffset(MIB, -1);
1023 
1024  break;
1025  }
1026  case X86::DEC8r:
1027  case X86::INC8r:
1028  Is8BitOp = true;
1030  case X86::DEC16r:
1031  case X86::INC16r:
1032  return convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV, Is8BitOp);
1033  case X86::ADD64rr:
1034  case X86::ADD64rr_DB:
1035  case X86::ADD32rr:
1036  case X86::ADD32rr_DB: {
1037  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1038  unsigned Opc;
1039  if (MIOpc == X86::ADD64rr || MIOpc == X86::ADD64rr_DB)
1040  Opc = X86::LEA64r;
1041  else
1042  Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1043 
1044  bool isKill;
1045  Register SrcReg;
1046  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1047  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1048  SrcReg, isKill, ImplicitOp, LV))
1049  return nullptr;
1050 
1051  const MachineOperand &Src2 = MI.getOperand(2);
1052  bool isKill2;
1053  Register SrcReg2;
1054  MachineOperand ImplicitOp2 = MachineOperand::CreateReg(0, false);
1055  if (!classifyLEAReg(MI, Src2, Opc, /*AllowSP=*/ false,
1056  SrcReg2, isKill2, ImplicitOp2, LV))
1057  return nullptr;
1058 
1059  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc)).add(Dest);
1060  if (ImplicitOp.getReg() != 0)
1061  MIB.add(ImplicitOp);
1062  if (ImplicitOp2.getReg() != 0)
1063  MIB.add(ImplicitOp2);
1064 
1065  NewMI = addRegReg(MIB, SrcReg, isKill, SrcReg2, isKill2);
1066  if (LV && Src2.isKill())
1067  LV->replaceKillInstruction(SrcReg2, MI, *NewMI);
1068  break;
1069  }
1070  case X86::ADD8rr:
1071  case X86::ADD8rr_DB:
1072  Is8BitOp = true;
1074  case X86::ADD16rr:
1075  case X86::ADD16rr_DB:
1076  return convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV, Is8BitOp);
1077  case X86::ADD64ri32:
1078  case X86::ADD64ri8:
1079  case X86::ADD64ri32_DB:
1080  case X86::ADD64ri8_DB:
1081  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1082  NewMI = addOffset(
1083  BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r)).add(Dest).add(Src),
1084  MI.getOperand(2));
1085  break;
1086  case X86::ADD32ri:
1087  case X86::ADD32ri8:
1088  case X86::ADD32ri_DB:
1089  case X86::ADD32ri8_DB: {
1090  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1091  unsigned Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1092 
1093  bool isKill;
1094  Register SrcReg;
1095  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1096  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1097  SrcReg, isKill, ImplicitOp, LV))
1098  return nullptr;
1099 
1100  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1101  .add(Dest)
1102  .addReg(SrcReg, getKillRegState(isKill));
1103  if (ImplicitOp.getReg() != 0)
1104  MIB.add(ImplicitOp);
1105 
1106  NewMI = addOffset(MIB, MI.getOperand(2));
1107  break;
1108  }
1109  case X86::ADD8ri:
1110  case X86::ADD8ri_DB:
1111  Is8BitOp = true;
1113  case X86::ADD16ri:
1114  case X86::ADD16ri8:
1115  case X86::ADD16ri_DB:
1116  case X86::ADD16ri8_DB:
1117  return convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV, Is8BitOp);
1118  case X86::SUB8ri:
1119  case X86::SUB16ri8:
1120  case X86::SUB16ri:
1121  /// FIXME: Support these similar to ADD8ri/ADD16ri*.
1122  return nullptr;
1123  case X86::SUB32ri8:
1124  case X86::SUB32ri: {
1125  int64_t Imm = MI.getOperand(2).getImm();
1126  if (!isInt<32>(-Imm))
1127  return nullptr;
1128 
1129  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1130  unsigned Opc = Is64Bit ? X86::LEA64_32r : X86::LEA32r;
1131 
1132  bool isKill;
1133  Register SrcReg;
1134  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1135  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1136  SrcReg, isKill, ImplicitOp, LV))
1137  return nullptr;
1138 
1139  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1140  .add(Dest)
1141  .addReg(SrcReg, getKillRegState(isKill));
1142  if (ImplicitOp.getReg() != 0)
1143  MIB.add(ImplicitOp);
1144 
1145  NewMI = addOffset(MIB, -Imm);
1146  break;
1147  }
1148 
1149  case X86::SUB64ri8:
1150  case X86::SUB64ri32: {
1151  int64_t Imm = MI.getOperand(2).getImm();
1152  if (!isInt<32>(-Imm))
1153  return nullptr;
1154 
1155  assert(MI.getNumOperands() >= 3 && "Unknown sub instruction!");
1156 
1157  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(),
1158  get(X86::LEA64r)).add(Dest).add(Src);
1159  NewMI = addOffset(MIB, -Imm);
1160  break;
1161  }
1162 
1163  case X86::VMOVDQU8Z128rmk:
1164  case X86::VMOVDQU8Z256rmk:
1165  case X86::VMOVDQU8Zrmk:
1166  case X86::VMOVDQU16Z128rmk:
1167  case X86::VMOVDQU16Z256rmk:
1168  case X86::VMOVDQU16Zrmk:
1169  case X86::VMOVDQU32Z128rmk: case X86::VMOVDQA32Z128rmk:
1170  case X86::VMOVDQU32Z256rmk: case X86::VMOVDQA32Z256rmk:
1171  case X86::VMOVDQU32Zrmk: case X86::VMOVDQA32Zrmk:
1172  case X86::VMOVDQU64Z128rmk: case X86::VMOVDQA64Z128rmk:
1173  case X86::VMOVDQU64Z256rmk: case X86::VMOVDQA64Z256rmk:
1174  case X86::VMOVDQU64Zrmk: case X86::VMOVDQA64Zrmk:
1175  case X86::VMOVUPDZ128rmk: case X86::VMOVAPDZ128rmk:
1176  case X86::VMOVUPDZ256rmk: case X86::VMOVAPDZ256rmk:
1177  case X86::VMOVUPDZrmk: case X86::VMOVAPDZrmk:
1178  case X86::VMOVUPSZ128rmk: case X86::VMOVAPSZ128rmk:
1179  case X86::VMOVUPSZ256rmk: case X86::VMOVAPSZ256rmk:
1180  case X86::VMOVUPSZrmk: case X86::VMOVAPSZrmk:
1181  case X86::VBROADCASTSDZ256mk:
1182  case X86::VBROADCASTSDZmk:
1183  case X86::VBROADCASTSSZ128mk:
1184  case X86::VBROADCASTSSZ256mk:
1185  case X86::VBROADCASTSSZmk:
1186  case X86::VPBROADCASTDZ128mk:
1187  case X86::VPBROADCASTDZ256mk:
1188  case X86::VPBROADCASTDZmk:
1189  case X86::VPBROADCASTQZ128mk:
1190  case X86::VPBROADCASTQZ256mk:
1191  case X86::VPBROADCASTQZmk: {
1192  unsigned Opc;
1193  switch (MIOpc) {
1194  default: llvm_unreachable("Unreachable!");
1195  case X86::VMOVDQU8Z128rmk: Opc = X86::VPBLENDMBZ128rmk; break;
1196  case X86::VMOVDQU8Z256rmk: Opc = X86::VPBLENDMBZ256rmk; break;
1197  case X86::VMOVDQU8Zrmk: Opc = X86::VPBLENDMBZrmk; break;
1198  case X86::VMOVDQU16Z128rmk: Opc = X86::VPBLENDMWZ128rmk; break;
1199  case X86::VMOVDQU16Z256rmk: Opc = X86::VPBLENDMWZ256rmk; break;
1200  case X86::VMOVDQU16Zrmk: Opc = X86::VPBLENDMWZrmk; break;
1201  case X86::VMOVDQU32Z128rmk: Opc = X86::VPBLENDMDZ128rmk; break;
1202  case X86::VMOVDQU32Z256rmk: Opc = X86::VPBLENDMDZ256rmk; break;
1203  case X86::VMOVDQU32Zrmk: Opc = X86::VPBLENDMDZrmk; break;
1204  case X86::VMOVDQU64Z128rmk: Opc = X86::VPBLENDMQZ128rmk; break;
1205  case X86::VMOVDQU64Z256rmk: Opc = X86::VPBLENDMQZ256rmk; break;
1206  case X86::VMOVDQU64Zrmk: Opc = X86::VPBLENDMQZrmk; break;
1207  case X86::VMOVUPDZ128rmk: Opc = X86::VBLENDMPDZ128rmk; break;
1208  case X86::VMOVUPDZ256rmk: Opc = X86::VBLENDMPDZ256rmk; break;
1209  case X86::VMOVUPDZrmk: Opc = X86::VBLENDMPDZrmk; break;
1210  case X86::VMOVUPSZ128rmk: Opc = X86::VBLENDMPSZ128rmk; break;
1211  case X86::VMOVUPSZ256rmk: Opc = X86::VBLENDMPSZ256rmk; break;
1212  case X86::VMOVUPSZrmk: Opc = X86::VBLENDMPSZrmk; break;
1213  case X86::VMOVDQA32Z128rmk: Opc = X86::VPBLENDMDZ128rmk; break;
1214  case X86::VMOVDQA32Z256rmk: Opc = X86::VPBLENDMDZ256rmk; break;
1215  case X86::VMOVDQA32Zrmk: Opc = X86::VPBLENDMDZrmk; break;
1216  case X86::VMOVDQA64Z128rmk: Opc = X86::VPBLENDMQZ128rmk; break;
1217  case X86::VMOVDQA64Z256rmk: Opc = X86::VPBLENDMQZ256rmk; break;
1218  case X86::VMOVDQA64Zrmk: Opc = X86::VPBLENDMQZrmk; break;
1219  case X86::VMOVAPDZ128rmk: Opc = X86::VBLENDMPDZ128rmk; break;
1220  case X86::VMOVAPDZ256rmk: Opc = X86::VBLENDMPDZ256rmk; break;
1221  case X86::VMOVAPDZrmk: Opc = X86::VBLENDMPDZrmk; break;
1222  case X86::VMOVAPSZ128rmk: Opc = X86::VBLENDMPSZ128rmk; break;
1223  case X86::VMOVAPSZ256rmk: Opc = X86::VBLENDMPSZ256rmk; break;
1224  case X86::VMOVAPSZrmk: Opc = X86::VBLENDMPSZrmk; break;
1225  case X86::VBROADCASTSDZ256mk: Opc = X86::VBLENDMPDZ256rmbk; break;
1226  case X86::VBROADCASTSDZmk: Opc = X86::VBLENDMPDZrmbk; break;
1227  case X86::VBROADCASTSSZ128mk: Opc = X86::VBLENDMPSZ128rmbk; break;
1228  case X86::VBROADCASTSSZ256mk: Opc = X86::VBLENDMPSZ256rmbk; break;
1229  case X86::VBROADCASTSSZmk: Opc = X86::VBLENDMPSZrmbk; break;
1230  case X86::VPBROADCASTDZ128mk: Opc = X86::VPBLENDMDZ128rmbk; break;
1231  case X86::VPBROADCASTDZ256mk: Opc = X86::VPBLENDMDZ256rmbk; break;
1232  case X86::VPBROADCASTDZmk: Opc = X86::VPBLENDMDZrmbk; break;
1233  case X86::VPBROADCASTQZ128mk: Opc = X86::VPBLENDMQZ128rmbk; break;
1234  case X86::VPBROADCASTQZ256mk: Opc = X86::VPBLENDMQZ256rmbk; break;
1235  case X86::VPBROADCASTQZmk: Opc = X86::VPBLENDMQZrmbk; break;
1236  }
1237 
1238  NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1239  .add(Dest)
1240  .add(MI.getOperand(2))
1241  .add(Src)
1242  .add(MI.getOperand(3))
1243  .add(MI.getOperand(4))
1244  .add(MI.getOperand(5))
1245  .add(MI.getOperand(6))
1246  .add(MI.getOperand(7));
1247  break;
1248  }
1249 
1250  case X86::VMOVDQU8Z128rrk:
1251  case X86::VMOVDQU8Z256rrk:
1252  case X86::VMOVDQU8Zrrk:
1253  case X86::VMOVDQU16Z128rrk:
1254  case X86::VMOVDQU16Z256rrk:
1255  case X86::VMOVDQU16Zrrk:
1256  case X86::VMOVDQU32Z128rrk: case X86::VMOVDQA32Z128rrk:
1257  case X86::VMOVDQU32Z256rrk: case X86::VMOVDQA32Z256rrk:
1258  case X86::VMOVDQU32Zrrk: case X86::VMOVDQA32Zrrk:
1259  case X86::VMOVDQU64Z128rrk: case X86::VMOVDQA64Z128rrk:
1260  case X86::VMOVDQU64Z256rrk: case X86::VMOVDQA64Z256rrk:
1261  case X86::VMOVDQU64Zrrk: case X86::VMOVDQA64Zrrk:
1262  case X86::VMOVUPDZ128rrk: case X86::VMOVAPDZ128rrk:
1263  case X86::VMOVUPDZ256rrk: case X86::VMOVAPDZ256rrk:
1264  case X86::VMOVUPDZrrk: case X86::VMOVAPDZrrk:
1265  case X86::VMOVUPSZ128rrk: case X86::VMOVAPSZ128rrk:
1266  case X86::VMOVUPSZ256rrk: case X86::VMOVAPSZ256rrk:
1267  case X86::VMOVUPSZrrk: case X86::VMOVAPSZrrk: {
1268  unsigned Opc;
1269  switch (MIOpc) {
1270  default: llvm_unreachable("Unreachable!");
1271  case X86::VMOVDQU8Z128rrk: Opc = X86::VPBLENDMBZ128rrk; break;
1272  case X86::VMOVDQU8Z256rrk: Opc = X86::VPBLENDMBZ256rrk; break;
1273  case X86::VMOVDQU8Zrrk: Opc = X86::VPBLENDMBZrrk; break;
1274  case X86::VMOVDQU16Z128rrk: Opc = X86::VPBLENDMWZ128rrk; break;
1275  case X86::VMOVDQU16Z256rrk: Opc = X86::VPBLENDMWZ256rrk; break;
1276  case X86::VMOVDQU16Zrrk: Opc = X86::VPBLENDMWZrrk; break;
1277  case X86::VMOVDQU32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1278  case X86::VMOVDQU32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1279  case X86::VMOVDQU32Zrrk: Opc = X86::VPBLENDMDZrrk; break;
1280  case X86::VMOVDQU64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1281  case X86::VMOVDQU64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1282  case X86::VMOVDQU64Zrrk: Opc = X86::VPBLENDMQZrrk; break;
1283  case X86::VMOVUPDZ128rrk: Opc = X86::VBLENDMPDZ128rrk; break;
1284  case X86::VMOVUPDZ256rrk: Opc = X86::VBLENDMPDZ256rrk; break;
1285  case X86::VMOVUPDZrrk: Opc = X86::VBLENDMPDZrrk; break;
1286  case X86::VMOVUPSZ128rrk: Opc = X86::VBLENDMPSZ128rrk; break;
1287  case X86::VMOVUPSZ256rrk: Opc = X86::VBLENDMPSZ256rrk; break;
1288  case X86::VMOVUPSZrrk: Opc = X86::VBLENDMPSZrrk; break;
1289  case X86::VMOVDQA32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1290  case X86::VMOVDQA32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1291  case X86::VMOVDQA32Zrrk: Opc = X86::VPBLENDMDZrrk; break;
1292  case X86::VMOVDQA64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1293  case X86::VMOVDQA64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1294  case X86::VMOVDQA64Zrrk: Opc = X86::VPBLENDMQZrrk; break;
1295  case X86::VMOVAPDZ128rrk: Opc = X86::VBLENDMPDZ128rrk; break;
1296  case X86::VMOVAPDZ256rrk: Opc = X86::VBLENDMPDZ256rrk; break;
1297  case X86::VMOVAPDZrrk: Opc = X86::VBLENDMPDZrrk; break;
1298  case X86::VMOVAPSZ128rrk: Opc = X86::VBLENDMPSZ128rrk; break;
1299  case X86::VMOVAPSZ256rrk: Opc = X86::VBLENDMPSZ256rrk; break;
1300  case X86::VMOVAPSZrrk: Opc = X86::VBLENDMPSZrrk; break;
1301  }
1302 
1303  NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1304  .add(Dest)
1305  .add(MI.getOperand(2))
1306  .add(Src)
1307  .add(MI.getOperand(3));
1308  break;
1309  }
1310  }
1311 
1312  if (!NewMI) return nullptr;
1313 
1314  if (LV) { // Update live variables
1315  if (Src.isKill())
1316  LV->replaceKillInstruction(Src.getReg(), MI, *NewMI);
1317  if (Dest.isDead())
1318  LV->replaceKillInstruction(Dest.getReg(), MI, *NewMI);
1319  }
1320 
1321  MFI->insert(MI.getIterator(), NewMI); // Insert the new inst
1322  return NewMI;
1323 }
1324 
1325 /// This determines which of three possible cases of a three source commute
1326 /// the source indexes correspond to taking into account any mask operands.
1327 /// All prevents commuting a passthru operand. Returns -1 if the commute isn't
1328 /// possible.
1329 /// Case 0 - Possible to commute the first and second operands.
1330 /// Case 1 - Possible to commute the first and third operands.
1331 /// Case 2 - Possible to commute the second and third operands.
1332 static unsigned getThreeSrcCommuteCase(uint64_t TSFlags, unsigned SrcOpIdx1,
1333  unsigned SrcOpIdx2) {
1334  // Put the lowest index to SrcOpIdx1 to simplify the checks below.
1335  if (SrcOpIdx1 > SrcOpIdx2)
1336  std::swap(SrcOpIdx1, SrcOpIdx2);
1337 
1338  unsigned Op1 = 1, Op2 = 2, Op3 = 3;
1339  if (X86II::isKMasked(TSFlags)) {
1340  Op2++;
1341  Op3++;
1342  }
1343 
1344  if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op2)
1345  return 0;
1346  if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op3)
1347  return 1;
1348  if (SrcOpIdx1 == Op2 && SrcOpIdx2 == Op3)
1349  return 2;
1350  llvm_unreachable("Unknown three src commute case.");
1351 }
1352 
1354  const MachineInstr &MI, unsigned SrcOpIdx1, unsigned SrcOpIdx2,
1355  const X86InstrFMA3Group &FMA3Group) const {
1356 
1357  unsigned Opc = MI.getOpcode();
1358 
1359  // TODO: Commuting the 1st operand of FMA*_Int requires some additional
1360  // analysis. The commute optimization is legal only if all users of FMA*_Int
1361  // use only the lowest element of the FMA*_Int instruction. Such analysis are
1362  // not implemented yet. So, just return 0 in that case.
1363  // When such analysis are available this place will be the right place for
1364  // calling it.
1365  assert(!(FMA3Group.isIntrinsic() && (SrcOpIdx1 == 1 || SrcOpIdx2 == 1)) &&
1366  "Intrinsic instructions can't commute operand 1");
1367 
1368  // Determine which case this commute is or if it can't be done.
1369  unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1370  SrcOpIdx2);
1371  assert(Case < 3 && "Unexpected case number!");
1372 
1373  // Define the FMA forms mapping array that helps to map input FMA form
1374  // to output FMA form to preserve the operation semantics after
1375  // commuting the operands.
1376  const unsigned Form132Index = 0;
1377  const unsigned Form213Index = 1;
1378  const unsigned Form231Index = 2;
1379  static const unsigned FormMapping[][3] = {
1380  // 0: SrcOpIdx1 == 1 && SrcOpIdx2 == 2;
1381  // FMA132 A, C, b; ==> FMA231 C, A, b;
1382  // FMA213 B, A, c; ==> FMA213 A, B, c;
1383  // FMA231 C, A, b; ==> FMA132 A, C, b;
1384  { Form231Index, Form213Index, Form132Index },
1385  // 1: SrcOpIdx1 == 1 && SrcOpIdx2 == 3;
1386  // FMA132 A, c, B; ==> FMA132 B, c, A;
1387  // FMA213 B, a, C; ==> FMA231 C, a, B;
1388  // FMA231 C, a, B; ==> FMA213 B, a, C;
1389  { Form132Index, Form231Index, Form213Index },
1390  // 2: SrcOpIdx1 == 2 && SrcOpIdx2 == 3;
1391  // FMA132 a, C, B; ==> FMA213 a, B, C;
1392  // FMA213 b, A, C; ==> FMA132 b, C, A;
1393  // FMA231 c, A, B; ==> FMA231 c, B, A;
1394  { Form213Index, Form132Index, Form231Index }
1395  };
1396 
1397  unsigned FMAForms[3];
1398  FMAForms[0] = FMA3Group.get132Opcode();
1399  FMAForms[1] = FMA3Group.get213Opcode();
1400  FMAForms[2] = FMA3Group.get231Opcode();
1401  unsigned FormIndex;
1402  for (FormIndex = 0; FormIndex < 3; FormIndex++)
1403  if (Opc == FMAForms[FormIndex])
1404  break;
1405 
1406  // Everything is ready, just adjust the FMA opcode and return it.
1407  FormIndex = FormMapping[Case][FormIndex];
1408  return FMAForms[FormIndex];
1409 }
1410 
1411 static void commuteVPTERNLOG(MachineInstr &MI, unsigned SrcOpIdx1,
1412  unsigned SrcOpIdx2) {
1413  // Determine which case this commute is or if it can't be done.
1414  unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1415  SrcOpIdx2);
1416  assert(Case < 3 && "Unexpected case value!");
1417 
1418  // For each case we need to swap two pairs of bits in the final immediate.
1419  static const uint8_t SwapMasks[3][4] = {
1420  { 0x04, 0x10, 0x08, 0x20 }, // Swap bits 2/4 and 3/5.
1421  { 0x02, 0x10, 0x08, 0x40 }, // Swap bits 1/4 and 3/6.
1422  { 0x02, 0x04, 0x20, 0x40 }, // Swap bits 1/2 and 5/6.
1423  };
1424 
1425  uint8_t Imm = MI.getOperand(MI.getNumOperands()-1).getImm();
1426  // Clear out the bits we are swapping.
1427  uint8_t NewImm = Imm & ~(SwapMasks[Case][0] | SwapMasks[Case][1] |
1428  SwapMasks[Case][2] | SwapMasks[Case][3]);
1429  // If the immediate had a bit of the pair set, then set the opposite bit.
1430  if (Imm & SwapMasks[Case][0]) NewImm |= SwapMasks[Case][1];
1431  if (Imm & SwapMasks[Case][1]) NewImm |= SwapMasks[Case][0];
1432  if (Imm & SwapMasks[Case][2]) NewImm |= SwapMasks[Case][3];
1433  if (Imm & SwapMasks[Case][3]) NewImm |= SwapMasks[Case][2];
1434  MI.getOperand(MI.getNumOperands()-1).setImm(NewImm);
1435 }
1436 
1437 // Returns true if this is a VPERMI2 or VPERMT2 instruction that can be
1438 // commuted.
1439 static bool isCommutableVPERMV3Instruction(unsigned Opcode) {
1440 #define VPERM_CASES(Suffix) \
1441  case X86::VPERMI2##Suffix##128rr: case X86::VPERMT2##Suffix##128rr: \
1442  case X86::VPERMI2##Suffix##256rr: case X86::VPERMT2##Suffix##256rr: \
1443  case X86::VPERMI2##Suffix##rr: case X86::VPERMT2##Suffix##rr: \
1444  case X86::VPERMI2##Suffix##128rm: case X86::VPERMT2##Suffix##128rm: \
1445  case X86::VPERMI2##Suffix##256rm: case X86::VPERMT2##Suffix##256rm: \
1446  case X86::VPERMI2##Suffix##rm: case X86::VPERMT2##Suffix##rm: \
1447  case X86::VPERMI2##Suffix##128rrkz: case X86::VPERMT2##Suffix##128rrkz: \
1448  case X86::VPERMI2##Suffix##256rrkz: case X86::VPERMT2##Suffix##256rrkz: \
1449  case X86::VPERMI2##Suffix##rrkz: case X86::VPERMT2##Suffix##rrkz: \
1450  case X86::VPERMI2##Suffix##128rmkz: case X86::VPERMT2##Suffix##128rmkz: \
1451  case X86::VPERMI2##Suffix##256rmkz: case X86::VPERMT2##Suffix##256rmkz: \
1452  case X86::VPERMI2##Suffix##rmkz: case X86::VPERMT2##Suffix##rmkz:
1453 
1454 #define VPERM_CASES_BROADCAST(Suffix) \
1455  VPERM_CASES(Suffix) \
1456  case X86::VPERMI2##Suffix##128rmb: case X86::VPERMT2##Suffix##128rmb: \
1457  case X86::VPERMI2##Suffix##256rmb: case X86::VPERMT2##Suffix##256rmb: \
1458  case X86::VPERMI2##Suffix##rmb: case X86::VPERMT2##Suffix##rmb: \
1459  case X86::VPERMI2##Suffix##128rmbkz: case X86::VPERMT2##Suffix##128rmbkz: \
1460  case X86::VPERMI2##Suffix##256rmbkz: case X86::VPERMT2##Suffix##256rmbkz: \
1461  case X86::VPERMI2##Suffix##rmbkz: case X86::VPERMT2##Suffix##rmbkz:
1462 
1463  switch (Opcode) {
1464  default: return false;
1465  VPERM_CASES(B)
1470  VPERM_CASES(W)
1471  return true;
1472  }
1473 #undef VPERM_CASES_BROADCAST
1474 #undef VPERM_CASES
1475 }
1476 
1477 // Returns commuted opcode for VPERMI2 and VPERMT2 instructions by switching
1478 // from the I opcode to the T opcode and vice versa.
1479 static unsigned getCommutedVPERMV3Opcode(unsigned Opcode) {
1480 #define VPERM_CASES(Orig, New) \
1481  case X86::Orig##128rr: return X86::New##128rr; \
1482  case X86::Orig##128rrkz: return X86::New##128rrkz; \
1483  case X86::Orig##128rm: return X86::New##128rm; \
1484  case X86::Orig##128rmkz: return X86::New##128rmkz; \
1485  case X86::Orig##256rr: return X86::New##256rr; \
1486  case X86::Orig##256rrkz: return X86::New##256rrkz; \
1487  case X86::Orig##256rm: return X86::New##256rm; \
1488  case X86::Orig##256rmkz: return X86::New##256rmkz; \
1489  case X86::Orig##rr: return X86::New##rr; \
1490  case X86::Orig##rrkz: return X86::New##rrkz; \
1491  case X86::Orig##rm: return X86::New##rm; \
1492  case X86::Orig##rmkz: return X86::New##rmkz;
1493 
1494 #define VPERM_CASES_BROADCAST(Orig, New) \
1495  VPERM_CASES(Orig, New) \
1496  case X86::Orig##128rmb: return X86::New##128rmb; \
1497  case X86::Orig##128rmbkz: return X86::New##128rmbkz; \
1498  case X86::Orig##256rmb: return X86::New##256rmb; \
1499  case X86::Orig##256rmbkz: return X86::New##256rmbkz; \
1500  case X86::Orig##rmb: return X86::New##rmb; \
1501  case X86::Orig##rmbkz: return X86::New##rmbkz;
1502 
1503  switch (Opcode) {
1504  VPERM_CASES(VPERMI2B, VPERMT2B)
1505  VPERM_CASES_BROADCAST(VPERMI2D, VPERMT2D)
1506  VPERM_CASES_BROADCAST(VPERMI2PD, VPERMT2PD)
1507  VPERM_CASES_BROADCAST(VPERMI2PS, VPERMT2PS)
1508  VPERM_CASES_BROADCAST(VPERMI2Q, VPERMT2Q)
1509  VPERM_CASES(VPERMI2W, VPERMT2W)
1510  VPERM_CASES(VPERMT2B, VPERMI2B)
1511  VPERM_CASES_BROADCAST(VPERMT2D, VPERMI2D)
1512  VPERM_CASES_BROADCAST(VPERMT2PD, VPERMI2PD)
1513  VPERM_CASES_BROADCAST(VPERMT2PS, VPERMI2PS)
1514  VPERM_CASES_BROADCAST(VPERMT2Q, VPERMI2Q)
1515  VPERM_CASES(VPERMT2W, VPERMI2W)
1516  }
1517 
1518  llvm_unreachable("Unreachable!");
1519 #undef VPERM_CASES_BROADCAST
1520 #undef VPERM_CASES
1521 }
1522 
1524  unsigned OpIdx1,
1525  unsigned OpIdx2) const {
1526  auto cloneIfNew = [NewMI](MachineInstr &MI) -> MachineInstr & {
1527  if (NewMI)
1528  return *MI.getParent()->getParent()->CloneMachineInstr(&MI);
1529  return MI;
1530  };
1531 
1532  switch (MI.getOpcode()) {
1533  case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
1534  case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
1535  case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
1536  case X86::SHLD32rri8: // A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
1537  case X86::SHRD64rri8: // A = SHRD64rri8 B, C, I -> A = SHLD64rri8 C, B, (64-I)
1538  case X86::SHLD64rri8:{// A = SHLD64rri8 B, C, I -> A = SHRD64rri8 C, B, (64-I)
1539  unsigned Opc;
1540  unsigned Size;
1541  switch (MI.getOpcode()) {
1542  default: llvm_unreachable("Unreachable!");
1543  case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
1544  case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
1545  case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
1546  case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
1547  case X86::SHRD64rri8: Size = 64; Opc = X86::SHLD64rri8; break;
1548  case X86::SHLD64rri8: Size = 64; Opc = X86::SHRD64rri8; break;
1549  }
1550  unsigned Amt = MI.getOperand(3).getImm();
1551  auto &WorkingMI = cloneIfNew(MI);
1552  WorkingMI.setDesc(get(Opc));
1553  WorkingMI.getOperand(3).setImm(Size - Amt);
1554  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1555  OpIdx1, OpIdx2);
1556  }
1557  case X86::PFSUBrr:
1558  case X86::PFSUBRrr: {
1559  // PFSUB x, y: x = x - y
1560  // PFSUBR x, y: x = y - x
1561  unsigned Opc =
1562  (X86::PFSUBRrr == MI.getOpcode() ? X86::PFSUBrr : X86::PFSUBRrr);
1563  auto &WorkingMI = cloneIfNew(MI);
1564  WorkingMI.setDesc(get(Opc));
1565  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1566  OpIdx1, OpIdx2);
1567  }
1568  case X86::BLENDPDrri:
1569  case X86::BLENDPSrri:
1570  case X86::VBLENDPDrri:
1571  case X86::VBLENDPSrri:
1572  // If we're optimizing for size, try to use MOVSD/MOVSS.
1573  if (MI.getParent()->getParent()->getFunction().hasOptSize()) {
1574  unsigned Mask, Opc;
1575  switch (MI.getOpcode()) {
1576  default: llvm_unreachable("Unreachable!");
1577  case X86::BLENDPDrri: Opc = X86::MOVSDrr; Mask = 0x03; break;
1578  case X86::BLENDPSrri: Opc = X86::MOVSSrr; Mask = 0x0F; break;
1579  case X86::VBLENDPDrri: Opc = X86::VMOVSDrr; Mask = 0x03; break;
1580  case X86::VBLENDPSrri: Opc = X86::VMOVSSrr; Mask = 0x0F; break;
1581  }
1582  if ((MI.getOperand(3).getImm() ^ Mask) == 1) {
1583  auto &WorkingMI = cloneIfNew(MI);
1584  WorkingMI.setDesc(get(Opc));
1585  WorkingMI.RemoveOperand(3);
1586  return TargetInstrInfo::commuteInstructionImpl(WorkingMI,
1587  /*NewMI=*/false,
1588  OpIdx1, OpIdx2);
1589  }
1590  }
1592  case X86::PBLENDWrri:
1593  case X86::VBLENDPDYrri:
1594  case X86::VBLENDPSYrri:
1595  case X86::VPBLENDDrri:
1596  case X86::VPBLENDWrri:
1597  case X86::VPBLENDDYrri:
1598  case X86::VPBLENDWYrri:{
1599  int8_t Mask;
1600  switch (MI.getOpcode()) {
1601  default: llvm_unreachable("Unreachable!");
1602  case X86::BLENDPDrri: Mask = (int8_t)0x03; break;
1603  case X86::BLENDPSrri: Mask = (int8_t)0x0F; break;
1604  case X86::PBLENDWrri: Mask = (int8_t)0xFF; break;
1605  case X86::VBLENDPDrri: Mask = (int8_t)0x03; break;
1606  case X86::VBLENDPSrri: Mask = (int8_t)0x0F; break;
1607  case X86::VBLENDPDYrri: Mask = (int8_t)0x0F; break;
1608  case X86::VBLENDPSYrri: Mask = (int8_t)0xFF; break;
1609  case X86::VPBLENDDrri: Mask = (int8_t)0x0F; break;
1610  case X86::VPBLENDWrri: Mask = (int8_t)0xFF; break;
1611  case X86::VPBLENDDYrri: Mask = (int8_t)0xFF; break;
1612  case X86::VPBLENDWYrri: Mask = (int8_t)0xFF; break;
1613  }
1614  // Only the least significant bits of Imm are used.
1615  // Using int8_t to ensure it will be sign extended to the int64_t that
1616  // setImm takes in order to match isel behavior.
1617  int8_t Imm = MI.getOperand(3).getImm() & Mask;
1618  auto &WorkingMI = cloneIfNew(MI);
1619  WorkingMI.getOperand(3).setImm(Mask ^ Imm);
1620  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1621  OpIdx1, OpIdx2);
1622  }
1623  case X86::INSERTPSrr:
1624  case X86::VINSERTPSrr:
1625  case X86::VINSERTPSZrr: {
1626  unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm();
1627  unsigned ZMask = Imm & 15;
1628  unsigned DstIdx = (Imm >> 4) & 3;
1629  unsigned SrcIdx = (Imm >> 6) & 3;
1630 
1631  // We can commute insertps if we zero 2 of the elements, the insertion is
1632  // "inline" and we don't override the insertion with a zero.
1633  if (DstIdx == SrcIdx && (ZMask & (1 << DstIdx)) == 0 &&
1634  countPopulation(ZMask) == 2) {
1635  unsigned AltIdx = findFirstSet((ZMask | (1 << DstIdx)) ^ 15);
1636  assert(AltIdx < 4 && "Illegal insertion index");
1637  unsigned AltImm = (AltIdx << 6) | (AltIdx << 4) | ZMask;
1638  auto &WorkingMI = cloneIfNew(MI);
1639  WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(AltImm);
1640  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1641  OpIdx1, OpIdx2);
1642  }
1643  return nullptr;
1644  }
1645  case X86::MOVSDrr:
1646  case X86::MOVSSrr:
1647  case X86::VMOVSDrr:
1648  case X86::VMOVSSrr:{
1649  // On SSE41 or later we can commute a MOVSS/MOVSD to a BLENDPS/BLENDPD.
1650  if (Subtarget.hasSSE41()) {
1651  unsigned Mask, Opc;
1652  switch (MI.getOpcode()) {
1653  default: llvm_unreachable("Unreachable!");
1654  case X86::MOVSDrr: Opc = X86::BLENDPDrri; Mask = 0x02; break;
1655  case X86::MOVSSrr: Opc = X86::BLENDPSrri; Mask = 0x0E; break;
1656  case X86::VMOVSDrr: Opc = X86::VBLENDPDrri; Mask = 0x02; break;
1657  case X86::VMOVSSrr: Opc = X86::VBLENDPSrri; Mask = 0x0E; break;
1658  }
1659 
1660  auto &WorkingMI = cloneIfNew(MI);
1661  WorkingMI.setDesc(get(Opc));
1662  WorkingMI.addOperand(MachineOperand::CreateImm(Mask));
1663  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1664  OpIdx1, OpIdx2);
1665  }
1666 
1667  // Convert to SHUFPD.
1668  assert(MI.getOpcode() == X86::MOVSDrr &&
1669  "Can only commute MOVSDrr without SSE4.1");
1670 
1671  auto &WorkingMI = cloneIfNew(MI);
1672  WorkingMI.setDesc(get(X86::SHUFPDrri));
1673  WorkingMI.addOperand(MachineOperand::CreateImm(0x02));
1674  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1675  OpIdx1, OpIdx2);
1676  }
1677  case X86::SHUFPDrri: {
1678  // Commute to MOVSD.
1679  assert(MI.getOperand(3).getImm() == 0x02 && "Unexpected immediate!");
1680  auto &WorkingMI = cloneIfNew(MI);
1681  WorkingMI.setDesc(get(X86::MOVSDrr));
1682  WorkingMI.RemoveOperand(3);
1683  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1684  OpIdx1, OpIdx2);
1685  }
1686  case X86::PCLMULQDQrr:
1687  case X86::VPCLMULQDQrr:
1688  case X86::VPCLMULQDQYrr:
1689  case X86::VPCLMULQDQZrr:
1690  case X86::VPCLMULQDQZ128rr:
1691  case X86::VPCLMULQDQZ256rr: {
1692  // SRC1 64bits = Imm[0] ? SRC1[127:64] : SRC1[63:0]
1693  // SRC2 64bits = Imm[4] ? SRC2[127:64] : SRC2[63:0]
1694  unsigned Imm = MI.getOperand(3).getImm();
1695  unsigned Src1Hi = Imm & 0x01;
1696  unsigned Src2Hi = Imm & 0x10;
1697  auto &WorkingMI = cloneIfNew(MI);
1698  WorkingMI.getOperand(3).setImm((Src1Hi << 4) | (Src2Hi >> 4));
1699  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1700  OpIdx1, OpIdx2);
1701  }
1702  case X86::VPCMPBZ128rri: case X86::VPCMPUBZ128rri:
1703  case X86::VPCMPBZ256rri: case X86::VPCMPUBZ256rri:
1704  case X86::VPCMPBZrri: case X86::VPCMPUBZrri:
1705  case X86::VPCMPDZ128rri: case X86::VPCMPUDZ128rri:
1706  case X86::VPCMPDZ256rri: case X86::VPCMPUDZ256rri:
1707  case X86::VPCMPDZrri: case X86::VPCMPUDZrri:
1708  case X86::VPCMPQZ128rri: case X86::VPCMPUQZ128rri:
1709  case X86::VPCMPQZ256rri: case X86::VPCMPUQZ256rri:
1710  case X86::VPCMPQZrri: case X86::VPCMPUQZrri:
1711  case X86::VPCMPWZ128rri: case X86::VPCMPUWZ128rri:
1712  case X86::VPCMPWZ256rri: case X86::VPCMPUWZ256rri:
1713  case X86::VPCMPWZrri: case X86::VPCMPUWZrri:
1714  case X86::VPCMPBZ128rrik: case X86::VPCMPUBZ128rrik:
1715  case X86::VPCMPBZ256rrik: case X86::VPCMPUBZ256rrik:
1716  case X86::VPCMPBZrrik: case X86::VPCMPUBZrrik:
1717  case X86::VPCMPDZ128rrik: case X86::VPCMPUDZ128rrik:
1718  case X86::VPCMPDZ256rrik: case X86::VPCMPUDZ256rrik:
1719  case X86::VPCMPDZrrik: case X86::VPCMPUDZrrik:
1720  case X86::VPCMPQZ128rrik: case X86::VPCMPUQZ128rrik:
1721  case X86::VPCMPQZ256rrik: case X86::VPCMPUQZ256rrik:
1722  case X86::VPCMPQZrrik: case X86::VPCMPUQZrrik:
1723  case X86::VPCMPWZ128rrik: case X86::VPCMPUWZ128rrik:
1724  case X86::VPCMPWZ256rrik: case X86::VPCMPUWZ256rrik:
1725  case X86::VPCMPWZrrik: case X86::VPCMPUWZrrik: {
1726  // Flip comparison mode immediate (if necessary).
1727  unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm() & 0x7;
1728  Imm = X86::getSwappedVPCMPImm(Imm);
1729  auto &WorkingMI = cloneIfNew(MI);
1730  WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(Imm);
1731  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1732  OpIdx1, OpIdx2);
1733  }
1734  case X86::VPCOMBri: case X86::VPCOMUBri:
1735  case X86::VPCOMDri: case X86::VPCOMUDri:
1736  case X86::VPCOMQri: case X86::VPCOMUQri:
1737  case X86::VPCOMWri: case X86::VPCOMUWri: {
1738  // Flip comparison mode immediate (if necessary).
1739  unsigned Imm = MI.getOperand(3).getImm() & 0x7;
1740  Imm = X86::getSwappedVPCOMImm(Imm);
1741  auto &WorkingMI = cloneIfNew(MI);
1742  WorkingMI.getOperand(3).setImm(Imm);
1743  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1744  OpIdx1, OpIdx2);
1745  }
1746  case X86::VCMPSDZrr:
1747  case X86::VCMPSSZrr:
1748  case X86::VCMPPDZrri:
1749  case X86::VCMPPSZrri:
1750  case X86::VCMPPDZ128rri:
1751  case X86::VCMPPSZ128rri:
1752  case X86::VCMPPDZ256rri:
1753  case X86::VCMPPSZ256rri:
1754  case X86::VCMPPDZrrik:
1755  case X86::VCMPPSZrrik:
1756  case X86::VCMPPDZ128rrik:
1757  case X86::VCMPPSZ128rrik:
1758  case X86::VCMPPDZ256rrik:
1759  case X86::VCMPPSZ256rrik: {
1760  unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm() & 0x1f;
1761  Imm = X86::getSwappedVCMPImm(Imm);
1762  auto &WorkingMI = cloneIfNew(MI);
1763  WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(Imm);
1764  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1765  OpIdx1, OpIdx2);
1766  }
1767  case X86::VPERM2F128rr:
1768  case X86::VPERM2I128rr: {
1769  // Flip permute source immediate.
1770  // Imm & 0x02: lo = if set, select Op1.lo/hi else Op0.lo/hi.
1771  // Imm & 0x20: hi = if set, select Op1.lo/hi else Op0.lo/hi.
1772  int8_t Imm = MI.getOperand(3).getImm() & 0xFF;
1773  auto &WorkingMI = cloneIfNew(MI);
1774  WorkingMI.getOperand(3).setImm(Imm ^ 0x22);
1775  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1776  OpIdx1, OpIdx2);
1777  }
1778  case X86::MOVHLPSrr:
1779  case X86::UNPCKHPDrr:
1780  case X86::VMOVHLPSrr:
1781  case X86::VUNPCKHPDrr:
1782  case X86::VMOVHLPSZrr:
1783  case X86::VUNPCKHPDZ128rr: {
1784  assert(Subtarget.hasSSE2() && "Commuting MOVHLP/UNPCKHPD requires SSE2!");
1785 
1786  unsigned Opc = MI.getOpcode();
1787  switch (Opc) {
1788  default: llvm_unreachable("Unreachable!");
1789  case X86::MOVHLPSrr: Opc = X86::UNPCKHPDrr; break;
1790  case X86::UNPCKHPDrr: Opc = X86::MOVHLPSrr; break;
1791  case X86::VMOVHLPSrr: Opc = X86::VUNPCKHPDrr; break;
1792  case X86::VUNPCKHPDrr: Opc = X86::VMOVHLPSrr; break;
1793  case X86::VMOVHLPSZrr: Opc = X86::VUNPCKHPDZ128rr; break;
1794  case X86::VUNPCKHPDZ128rr: Opc = X86::VMOVHLPSZrr; 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::CMOV16rr: case X86::CMOV32rr: case X86::CMOV64rr: {
1802  auto &WorkingMI = cloneIfNew(MI);
1803  unsigned OpNo = MI.getDesc().getNumOperands() - 1;
1804  X86::CondCode CC = static_cast<X86::CondCode>(MI.getOperand(OpNo).getImm());
1805  WorkingMI.getOperand(OpNo).setImm(X86::GetOppositeBranchCondition(CC));
1806  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1807  OpIdx1, OpIdx2);
1808  }
1809  case X86::VPTERNLOGDZrri: case X86::VPTERNLOGDZrmi:
1810  case X86::VPTERNLOGDZ128rri: case X86::VPTERNLOGDZ128rmi:
1811  case X86::VPTERNLOGDZ256rri: case X86::VPTERNLOGDZ256rmi:
1812  case X86::VPTERNLOGQZrri: case X86::VPTERNLOGQZrmi:
1813  case X86::VPTERNLOGQZ128rri: case X86::VPTERNLOGQZ128rmi:
1814  case X86::VPTERNLOGQZ256rri: case X86::VPTERNLOGQZ256rmi:
1815  case X86::VPTERNLOGDZrrik:
1816  case X86::VPTERNLOGDZ128rrik:
1817  case X86::VPTERNLOGDZ256rrik:
1818  case X86::VPTERNLOGQZrrik:
1819  case X86::VPTERNLOGQZ128rrik:
1820  case X86::VPTERNLOGQZ256rrik:
1821  case X86::VPTERNLOGDZrrikz: case X86::VPTERNLOGDZrmikz:
1822  case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
1823  case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
1824  case X86::VPTERNLOGQZrrikz: case X86::VPTERNLOGQZrmikz:
1825  case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
1826  case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
1827  case X86::VPTERNLOGDZ128rmbi:
1828  case X86::VPTERNLOGDZ256rmbi:
1829  case X86::VPTERNLOGDZrmbi:
1830  case X86::VPTERNLOGQZ128rmbi:
1831  case X86::VPTERNLOGQZ256rmbi:
1832  case X86::VPTERNLOGQZrmbi:
1833  case X86::VPTERNLOGDZ128rmbikz:
1834  case X86::VPTERNLOGDZ256rmbikz:
1835  case X86::VPTERNLOGDZrmbikz:
1836  case X86::VPTERNLOGQZ128rmbikz:
1837  case X86::VPTERNLOGQZ256rmbikz:
1838  case X86::VPTERNLOGQZrmbikz: {
1839  auto &WorkingMI = cloneIfNew(MI);
1840  commuteVPTERNLOG(WorkingMI, OpIdx1, OpIdx2);
1841  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1842  OpIdx1, OpIdx2);
1843  }
1844  default: {
1846  unsigned Opc = getCommutedVPERMV3Opcode(MI.getOpcode());
1847  auto &WorkingMI = cloneIfNew(MI);
1848  WorkingMI.setDesc(get(Opc));
1849  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1850  OpIdx1, OpIdx2);
1851  }
1852 
1853  const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
1854  MI.getDesc().TSFlags);
1855  if (FMA3Group) {
1856  unsigned Opc =
1857  getFMA3OpcodeToCommuteOperands(MI, OpIdx1, OpIdx2, *FMA3Group);
1858  auto &WorkingMI = cloneIfNew(MI);
1859  WorkingMI.setDesc(get(Opc));
1860  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1861  OpIdx1, OpIdx2);
1862  }
1863 
1864  return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
1865  }
1866  }
1867 }
1868 
1869 bool
1870 X86InstrInfo::findThreeSrcCommutedOpIndices(const MachineInstr &MI,
1871  unsigned &SrcOpIdx1,
1872  unsigned &SrcOpIdx2,
1873  bool IsIntrinsic) const {
1874  uint64_t TSFlags = MI.getDesc().TSFlags;
1875 
1876  unsigned FirstCommutableVecOp = 1;
1877  unsigned LastCommutableVecOp = 3;
1878  unsigned KMaskOp = -1U;
1879  if (X86II::isKMasked(TSFlags)) {
1880  // For k-zero-masked operations it is Ok to commute the first vector
1881  // operand.
1882  // For regular k-masked operations a conservative choice is done as the
1883  // elements of the first vector operand, for which the corresponding bit
1884  // in the k-mask operand is set to 0, are copied to the result of the
1885  // instruction.
1886  // TODO/FIXME: The commute still may be legal if it is known that the
1887  // k-mask operand is set to either all ones or all zeroes.
1888  // It is also Ok to commute the 1st operand if all users of MI use only
1889  // the elements enabled by the k-mask operand. For example,
1890  // v4 = VFMADD213PSZrk v1, k, v2, v3; // v1[i] = k[i] ? v2[i]*v1[i]+v3[i]
1891  // : v1[i];
1892  // VMOVAPSZmrk <mem_addr>, k, v4; // this is the ONLY user of v4 ->
1893  // // Ok, to commute v1 in FMADD213PSZrk.
1894 
1895  // The k-mask operand has index = 2 for masked and zero-masked operations.
1896  KMaskOp = 2;
1897 
1898  // The operand with index = 1 is used as a source for those elements for
1899  // which the corresponding bit in the k-mask is set to 0.
1900  if (X86II::isKMergeMasked(TSFlags))
1901  FirstCommutableVecOp = 3;
1902 
1903  LastCommutableVecOp++;
1904  } else if (IsIntrinsic) {
1905  // Commuting the first operand of an intrinsic instruction isn't possible
1906  // unless we can prove that only the lowest element of the result is used.
1907  FirstCommutableVecOp = 2;
1908  }
1909 
1910  if (isMem(MI, LastCommutableVecOp))
1911  LastCommutableVecOp--;
1912 
1913  // Only the first RegOpsNum operands are commutable.
1914  // Also, the value 'CommuteAnyOperandIndex' is valid here as it means
1915  // that the operand is not specified/fixed.
1916  if (SrcOpIdx1 != CommuteAnyOperandIndex &&
1917  (SrcOpIdx1 < FirstCommutableVecOp || SrcOpIdx1 > LastCommutableVecOp ||
1918  SrcOpIdx1 == KMaskOp))
1919  return false;
1920  if (SrcOpIdx2 != CommuteAnyOperandIndex &&
1921  (SrcOpIdx2 < FirstCommutableVecOp || SrcOpIdx2 > LastCommutableVecOp ||
1922  SrcOpIdx2 == KMaskOp))
1923  return false;
1924 
1925  // Look for two different register operands assumed to be commutable
1926  // regardless of the FMA opcode. The FMA opcode is adjusted later.
1927  if (SrcOpIdx1 == CommuteAnyOperandIndex ||
1928  SrcOpIdx2 == CommuteAnyOperandIndex) {
1929  unsigned CommutableOpIdx2 = SrcOpIdx2;
1930 
1931  // At least one of operands to be commuted is not specified and
1932  // this method is free to choose appropriate commutable operands.
1933  if (SrcOpIdx1 == SrcOpIdx2)
1934  // Both of operands are not fixed. By default set one of commutable
1935  // operands to the last register operand of the instruction.
1936  CommutableOpIdx2 = LastCommutableVecOp;
1937  else if (SrcOpIdx2 == CommuteAnyOperandIndex)
1938  // Only one of operands is not fixed.
1939  CommutableOpIdx2 = SrcOpIdx1;
1940 
1941  // CommutableOpIdx2 is well defined now. Let's choose another commutable
1942  // operand and assign its index to CommutableOpIdx1.
1943  Register Op2Reg = MI.getOperand(CommutableOpIdx2).getReg();
1944 
1945  unsigned CommutableOpIdx1;
1946  for (CommutableOpIdx1 = LastCommutableVecOp;
1947  CommutableOpIdx1 >= FirstCommutableVecOp; CommutableOpIdx1--) {
1948  // Just ignore and skip the k-mask operand.
1949  if (CommutableOpIdx1 == KMaskOp)
1950  continue;
1951 
1952  // The commuted operands must have different registers.
1953  // Otherwise, the commute transformation does not change anything and
1954  // is useless then.
1955  if (Op2Reg != MI.getOperand(CommutableOpIdx1).getReg())
1956  break;
1957  }
1958 
1959  // No appropriate commutable operands were found.
1960  if (CommutableOpIdx1 < FirstCommutableVecOp)
1961  return false;
1962 
1963  // Assign the found pair of commutable indices to SrcOpIdx1 and SrcOpidx2
1964  // to return those values.
1965  if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
1966  CommutableOpIdx1, CommutableOpIdx2))
1967  return false;
1968  }
1969 
1970  return true;
1971 }
1972 
1974  unsigned &SrcOpIdx2) const {
1975  const MCInstrDesc &Desc = MI.getDesc();
1976  if (!Desc.isCommutable())
1977  return false;
1978 
1979  switch (MI.getOpcode()) {
1980  case X86::CMPSDrr:
1981  case X86::CMPSSrr:
1982  case X86::CMPPDrri:
1983  case X86::CMPPSrri:
1984  case X86::VCMPSDrr:
1985  case X86::VCMPSSrr:
1986  case X86::VCMPPDrri:
1987  case X86::VCMPPSrri:
1988  case X86::VCMPPDYrri:
1989  case X86::VCMPPSYrri:
1990  case X86::VCMPSDZrr:
1991  case X86::VCMPSSZrr:
1992  case X86::VCMPPDZrri:
1993  case X86::VCMPPSZrri:
1994  case X86::VCMPPDZ128rri:
1995  case X86::VCMPPSZ128rri:
1996  case X86::VCMPPDZ256rri:
1997  case X86::VCMPPSZ256rri:
1998  case X86::VCMPPDZrrik:
1999  case X86::VCMPPSZrrik:
2000  case X86::VCMPPDZ128rrik:
2001  case X86::VCMPPSZ128rrik:
2002  case X86::VCMPPDZ256rrik:
2003  case X86::VCMPPSZ256rrik: {
2004  unsigned OpOffset = X86II::isKMasked(Desc.TSFlags) ? 1 : 0;
2005 
2006  // Float comparison can be safely commuted for
2007  // Ordered/Unordered/Equal/NotEqual tests
2008  unsigned Imm = MI.getOperand(3 + OpOffset).getImm() & 0x7;
2009  switch (Imm) {
2010  default:
2011  // EVEX versions can be commuted.
2012  if ((Desc.TSFlags & X86II::EncodingMask) == X86II::EVEX)
2013  break;
2014  return false;
2015  case 0x00: // EQUAL
2016  case 0x03: // UNORDERED
2017  case 0x04: // NOT EQUAL
2018  case 0x07: // ORDERED
2019  break;
2020  }
2021 
2022  // The indices of the commutable operands are 1 and 2 (or 2 and 3
2023  // when masked).
2024  // Assign them to the returned operand indices here.
2025  return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 1 + OpOffset,
2026  2 + OpOffset);
2027  }
2028  case X86::MOVSSrr:
2029  // X86::MOVSDrr is always commutable. MOVSS is only commutable if we can
2030  // form sse4.1 blend. We assume VMOVSSrr/VMOVSDrr is always commutable since
2031  // AVX implies sse4.1.
2032  if (Subtarget.hasSSE41())
2033  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2034  return false;
2035  case X86::SHUFPDrri:
2036  // We can commute this to MOVSD.
2037  if (MI.getOperand(3).getImm() == 0x02)
2038  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2039  return false;
2040  case X86::MOVHLPSrr:
2041  case X86::UNPCKHPDrr:
2042  case X86::VMOVHLPSrr:
2043  case X86::VUNPCKHPDrr:
2044  case X86::VMOVHLPSZrr:
2045  case X86::VUNPCKHPDZ128rr:
2046  if (Subtarget.hasSSE2())
2047  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2048  return false;
2049  case X86::VPTERNLOGDZrri: case X86::VPTERNLOGDZrmi:
2050  case X86::VPTERNLOGDZ128rri: case X86::VPTERNLOGDZ128rmi:
2051  case X86::VPTERNLOGDZ256rri: case X86::VPTERNLOGDZ256rmi:
2052  case X86::VPTERNLOGQZrri: case X86::VPTERNLOGQZrmi:
2053  case X86::VPTERNLOGQZ128rri: case X86::VPTERNLOGQZ128rmi:
2054  case X86::VPTERNLOGQZ256rri: case X86::VPTERNLOGQZ256rmi:
2055  case X86::VPTERNLOGDZrrik:
2056  case X86::VPTERNLOGDZ128rrik:
2057  case X86::VPTERNLOGDZ256rrik:
2058  case X86::VPTERNLOGQZrrik:
2059  case X86::VPTERNLOGQZ128rrik:
2060  case X86::VPTERNLOGQZ256rrik:
2061  case X86::VPTERNLOGDZrrikz: case X86::VPTERNLOGDZrmikz:
2062  case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
2063  case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
2064  case X86::VPTERNLOGQZrrikz: case X86::VPTERNLOGQZrmikz:
2065  case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
2066  case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
2067  case X86::VPTERNLOGDZ128rmbi:
2068  case X86::VPTERNLOGDZ256rmbi:
2069  case X86::VPTERNLOGDZrmbi:
2070  case X86::VPTERNLOGQZ128rmbi:
2071  case X86::VPTERNLOGQZ256rmbi:
2072  case X86::VPTERNLOGQZrmbi:
2073  case X86::VPTERNLOGDZ128rmbikz:
2074  case X86::VPTERNLOGDZ256rmbikz:
2075  case X86::VPTERNLOGDZrmbikz:
2076  case X86::VPTERNLOGQZ128rmbikz:
2077  case X86::VPTERNLOGQZ256rmbikz:
2078  case X86::VPTERNLOGQZrmbikz:
2079  return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2080  case X86::VPDPWSSDZ128r:
2081  case X86::VPDPWSSDZ128rk:
2082  case X86::VPDPWSSDZ128rkz:
2083  case X86::VPDPWSSDZ256r:
2084  case X86::VPDPWSSDZ256rk:
2085  case X86::VPDPWSSDZ256rkz:
2086  case X86::VPDPWSSDZr:
2087  case X86::VPDPWSSDZrk:
2088  case X86::VPDPWSSDZrkz:
2089  case X86::VPDPWSSDSZ128r:
2090  case X86::VPDPWSSDSZ128rk:
2091  case X86::VPDPWSSDSZ128rkz:
2092  case X86::VPDPWSSDSZ256r:
2093  case X86::VPDPWSSDSZ256rk:
2094  case X86::VPDPWSSDSZ256rkz:
2095  case X86::VPDPWSSDSZr:
2096  case X86::VPDPWSSDSZrk:
2097  case X86::VPDPWSSDSZrkz:
2098  case X86::VPMADD52HUQZ128r:
2099  case X86::VPMADD52HUQZ128rk:
2100  case X86::VPMADD52HUQZ128rkz:
2101  case X86::VPMADD52HUQZ256r:
2102  case X86::VPMADD52HUQZ256rk:
2103  case X86::VPMADD52HUQZ256rkz:
2104  case X86::VPMADD52HUQZr:
2105  case X86::VPMADD52HUQZrk:
2106  case X86::VPMADD52HUQZrkz:
2107  case X86::VPMADD52LUQZ128r:
2108  case X86::VPMADD52LUQZ128rk:
2109  case X86::VPMADD52LUQZ128rkz:
2110  case X86::VPMADD52LUQZ256r:
2111  case X86::VPMADD52LUQZ256rk:
2112  case X86::VPMADD52LUQZ256rkz:
2113  case X86::VPMADD52LUQZr:
2114  case X86::VPMADD52LUQZrk:
2115  case X86::VPMADD52LUQZrkz: {
2116  unsigned CommutableOpIdx1 = 2;
2117  unsigned CommutableOpIdx2 = 3;
2118  if (X86II::isKMasked(Desc.TSFlags)) {
2119  // Skip the mask register.
2120  ++CommutableOpIdx1;
2121  ++CommutableOpIdx2;
2122  }
2123  if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2124  CommutableOpIdx1, CommutableOpIdx2))
2125  return false;
2126  if (!MI.getOperand(SrcOpIdx1).isReg() ||
2127  !MI.getOperand(SrcOpIdx2).isReg())
2128  // No idea.
2129  return false;
2130  return true;
2131  }
2132 
2133  default:
2134  const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
2135  MI.getDesc().TSFlags);
2136  if (FMA3Group)
2137  return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2,
2138  FMA3Group->isIntrinsic());
2139 
2140  // Handled masked instructions since we need to skip over the mask input
2141  // and the preserved input.
2142  if (X86II::isKMasked(Desc.TSFlags)) {
2143  // First assume that the first input is the mask operand and skip past it.
2144  unsigned CommutableOpIdx1 = Desc.getNumDefs() + 1;
2145  unsigned CommutableOpIdx2 = Desc.getNumDefs() + 2;
2146  // Check if the first input is tied. If there isn't one then we only
2147  // need to skip the mask operand which we did above.
2148  if ((MI.getDesc().getOperandConstraint(Desc.getNumDefs(),
2149  MCOI::TIED_TO) != -1)) {
2150  // If this is zero masking instruction with a tied operand, we need to
2151  // move the first index back to the first input since this must
2152  // be a 3 input instruction and we want the first two non-mask inputs.
2153  // Otherwise this is a 2 input instruction with a preserved input and
2154  // mask, so we need to move the indices to skip one more input.
2155  if (X86II::isKMergeMasked(Desc.TSFlags)) {
2156  ++CommutableOpIdx1;
2157  ++CommutableOpIdx2;
2158  } else {
2159  --CommutableOpIdx1;
2160  }
2161  }
2162 
2163  if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2164  CommutableOpIdx1, CommutableOpIdx2))
2165  return false;
2166 
2167  if (!MI.getOperand(SrcOpIdx1).isReg() ||
2168  !MI.getOperand(SrcOpIdx2).isReg())
2169  // No idea.
2170  return false;
2171  return true;
2172  }
2173 
2174  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2175  }
2176  return false;
2177 }
2178 
2180  switch (MI.getOpcode()) {
2181  default: return X86::COND_INVALID;
2182  case X86::JCC_1:
2183  return static_cast<X86::CondCode>(
2184  MI.getOperand(MI.getDesc().getNumOperands() - 1).getImm());
2185  }
2186 }
2187 
2188 /// Return condition code of a SETCC opcode.
2190  switch (MI.getOpcode()) {
2191  default: return X86::COND_INVALID;
2192  case X86::SETCCr: case X86::SETCCm:
2193  return static_cast<X86::CondCode>(
2194  MI.getOperand(MI.getDesc().getNumOperands() - 1).getImm());
2195  }
2196 }
2197 
2198 /// Return condition code of a CMov opcode.
2200  switch (MI.getOpcode()) {
2201  default: return X86::COND_INVALID;
2202  case X86::CMOV16rr: case X86::CMOV32rr: case X86::CMOV64rr:
2203  case X86::CMOV16rm: case X86::CMOV32rm: case X86::CMOV64rm:
2204  return static_cast<X86::CondCode>(
2205  MI.getOperand(MI.getDesc().getNumOperands() - 1).getImm());
2206  }
2207 }
2208 
2209 /// Return the inverse of the specified condition,
2210 /// e.g. turning COND_E to COND_NE.
2212  switch (CC) {
2213  default: llvm_unreachable("Illegal condition code!");
2214  case X86::COND_E: return X86::COND_NE;
2215  case X86::COND_NE: return X86::COND_E;
2216  case X86::COND_L: return X86::COND_GE;
2217  case X86::COND_LE: return X86::COND_G;
2218  case X86::COND_G: return X86::COND_LE;
2219  case X86::COND_GE: return X86::COND_L;
2220  case X86::COND_B: return X86::COND_AE;
2221  case X86::COND_BE: return X86::COND_A;
2222  case X86::COND_A: return X86::COND_BE;
2223  case X86::COND_AE: return X86::COND_B;
2224  case X86::COND_S: return X86::COND_NS;
2225  case X86::COND_NS: return X86::COND_S;
2226  case X86::COND_P: return X86::COND_NP;
2227  case X86::COND_NP: return X86::COND_P;
2228  case X86::COND_O: return X86::COND_NO;
2229  case X86::COND_NO: return X86::COND_O;
2232  }
2233 }
2234 
2235 /// Assuming the flags are set by MI(a,b), return the condition code if we
2236 /// modify the instructions such that flags are set by MI(b,a).
2238  switch (CC) {
2239  default: return X86::COND_INVALID;
2240  case X86::COND_E: return X86::COND_E;
2241  case X86::COND_NE: return X86::COND_NE;
2242  case X86::COND_L: return X86::COND_G;
2243  case X86::COND_LE: return X86::COND_GE;
2244  case X86::COND_G: return X86::COND_L;
2245  case X86::COND_GE: return X86::COND_LE;
2246  case X86::COND_B: return X86::COND_A;
2247  case X86::COND_BE: return X86::COND_AE;
2248  case X86::COND_A: return X86::COND_B;
2249  case X86::COND_AE: return X86::COND_BE;
2250  }
2251 }
2252 
2253 std::pair<X86::CondCode, bool>
2256  bool NeedSwap = false;
2257  switch (Predicate) {
2258  default: break;
2259  // Floating-point Predicates
2260  case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
2261  case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH;
2262  case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
2263  case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH;
2264  case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
2265  case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH;
2266  case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
2267  case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH;
2268  case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
2269  case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
2270  case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
2271  case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
2273  case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
2274 
2275  // Integer Predicates
2276  case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
2277  case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
2278  case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
2279  case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
2280  case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
2281  case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
2282  case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
2283  case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
2284  case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
2285  case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
2286  }
2287 
2288  return std::make_pair(CC, NeedSwap);
2289 }
2290 
2291 /// Return a setcc opcode based on whether it has memory operand.
2292 unsigned X86::getSETOpc(bool HasMemoryOperand) {
2293  return HasMemoryOperand ? X86::SETCCr : X86::SETCCm;
2294 }
2295 
2296 /// Return a cmov opcode for the given register size in bytes, and operand type.
2297 unsigned X86::getCMovOpcode(unsigned RegBytes, bool HasMemoryOperand) {
2298  switch(RegBytes) {
2299  default: llvm_unreachable("Illegal register size!");
2300  case 2: return HasMemoryOperand ? X86::CMOV16rm : X86::CMOV16rr;
2301  case 4: return HasMemoryOperand ? X86::CMOV32rm : X86::CMOV32rr;
2302  case 8: return HasMemoryOperand ? X86::CMOV32rm : X86::CMOV64rr;
2303  }
2304 }
2305 
2306 /// Get the VPCMP immediate for the given condition.
2308  switch (CC) {
2309  default: llvm_unreachable("Unexpected SETCC condition");
2310  case ISD::SETNE: return 4;
2311  case ISD::SETEQ: return 0;
2312  case ISD::SETULT:
2313  case ISD::SETLT: return 1;
2314  case ISD::SETUGT:
2315  case ISD::SETGT: return 6;
2316  case ISD::SETUGE:
2317  case ISD::SETGE: return 5;
2318  case ISD::SETULE:
2319  case ISD::SETLE: return 2;
2320  }
2321 }
2322 
2323 /// Get the VPCMP immediate if the operands are swapped.
2324 unsigned X86::getSwappedVPCMPImm(unsigned Imm) {
2325  switch (Imm) {
2326  default: llvm_unreachable("Unreachable!");
2327  case 0x01: Imm = 0x06; break; // LT -> NLE
2328  case 0x02: Imm = 0x05; break; // LE -> NLT
2329  case 0x05: Imm = 0x02; break; // NLT -> LE
2330  case 0x06: Imm = 0x01; break; // NLE -> LT
2331  case 0x00: // EQ
2332  case 0x03: // FALSE
2333  case 0x04: // NE
2334  case 0x07: // TRUE
2335  break;
2336  }
2337 
2338  return Imm;
2339 }
2340 
2341 /// Get the VPCOM immediate if the operands are swapped.
2342 unsigned X86::getSwappedVPCOMImm(unsigned Imm) {
2343  switch (Imm) {
2344  default: llvm_unreachable("Unreachable!");
2345  case 0x00: Imm = 0x02; break; // LT -> GT
2346  case 0x01: Imm = 0x03; break; // LE -> GE
2347  case 0x02: Imm = 0x00; break; // GT -> LT
2348  case 0x03: Imm = 0x01; break; // GE -> LE
2349  case 0x04: // EQ
2350  case 0x05: // NE
2351  case 0x06: // FALSE
2352  case 0x07: // TRUE
2353  break;
2354  }
2355 
2356  return Imm;
2357 }
2358 
2359 /// Get the VCMP immediate if the operands are swapped.
2360 unsigned X86::getSwappedVCMPImm(unsigned Imm) {
2361  // Only need the lower 2 bits to distinquish.
2362  switch (Imm & 0x3) {
2363  default: llvm_unreachable("Unreachable!");
2364  case 0x00: case 0x03:
2365  // EQ/NE/TRUE/FALSE/ORD/UNORD don't change immediate when commuted.
2366  break;
2367  case 0x01: case 0x02:
2368  // Need to toggle bits 3:0. Bit 4 stays the same.
2369  Imm ^= 0xf;
2370  break;
2371  }
2372 
2373  return Imm;
2374 }
2375 
2377  if (!MI.isTerminator()) return false;
2378 
2379  // Conditional branch is a special case.
2380  if (MI.isBranch() && !MI.isBarrier())
2381  return true;
2382  if (!MI.isPredicable())
2383  return true;
2384  return !isPredicated(MI);
2385 }
2386 
2388  switch (MI.getOpcode()) {
2389  case X86::TCRETURNdi:
2390  case X86::TCRETURNri:
2391  case X86::TCRETURNmi:
2392  case X86::TCRETURNdi64:
2393  case X86::TCRETURNri64:
2394  case X86::TCRETURNmi64:
2395  return true;
2396  default:
2397  return false;
2398  }
2399 }
2400 
2402  SmallVectorImpl<MachineOperand> &BranchCond,
2403  const MachineInstr &TailCall) const {
2404  if (TailCall.getOpcode() != X86::TCRETURNdi &&
2405  TailCall.getOpcode() != X86::TCRETURNdi64) {
2406  // Only direct calls can be done with a conditional branch.
2407  return false;
2408  }
2409 
2410  const MachineFunction *MF = TailCall.getParent()->getParent();
2411  if (Subtarget.isTargetWin64() && MF->hasWinCFI()) {
2412  // Conditional tail calls confuse the Win64 unwinder.
2413  return false;
2414  }
2415 
2416  assert(BranchCond.size() == 1);
2417  if (BranchCond[0].getImm() > X86::LAST_VALID_COND) {
2418  // Can't make a conditional tail call with this condition.
2419  return false;
2420  }
2421 
2423  if (X86FI->getTCReturnAddrDelta() != 0 ||
2424  TailCall.getOperand(1).getImm() != 0) {
2425  // A conditional tail call cannot do any stack adjustment.
2426  return false;
2427  }
2428 
2429  return true;
2430 }
2431 
2434  const MachineInstr &TailCall) const {
2435  assert(canMakeTailCallConditional(BranchCond, TailCall));
2436 
2438  while (I != MBB.begin()) {
2439  --I;
2440  if (I->isDebugInstr())
2441  continue;
2442  if (!I->isBranch())
2443  assert(0 && "Can't find the branch to replace!");
2444 
2446  assert(BranchCond.size() == 1);
2447  if (CC != BranchCond[0].getImm())
2448  continue;
2449 
2450  break;
2451  }
2452 
2453  unsigned Opc = TailCall.getOpcode() == X86::TCRETURNdi ? X86::TCRETURNdicc
2454  : X86::TCRETURNdi64cc;
2455 
2456  auto MIB = BuildMI(MBB, I, MBB.findDebugLoc(I), get(Opc));
2457  MIB->addOperand(TailCall.getOperand(0)); // Destination.
2458  MIB.addImm(0); // Stack offset (not used).
2459  MIB->addOperand(BranchCond[0]); // Condition.
2460  MIB.copyImplicitOps(TailCall); // Regmask and (imp-used) parameters.
2461 
2462  // Add implicit uses and defs of all live regs potentially clobbered by the
2463  // call. This way they still appear live across the call.
2464  LivePhysRegs LiveRegs(getRegisterInfo());
2465  LiveRegs.addLiveOuts(MBB);
2467  LiveRegs.stepForward(*MIB, Clobbers);
2468  for (const auto &C : Clobbers) {
2469  MIB.addReg(C.first, RegState::Implicit);
2470  MIB.addReg(C.first, RegState::Implicit | RegState::Define);
2471  }
2472 
2473  I->eraseFromParent();
2474 }
2475 
2476 // Given a MBB and its TBB, find the FBB which was a fallthrough MBB (it may
2477 // not be a fallthrough MBB now due to layout changes). Return nullptr if the
2478 // fallthrough MBB cannot be identified.
2480  MachineBasicBlock *TBB) {
2481  // Look for non-EHPad successors other than TBB. If we find exactly one, it
2482  // is the fallthrough MBB. If we find zero, then TBB is both the target MBB
2483  // and fallthrough MBB. If we find more than one, we cannot identify the
2484  // fallthrough MBB and should return nullptr.
2485  MachineBasicBlock *FallthroughBB = nullptr;
2486  for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) {
2487  if ((*SI)->isEHPad() || (*SI == TBB && FallthroughBB))
2488  continue;
2489  // Return a nullptr if we found more than one fallthrough successor.
2490  if (FallthroughBB && FallthroughBB != TBB)
2491  return nullptr;
2492  FallthroughBB = *SI;
2493  }
2494  return FallthroughBB;
2495 }
2496 
2497 bool X86InstrInfo::AnalyzeBranchImpl(
2500  SmallVectorImpl<MachineInstr *> &CondBranches, bool AllowModify) const {
2501 
2502  // Start from the bottom of the block and work up, examining the
2503  // terminator instructions.
2505  MachineBasicBlock::iterator UnCondBrIter = MBB.end();
2506  while (I != MBB.begin()) {
2507  --I;
2508  if (I->isDebugInstr())
2509  continue;
2510 
2511  // Working from the bottom, when we see a non-terminator instruction, we're
2512  // done.
2513  if (!isUnpredicatedTerminator(*I))
2514  break;
2515 
2516  // A terminator that isn't a branch can't easily be handled by this
2517  // analysis.
2518  if (!I->isBranch())
2519  return true;
2520 
2521  // Handle unconditional branches.
2522  if (I->getOpcode() == X86::JMP_1) {
2523  UnCondBrIter = I;
2524 
2525  if (!AllowModify) {
2526  TBB = I->getOperand(0).getMBB();
2527  continue;
2528  }
2529 
2530  // If the block has any instructions after a JMP, delete them.
2531  while (std::next(I) != MBB.end())
2532  std::next(I)->eraseFromParent();
2533 
2534  Cond.clear();
2535  FBB = nullptr;
2536 
2537  // Delete the JMP if it's equivalent to a fall-through.
2538  if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
2539  TBB = nullptr;
2540  I->eraseFromParent();
2541  I = MBB.end();
2542  UnCondBrIter = MBB.end();
2543  continue;
2544  }
2545 
2546  // TBB is used to indicate the unconditional destination.
2547  TBB = I->getOperand(0).getMBB();
2548  continue;
2549  }
2550 
2551  // Handle conditional branches.
2552  X86::CondCode BranchCode = X86::getCondFromBranch(*I);
2553  if (BranchCode == X86::COND_INVALID)
2554  return true; // Can't handle indirect branch.
2555 
2556  // In practice we should never have an undef eflags operand, if we do
2557  // abort here as we are not prepared to preserve the flag.
2558  if (I->findRegisterUseOperand(X86::EFLAGS)->isUndef())
2559  return true;
2560 
2561  // Working from the bottom, handle the first conditional branch.
2562  if (Cond.empty()) {
2563  MachineBasicBlock *TargetBB = I->getOperand(0).getMBB();
2564  if (AllowModify && UnCondBrIter != MBB.end() &&
2565  MBB.isLayoutSuccessor(TargetBB)) {
2566  // If we can modify the code and it ends in something like:
2567  //
2568  // jCC L1
2569  // jmp L2
2570  // L1:
2571  // ...
2572  // L2:
2573  //
2574  // Then we can change this to:
2575  //
2576  // jnCC L2
2577  // L1:
2578  // ...
2579  // L2:
2580  //
2581  // Which is a bit more efficient.
2582  // We conditionally jump to the fall-through block.
2583  BranchCode = GetOppositeBranchCondition(BranchCode);
2584  MachineBasicBlock::iterator OldInst = I;
2585 
2586  BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(X86::JCC_1))
2587  .addMBB(UnCondBrIter->getOperand(0).getMBB())
2588  .addImm(BranchCode);
2589  BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(X86::JMP_1))
2590  .addMBB(TargetBB);
2591 
2592  OldInst->eraseFromParent();
2593  UnCondBrIter->eraseFromParent();
2594 
2595  // Restart the analysis.
2596  UnCondBrIter = MBB.end();
2597  I = MBB.end();
2598  continue;
2599  }
2600 
2601  FBB = TBB;
2602  TBB = I->getOperand(0).getMBB();
2603  Cond.push_back(MachineOperand::CreateImm(BranchCode));
2604  CondBranches.push_back(&*I);
2605  continue;
2606  }
2607 
2608  // Handle subsequent conditional branches. Only handle the case where all
2609  // conditional branches branch to the same destination and their condition
2610  // opcodes fit one of the special multi-branch idioms.
2611  assert(Cond.size() == 1);
2612  assert(TBB);
2613 
2614  // If the conditions are the same, we can leave them alone.
2615  X86::CondCode OldBranchCode = (X86::CondCode)Cond[0].getImm();
2616  auto NewTBB = I->getOperand(0).getMBB();
2617  if (OldBranchCode == BranchCode && TBB == NewTBB)
2618  continue;
2619 
2620  // If they differ, see if they fit one of the known patterns. Theoretically,
2621  // we could handle more patterns here, but we shouldn't expect to see them
2622  // if instruction selection has done a reasonable job.
2623  if (TBB == NewTBB &&
2624  ((OldBranchCode == X86::COND_P && BranchCode == X86::COND_NE) ||
2625  (OldBranchCode == X86::COND_NE && BranchCode == X86::COND_P))) {
2626  BranchCode = X86::COND_NE_OR_P;
2627  } else if ((OldBranchCode == X86::COND_NP && BranchCode == X86::COND_NE) ||
2628  (OldBranchCode == X86::COND_E && BranchCode == X86::COND_P)) {
2629  if (NewTBB != (FBB ? FBB : getFallThroughMBB(&MBB, TBB)))
2630  return true;
2631 
2632  // X86::COND_E_AND_NP usually has two different branch destinations.
2633  //
2634  // JP B1
2635  // JE B2
2636  // JMP B1
2637  // B1:
2638  // B2:
2639  //
2640  // Here this condition branches to B2 only if NP && E. It has another
2641  // equivalent form:
2642  //
2643  // JNE B1
2644  // JNP B2
2645  // JMP B1
2646  // B1:
2647  // B2:
2648  //
2649  // Similarly it branches to B2 only if E && NP. That is why this condition
2650  // is named with COND_E_AND_NP.
2651  BranchCode = X86::COND_E_AND_NP;
2652  } else
2653  return true;
2654 
2655  // Update the MachineOperand.
2656  Cond[0].setImm(BranchCode);
2657  CondBranches.push_back(&*I);
2658  }
2659 
2660  return false;
2661 }
2662 
2664  MachineBasicBlock *&TBB,
2665  MachineBasicBlock *&FBB,
2667  bool AllowModify) const {
2668  SmallVector<MachineInstr *, 4> CondBranches;
2669  return AnalyzeBranchImpl(MBB, TBB, FBB, Cond, CondBranches, AllowModify);
2670 }
2671 
2673  MachineBranchPredicate &MBP,
2674  bool AllowModify) const {
2675  using namespace std::placeholders;
2676 
2678  SmallVector<MachineInstr *, 4> CondBranches;
2679  if (AnalyzeBranchImpl(MBB, MBP.TrueDest, MBP.FalseDest, Cond, CondBranches,
2680  AllowModify))
2681  return true;
2682 
2683  if (Cond.size() != 1)
2684  return true;
2685 
2686  assert(MBP.TrueDest && "expected!");
2687 
2688  if (!MBP.FalseDest)
2689  MBP.FalseDest = MBB.getNextNode();
2690 
2692 
2693  MachineInstr *ConditionDef = nullptr;
2694  bool SingleUseCondition = true;
2695 
2696  for (auto I = std::next(MBB.rbegin()), E = MBB.rend(); I != E; ++I) {
2697  if (I->modifiesRegister(X86::EFLAGS, TRI)) {
2698  ConditionDef = &*I;
2699  break;
2700  }
2701 
2702  if (I->readsRegister(X86::EFLAGS, TRI))
2703  SingleUseCondition = false;
2704  }
2705 
2706  if (!ConditionDef)
2707  return true;
2708 
2709  if (SingleUseCondition) {
2710  for (auto *Succ : MBB.successors())
2711  if (Succ->isLiveIn(X86::EFLAGS))
2712  SingleUseCondition = false;
2713  }
2714 
2715  MBP.ConditionDef = ConditionDef;
2716  MBP.SingleUseCondition = SingleUseCondition;
2717 
2718  // Currently we only recognize the simple pattern:
2719  //
2720  // test %reg, %reg
2721  // je %label
2722  //
2723  const unsigned TestOpcode =
2724  Subtarget.is64Bit() ? X86::TEST64rr : X86::TEST32rr;
2725 
2726  if (ConditionDef->getOpcode() == TestOpcode &&
2727  ConditionDef->getNumOperands() == 3 &&
2728  ConditionDef->getOperand(0).isIdenticalTo(ConditionDef->getOperand(1)) &&
2729  (Cond[0].getImm() == X86::COND_NE || Cond[0].getImm() == X86::COND_E)) {
2730  MBP.LHS = ConditionDef->getOperand(0);
2731  MBP.RHS = MachineOperand::CreateImm(0);
2732  MBP.Predicate = Cond[0].getImm() == X86::COND_NE
2735  return false;
2736  }
2737 
2738  return true;
2739 }
2740 
2742  int *BytesRemoved) const {
2743  assert(!BytesRemoved && "code size not handled");
2744 
2746  unsigned Count = 0;
2747 
2748  while (I != MBB.begin()) {
2749  --I;
2750  if (I->isDebugInstr())
2751  continue;
2752  if (I->getOpcode() != X86::JMP_1 &&
2754  break;
2755  // Remove the branch.
2756  I->eraseFromParent();
2757  I = MBB.end();
2758  ++Count;
2759  }
2760 
2761  return Count;
2762 }
2763 
2765  MachineBasicBlock *TBB,
2766  MachineBasicBlock *FBB,
2768  const DebugLoc &DL,
2769  int *BytesAdded) const {
2770  // Shouldn't be a fall through.
2771  assert(TBB && "insertBranch must not be told to insert a fallthrough");
2772  assert((Cond.size() == 1 || Cond.size() == 0) &&
2773  "X86 branch conditions have one component!");
2774  assert(!BytesAdded && "code size not handled");
2775 
2776  if (Cond.empty()) {
2777  // Unconditional branch?
2778  assert(!FBB && "Unconditional branch with multiple successors!");
2779  BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(TBB);
2780  return 1;
2781  }
2782 
2783  // If FBB is null, it is implied to be a fall-through block.
2784  bool FallThru = FBB == nullptr;
2785 
2786  // Conditional branch.
2787  unsigned Count = 0;
2788  X86::CondCode CC = (X86::CondCode)Cond[0].getImm();
2789  switch (CC) {
2790  case X86::COND_NE_OR_P:
2791  // Synthesize NE_OR_P with two branches.
2792  BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(X86::COND_NE);
2793  ++Count;
2794  BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(X86::COND_P);
2795  ++Count;
2796  break;
2797  case X86::COND_E_AND_NP:
2798  // Use the next block of MBB as FBB if it is null.
2799  if (FBB == nullptr) {
2800  FBB = getFallThroughMBB(&MBB, TBB);
2801  assert(FBB && "MBB cannot be the last block in function when the false "
2802  "body is a fall-through.");
2803  }
2804  // Synthesize COND_E_AND_NP with two branches.
2805  BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(FBB).addImm(X86::COND_NE);
2806  ++Count;
2807  BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(X86::COND_NP);
2808  ++Count;
2809  break;
2810  default: {
2811  BuildMI(&MBB, DL, get(X86::JCC_1)).addMBB(TBB).addImm(CC);
2812  ++Count;
2813  }
2814  }
2815  if (!FallThru) {
2816  // Two-way Conditional branch. Insert the second branch.
2817  BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(FBB);
2818  ++Count;
2819  }
2820  return Count;
2821 }
2822 
2823 bool X86InstrInfo::
2826  unsigned TrueReg, unsigned FalseReg,
2827  int &CondCycles, int &TrueCycles, int &FalseCycles) const {
2828  // Not all subtargets have cmov instructions.
2829  if (!Subtarget.hasCMov())
2830  return false;
2831  if (Cond.size() != 1)
2832  return false;
2833  // We cannot do the composite conditions, at least not in SSA form.
2834  if ((X86::CondCode)Cond[0].getImm() > X86::LAST_VALID_COND)
2835  return false;
2836 
2837  // Check register classes.
2838  const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2839  const TargetRegisterClass *RC =
2840  RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
2841  if (!RC)
2842  return false;
2843 
2844  // We have cmov instructions for 16, 32, and 64 bit general purpose registers.
2845  if (X86::GR16RegClass.hasSubClassEq(RC) ||
2846  X86::GR32RegClass.hasSubClassEq(RC) ||
2847  X86::GR64RegClass.hasSubClassEq(RC)) {
2848  // This latency applies to Pentium M, Merom, Wolfdale, Nehalem, and Sandy
2849  // Bridge. Probably Ivy Bridge as well.
2850  CondCycles = 2;
2851  TrueCycles = 2;
2852  FalseCycles = 2;
2853  return true;
2854  }
2855 
2856  // Can't do vectors.
2857  return false;
2858 }
2859 
2862  const DebugLoc &DL, unsigned DstReg,
2863  ArrayRef<MachineOperand> Cond, unsigned TrueReg,
2864  unsigned FalseReg) const {
2867  const TargetRegisterClass &RC = *MRI.getRegClass(DstReg);
2868  assert(Cond.size() == 1 && "Invalid Cond array");
2869  unsigned Opc = X86::getCMovOpcode(TRI.getRegSizeInBits(RC) / 8,
2870  false /*HasMemoryOperand*/);
2871  BuildMI(MBB, I, DL, get(Opc), DstReg)
2872  .addReg(FalseReg)
2873  .addReg(TrueReg)
2874  .addImm(Cond[0].getImm());
2875 }
2876 
2877 /// Test if the given register is a physical h register.
2878 static bool isHReg(unsigned Reg) {
2879  return X86::GR8_ABCD_HRegClass.contains(Reg);
2880 }
2881 
2882 // Try and copy between VR128/VR64 and GR64 registers.
2883 static unsigned CopyToFromAsymmetricReg(unsigned DestReg, unsigned SrcReg,
2884  const X86Subtarget &Subtarget) {
2885  bool HasAVX = Subtarget.hasAVX();
2886  bool HasAVX512 = Subtarget.hasAVX512();
2887 
2888  // SrcReg(MaskReg) -> DestReg(GR64)
2889  // SrcReg(MaskReg) -> DestReg(GR32)
2890 
2891  // All KMASK RegClasses hold the same k registers, can be tested against anyone.
2892  if (X86::VK16RegClass.contains(SrcReg)) {
2893  if (X86::GR64RegClass.contains(DestReg)) {
2894  assert(Subtarget.hasBWI());
2895  return X86::KMOVQrk;
2896  }
2897  if (X86::GR32RegClass.contains(DestReg))
2898  return Subtarget.hasBWI() ? X86::KMOVDrk : X86::KMOVWrk;
2899  }
2900 
2901  // SrcReg(GR64) -> DestReg(MaskReg)
2902  // SrcReg(GR32) -> DestReg(MaskReg)
2903 
2904  // All KMASK RegClasses hold the same k registers, can be tested against anyone.
2905  if (X86::VK16RegClass.contains(DestReg)) {
2906  if (X86::GR64RegClass.contains(SrcReg)) {
2907  assert(Subtarget.hasBWI());
2908  return X86::KMOVQkr;
2909  }
2910  if (X86::GR32RegClass.contains(SrcReg))
2911  return Subtarget.hasBWI() ? X86::KMOVDkr : X86::KMOVWkr;
2912  }
2913 
2914 
2915  // SrcReg(VR128) -> DestReg(GR64)
2916  // SrcReg(VR64) -> DestReg(GR64)
2917  // SrcReg(GR64) -> DestReg(VR128)
2918  // SrcReg(GR64) -> DestReg(VR64)
2919 
2920  if (X86::GR64RegClass.contains(DestReg)) {
2921  if (X86::VR128XRegClass.contains(SrcReg))
2922  // Copy from a VR128 register to a GR64 register.
2923  return HasAVX512 ? X86::VMOVPQIto64Zrr :
2924  HasAVX ? X86::VMOVPQIto64rr :
2925  X86::MOVPQIto64rr;
2926  if (X86::VR64RegClass.contains(SrcReg))
2927  // Copy from a VR64 register to a GR64 register.
2928  return X86::MMX_MOVD64from64rr;
2929  } else if (X86::GR64RegClass.contains(SrcReg)) {
2930  // Copy from a GR64 register to a VR128 register.
2931  if (X86::VR128XRegClass.contains(DestReg))
2932  return HasAVX512 ? X86::VMOV64toPQIZrr :
2933  HasAVX ? X86::VMOV64toPQIrr :
2934  X86::MOV64toPQIrr;
2935  // Copy from a GR64 register to a VR64 register.
2936  if (X86::VR64RegClass.contains(DestReg))
2937  return X86::MMX_MOVD64to64rr;
2938  }
2939 
2940  // SrcReg(VR128) -> DestReg(GR32)
2941  // SrcReg(GR32) -> DestReg(VR128)
2942 
2943  if (X86::GR32RegClass.contains(DestReg) &&
2944  X86::VR128XRegClass.contains(SrcReg))
2945  // Copy from a VR128 register to a GR32 register.
2946  return HasAVX512 ? X86::VMOVPDI2DIZrr :
2947  HasAVX ? X86::VMOVPDI2DIrr :
2948  X86::MOVPDI2DIrr;
2949 
2950  if (X86::VR128XRegClass.contains(DestReg) &&
2951  X86::GR32RegClass.contains(SrcReg))
2952  // Copy from a VR128 register to a VR128 register.
2953  return HasAVX512 ? X86::VMOVDI2PDIZrr :
2954  HasAVX ? X86::VMOVDI2PDIrr :
2955  X86::MOVDI2PDIrr;
2956  return 0;
2957 }
2958 
2961  const DebugLoc &DL, unsigned DestReg,
2962  unsigned SrcReg, bool KillSrc) const {
2963  // First deal with the normal symmetric copies.
2964  bool HasAVX = Subtarget.hasAVX();
2965  bool HasVLX = Subtarget.hasVLX();
2966  unsigned Opc = 0;
2967  if (X86::GR64RegClass.contains(DestReg, SrcReg))
2968  Opc = X86::MOV64rr;
2969  else if (X86::GR32RegClass.contains(DestReg, SrcReg))
2970  Opc = X86::MOV32rr;
2971  else if (X86::GR16RegClass.contains(DestReg, SrcReg))
2972  Opc = X86::MOV16rr;
2973  else if (X86::GR8RegClass.contains(DestReg, SrcReg)) {
2974  // Copying to or from a physical H register on x86-64 requires a NOREX
2975  // move. Otherwise use a normal move.
2976  if ((isHReg(DestReg) || isHReg(SrcReg)) &&
2977  Subtarget.is64Bit()) {
2978  Opc = X86::MOV8rr_NOREX;
2979  // Both operands must be encodable without an REX prefix.
2980  assert(X86::GR8_NOREXRegClass.contains(SrcReg, DestReg) &&
2981  "8-bit H register can not be copied outside GR8_NOREX");
2982  } else
2983  Opc = X86::MOV8rr;
2984  }
2985  else if (X86::VR64RegClass.contains(DestReg, SrcReg))
2986  Opc = X86::MMX_MOVQ64rr;
2987  else if (X86::VR128XRegClass.contains(DestReg, SrcReg)) {
2988  if (HasVLX)
2989  Opc = X86::VMOVAPSZ128rr;
2990  else if (X86::VR128RegClass.contains(DestReg, SrcReg))
2991  Opc = HasAVX ? X86::VMOVAPSrr : X86::MOVAPSrr;
2992  else {
2993  // If this an extended register and we don't have VLX we need to use a
2994  // 512-bit move.
2995  Opc = X86::VMOVAPSZrr;
2997  DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_xmm,
2998  &X86::VR512RegClass);
2999  SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm,
3000  &X86::VR512RegClass);
3001  }
3002  } else if (X86::VR256XRegClass.contains(DestReg, SrcReg)) {
3003  if (HasVLX)
3004  Opc = X86::VMOVAPSZ256rr;
3005  else if (X86::VR256RegClass.contains(DestReg, SrcReg))
3006  Opc = X86::VMOVAPSYrr;
3007  else {
3008  // If this an extended register and we don't have VLX we need to use a
3009  // 512-bit move.
3010  Opc = X86::VMOVAPSZrr;
3012  DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_ymm,
3013  &X86::VR512RegClass);
3014  SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_ymm,
3015  &X86::VR512RegClass);
3016  }
3017  } else if (X86::VR512RegClass.contains(DestReg, SrcReg))
3018  Opc = X86::VMOVAPSZrr;
3019  // All KMASK RegClasses hold the same k registers, can be tested against anyone.
3020  else if (X86::VK16RegClass.contains(DestReg, SrcReg))
3021  Opc = Subtarget.hasBWI() ? X86::KMOVQkk : X86::KMOVWkk;
3022  if (!Opc)
3023  Opc = CopyToFromAsymmetricReg(DestReg, SrcReg, Subtarget);
3024 
3025  if (Opc) {
3026  BuildMI(MBB, MI, DL, get(Opc), DestReg)
3027  .addReg(SrcReg, getKillRegState(KillSrc));
3028  return;
3029  }
3030 
3031  if (SrcReg == X86::EFLAGS || DestReg == X86::EFLAGS) {
3032  // FIXME: We use a fatal error here because historically LLVM has tried
3033  // lower some of these physreg copies and we want to ensure we get
3034  // reasonable bug reports if someone encounters a case no other testing
3035  // found. This path should be removed after the LLVM 7 release.
3036  report_fatal_error("Unable to copy EFLAGS physical register!");
3037  }
3038 
3039  LLVM_DEBUG(dbgs() << "Cannot copy " << RI.getName(SrcReg) << " to "
3040  << RI.getName(DestReg) << '\n');
3041  report_fatal_error("Cannot emit physreg copy instruction");
3042 }
3043 
3045  const MachineOperand *&Src,
3046  const MachineOperand *&Dest) const {
3047  if (MI.isMoveReg()) {
3048  Dest = &MI.getOperand(0);
3049  Src = &MI.getOperand(1);
3050  return true;
3051  }
3052  return false;
3053 }
3054 
3055 static unsigned getLoadStoreRegOpcode(unsigned Reg,
3056  const TargetRegisterClass *RC,
3057  bool isStackAligned,
3058  const X86Subtarget &STI,
3059  bool load) {
3060  bool HasAVX = STI.hasAVX();
3061  bool HasAVX512 = STI.hasAVX512();
3062  bool HasVLX = STI.hasVLX();
3063 
3064  switch (STI.getRegisterInfo()->getSpillSize(*RC)) {
3065  default:
3066  llvm_unreachable("Unknown spill size");
3067  case 1:
3068  assert(X86::GR8RegClass.hasSubClassEq(RC) && "Unknown 1-byte regclass");
3069  if (STI.is64Bit())
3070  // Copying to or from a physical H register on x86-64 requires a NOREX
3071  // move. Otherwise use a normal move.
3072  if (isHReg(Reg) || X86::GR8_ABCD_HRegClass.hasSubClassEq(RC))
3073  return load ? X86::MOV8rm_NOREX : X86::MOV8mr_NOREX;
3074  return load ? X86::MOV8rm : X86::MOV8mr;
3075  case 2:
3076  if (X86::VK16RegClass.hasSubClassEq(RC))
3077  return load ? X86::KMOVWkm : X86::KMOVWmk;
3078  assert(X86::GR16RegClass.hasSubClassEq(RC) && "Unknown 2-byte regclass");
3079  return load ? X86::MOV16rm : X86::MOV16mr;
3080  case 4:
3081  if (X86::GR32RegClass.hasSubClassEq(RC))
3082  return load ? X86::MOV32rm : X86::MOV32mr;
3083  if (X86::FR32XRegClass.hasSubClassEq(RC))
3084  return load ?
3085  (HasAVX512 ? X86::VMOVSSZrm_alt :
3086  HasAVX ? X86::VMOVSSrm_alt :
3087  X86::MOVSSrm_alt) :
3088  (HasAVX512 ? X86::VMOVSSZmr :
3089  HasAVX ? X86::VMOVSSmr :
3090  X86::MOVSSmr);
3091  if (X86::RFP32RegClass.hasSubClassEq(RC))
3092  return load ? X86::LD_Fp32m : X86::ST_Fp32m;
3093  if (X86::VK32RegClass.hasSubClassEq(RC)) {
3094  assert(STI.hasBWI() && "KMOVD requires BWI");
3095  return load ? X86::KMOVDkm : X86::KMOVDmk;
3096  }
3097  // All of these mask pair classes have the same spill size, the same kind
3098  // of kmov instructions can be used with all of them.
3099  if (X86::VK1PAIRRegClass.hasSubClassEq(RC) ||
3100  X86::VK2PAIRRegClass.hasSubClassEq(RC) ||
3101  X86::VK4PAIRRegClass.hasSubClassEq(RC) ||
3102  X86::VK8PAIRRegClass.hasSubClassEq(RC) ||
3103  X86::VK16PAIRRegClass.hasSubClassEq(RC))
3104  return load ? X86::MASKPAIR16LOAD : X86::MASKPAIR16STORE;
3105  llvm_unreachable("Unknown 4-byte regclass");
3106  case 8:
3107  if (X86::GR64RegClass.hasSubClassEq(RC))
3108  return load ? X86::MOV64rm : X86::MOV64mr;
3109  if (X86::FR64XRegClass.hasSubClassEq(RC))
3110  return load ?
3111  (HasAVX512 ? X86::VMOVSDZrm_alt :
3112  HasAVX ? X86::VMOVSDrm_alt :
3113  X86::MOVSDrm_alt) :
3114  (HasAVX512 ? X86::VMOVSDZmr :
3115  HasAVX ? X86::VMOVSDmr :
3116  X86::MOVSDmr);
3117  if (X86::VR64RegClass.hasSubClassEq(RC))
3118  return load ? X86::MMX_MOVQ64rm : X86::MMX_MOVQ64mr;
3119  if (X86::RFP64RegClass.hasSubClassEq(RC))
3120  return load ? X86::LD_Fp64m : X86::ST_Fp64m;
3121  if (X86::VK64RegClass.hasSubClassEq(RC)) {
3122  assert(STI.hasBWI() && "KMOVQ requires BWI");
3123  return load ? X86::KMOVQkm : X86::KMOVQmk;
3124  }
3125  llvm_unreachable("Unknown 8-byte regclass");
3126  case 10:
3127  assert(X86::RFP80RegClass.hasSubClassEq(RC) && "Unknown 10-byte regclass");
3128  return load ? X86::LD_Fp80m : X86::ST_FpP80m;
3129  case 16: {
3130  if (X86::VR128XRegClass.hasSubClassEq(RC)) {
3131  // If stack is realigned we can use aligned stores.
3132  if (isStackAligned)
3133  return load ?
3134  (HasVLX ? X86::VMOVAPSZ128rm :
3135  HasAVX512 ? X86::VMOVAPSZ128rm_NOVLX :
3136  HasAVX ? X86::VMOVAPSrm :
3137  X86::MOVAPSrm):
3138  (HasVLX ? X86::VMOVAPSZ128mr :
3139  HasAVX512 ? X86::VMOVAPSZ128mr_NOVLX :
3140  HasAVX ? X86::VMOVAPSmr :
3141  X86::MOVAPSmr);
3142  else
3143  return load ?
3144  (HasVLX ? X86::VMOVUPSZ128rm :
3145  HasAVX512 ? X86::VMOVUPSZ128rm_NOVLX :
3146  HasAVX ? X86::VMOVUPSrm :
3147  X86::MOVUPSrm):
3148  (HasVLX ? X86::VMOVUPSZ128mr :
3149  HasAVX512 ? X86::VMOVUPSZ128mr_NOVLX :
3150  HasAVX ? X86::VMOVUPSmr :
3151  X86::MOVUPSmr);
3152  }
3153  if (X86::BNDRRegClass.hasSubClassEq(RC)) {
3154  if (STI.is64Bit())
3155  return load ? X86::BNDMOV64rm : X86::BNDMOV64mr;
3156  else
3157  return load ? X86::BNDMOV32rm : X86::BNDMOV32mr;
3158  }
3159  llvm_unreachable("Unknown 16-byte regclass");
3160  }
3161  case 32:
3162  assert(X86::VR256XRegClass.hasSubClassEq(RC) && "Unknown 32-byte regclass");
3163  // If stack is realigned we can use aligned stores.
3164  if (isStackAligned)
3165  return load ?
3166  (HasVLX ? X86::VMOVAPSZ256rm :
3167  HasAVX512 ? X86::VMOVAPSZ256rm_NOVLX :
3168  X86::VMOVAPSYrm) :
3169  (HasVLX ? X86::VMOVAPSZ256mr :
3170  HasAVX512 ? X86::VMOVAPSZ256mr_NOVLX :
3171  X86::VMOVAPSYmr);
3172  else
3173  return load ?
3174  (HasVLX ? X86::VMOVUPSZ256rm :
3175  HasAVX512 ? X86::VMOVUPSZ256rm_NOVLX :
3176  X86::VMOVUPSYrm) :
3177  (HasVLX ? X86::VMOVUPSZ256mr :
3178  HasAVX512 ? X86::VMOVUPSZ256mr_NOVLX :
3179  X86::VMOVUPSYmr);
3180  case 64:
3181  assert(X86::VR512RegClass.hasSubClassEq(RC) && "Unknown 64-byte regclass");
3182  assert(STI.hasAVX512() && "Using 512-bit register requires AVX512");
3183  if (isStackAligned)
3184  return load ? X86::VMOVAPSZrm : X86::VMOVAPSZmr;
3185  else
3186  return load ? X86::VMOVUPSZrm : X86::VMOVUPSZmr;
3187  }
3188 }
3189 
3191  const MachineInstr &MemOp, const MachineOperand *&BaseOp, int64_t &Offset,
3192  const TargetRegisterInfo *TRI) const {
3193  const MCInstrDesc &Desc = MemOp.getDesc();
3194  int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
3195  if (MemRefBegin < 0)
3196  return false;
3197 
3198  MemRefBegin += X86II::getOperandBias(Desc);
3199 
3200  BaseOp = &MemOp.getOperand(MemRefBegin + X86::AddrBaseReg);
3201  if (!BaseOp->isReg()) // Can be an MO_FrameIndex
3202  return false;
3203 
3204  if (MemOp.getOperand(MemRefBegin + X86::AddrScaleAmt).getImm() != 1)
3205  return false;
3206 
3207  if (MemOp.getOperand(MemRefBegin + X86::AddrIndexReg).getReg() !=
3208  X86::NoRegister)
3209  return false;
3210 
3211  const MachineOperand &DispMO = MemOp.getOperand(MemRefBegin + X86::AddrDisp);
3212 
3213  // Displacement can be symbolic
3214  if (!DispMO.isImm())
3215  return false;
3216 
3217  Offset = DispMO.getImm();
3218 
3219  assert(BaseOp->isReg() && "getMemOperandWithOffset only supports base "
3220  "operands of type register.");
3221  return true;
3222 }
3223 
3224 static unsigned getStoreRegOpcode(unsigned SrcReg,
3225  const TargetRegisterClass *RC,
3226  bool isStackAligned,
3227  const X86Subtarget &STI) {
3228  return getLoadStoreRegOpcode(SrcReg, RC, isStackAligned, STI, false);
3229 }
3230 
3231 
3232 static unsigned getLoadRegOpcode(unsigned DestReg,
3233  const TargetRegisterClass *RC,
3234  bool isStackAligned,
3235  const X86Subtarget &STI) {
3236  return getLoadStoreRegOpcode(DestReg, RC, isStackAligned, STI, true);
3237 }
3238 
3241  unsigned SrcReg, bool isKill, int FrameIdx,
3242  const TargetRegisterClass *RC,
3243  const TargetRegisterInfo *TRI) const {
3244  const MachineFunction &MF = *MBB.getParent();
3245  assert(MF.getFrameInfo().getObjectSize(FrameIdx) >= TRI->getSpillSize(*RC) &&
3246  "Stack slot too small for store");
3247  unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
3248  bool isAligned =
3249  (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
3250  RI.canRealignStack(MF);
3251  unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
3252  addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc)), FrameIdx)
3253  .addReg(SrcReg, getKillRegState(isKill));
3254 }
3255 
3258  unsigned DestReg, int FrameIdx,
3259  const TargetRegisterClass *RC,
3260  const TargetRegisterInfo *TRI) const {
3261  const MachineFunction &MF = *MBB.getParent();
3262  unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
3263  bool isAligned =
3264  (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
3265  RI.canRealignStack(MF);
3266  unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
3267  addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc), DestReg), FrameIdx);
3268 }
3269 
3270 bool X86InstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
3271  unsigned &SrcReg2, int &CmpMask,
3272  int &CmpValue) const {
3273  switch (MI.getOpcode()) {
3274  default: break;
3275  case X86::CMP64ri32:
3276  case X86::CMP64ri8:
3277  case X86::CMP32ri:
3278  case X86::CMP32ri8:
3279  case X86::CMP16ri:
3280  case X86::CMP16ri8:
3281  case X86::CMP8ri:
3282  SrcReg = MI.getOperand(0).getReg();
3283  SrcReg2 = 0;
3284  if (MI.getOperand(1).isImm()) {
3285  CmpMask = ~0;
3286  CmpValue = MI.getOperand(1).getImm();
3287  } else {
3288  CmpMask = CmpValue = 0;
3289  }
3290  return true;
3291  // A SUB can be used to perform comparison.
3292  case X86::SUB64rm:
3293  case X86::SUB32rm:
3294  case X86::SUB16rm:
3295  case X86::SUB8rm:
3296  SrcReg = MI.getOperand(1).getReg();
3297  SrcReg2 = 0;
3298  CmpMask = 0;
3299  CmpValue = 0;
3300  return true;
3301  case X86::SUB64rr:
3302  case X86::SUB32rr:
3303  case X86::SUB16rr:
3304  case X86::SUB8rr:
3305  SrcReg = MI.getOperand(1).getReg();
3306  SrcReg2 = MI.getOperand(2).getReg();
3307  CmpMask = 0;
3308  CmpValue = 0;
3309  return true;
3310  case X86::SUB64ri32:
3311  case X86::SUB64ri8:
3312  case X86::SUB32ri:
3313  case X86::SUB32ri8:
3314  case X86::SUB16ri:
3315  case X86::SUB16ri8:
3316  case X86::SUB8ri:
3317  SrcReg = MI.getOperand(1).getReg();
3318  SrcReg2 = 0;
3319  if (MI.getOperand(2).isImm()) {
3320  CmpMask = ~0;
3321  CmpValue = MI.getOperand(2).getImm();
3322  } else {
3323  CmpMask = CmpValue = 0;
3324  }
3325  return true;
3326  case X86::CMP64rr:
3327  case X86::CMP32rr:
3328  case X86::CMP16rr:
3329  case X86::CMP8rr:
3330  SrcReg = MI.getOperand(0).getReg();
3331  SrcReg2 = MI.getOperand(1).getReg();
3332  CmpMask = 0;
3333  CmpValue = 0;
3334  return true;
3335  case X86::TEST8rr:
3336  case X86::TEST16rr:
3337  case X86::TEST32rr:
3338  case X86::TEST64rr:
3339  SrcReg = MI.getOperand(0).getReg();
3340  if (MI.getOperand(1).getReg() != SrcReg)
3341  return false;
3342  // Compare against zero.
3343  SrcReg2 = 0;
3344  CmpMask = ~0;
3345  CmpValue = 0;
3346  return true;
3347  }
3348  return false;
3349 }
3350 
3351 /// Check whether the first instruction, whose only
3352 /// purpose is to update flags, can be made redundant.
3353 /// CMPrr can be made redundant by SUBrr if the operands are the same.
3354 /// This function can be extended later on.
3355 /// SrcReg, SrcRegs: register operands for FlagI.
3356 /// ImmValue: immediate for FlagI if it takes an immediate.
3357 inline static bool isRedundantFlagInstr(const MachineInstr &FlagI,
3358  unsigned SrcReg, unsigned SrcReg2,
3359  int ImmMask, int ImmValue,
3360  const MachineInstr &OI) {
3361  if (((FlagI.getOpcode() == X86::CMP64rr && OI.getOpcode() == X86::SUB64rr) ||
3362  (FlagI.getOpcode() == X86::CMP32rr && OI.getOpcode() == X86::SUB32rr) ||
3363  (FlagI.getOpcode() == X86::CMP16rr && OI.getOpcode() == X86::SUB16rr) ||
3364  (FlagI.getOpcode() == X86::CMP8rr && OI.getOpcode() == X86::SUB8rr)) &&
3365  ((OI.getOperand(1).getReg() == SrcReg &&
3366  OI.getOperand(2).getReg() == SrcReg2) ||
3367  (OI.getOperand(1).getReg() == SrcReg2 &&
3368  OI.getOperand(2).getReg() == SrcReg)))
3369  return true;
3370 
3371  if (ImmMask != 0 &&
3372  ((FlagI.getOpcode() == X86::CMP64ri32 &&
3373  OI.getOpcode() == X86::SUB64ri32) ||
3374  (FlagI.getOpcode() == X86::CMP64ri8 &&
3375  OI.getOpcode() == X86::SUB64ri8) ||
3376  (FlagI.getOpcode() == X86::CMP32ri && OI.getOpcode() == X86::SUB32ri) ||
3377  (FlagI.getOpcode() == X86::CMP32ri8 &&
3378  OI.getOpcode() == X86::SUB32ri8) ||
3379  (FlagI.getOpcode() == X86::CMP16ri && OI.getOpcode() == X86::SUB16ri) ||
3380  (FlagI.getOpcode() == X86::CMP16ri8 &&
3381  OI.getOpcode() == X86::SUB16ri8) ||
3382  (FlagI.getOpcode() == X86::CMP8ri && OI.getOpcode() == X86::SUB8ri)) &&
3383  OI.getOperand(1).getReg() == SrcReg &&
3384  OI.getOperand(2).getImm() == ImmValue)
3385  return true;
3386  return false;
3387 }
3388 
3389 /// Check whether the definition can be converted
3390 /// to remove a comparison against zero.
3391 inline static bool isDefConvertible(const MachineInstr &MI, bool &NoSignFlag) {
3392  NoSignFlag = false;
3393 
3394  switch (MI.getOpcode()) {
3395  default: return false;
3396 
3397  // The shift instructions only modify ZF if their shift count is non-zero.
3398  // N.B.: The processor truncates the shift count depending on the encoding.
3399  case X86::SAR8ri: case X86::SAR16ri: case X86::SAR32ri:case X86::SAR64ri:
3400  case X86::SHR8ri: case X86::SHR16ri: case X86::SHR32ri:case X86::SHR64ri:
3401  return getTruncatedShiftCount(MI, 2) != 0;
3402 
3403  // Some left shift instructions can be turned into LEA instructions but only
3404  // if their flags aren't used. Avoid transforming such instructions.
3405  case X86::SHL8ri: case X86::SHL16ri: case X86::SHL32ri:case X86::SHL64ri:{
3406  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
3407  if (isTruncatedShiftCountForLEA(ShAmt)) return false;
3408  return ShAmt != 0;
3409  }
3410 
3411  case X86::SHRD16rri8:case X86::SHRD32rri8:case X86::SHRD64rri8:
3412  case X86::SHLD16rri8:case X86::SHLD32rri8:case X86::SHLD64rri8:
3413  return getTruncatedShiftCount(MI, 3) != 0;
3414 
3415  case X86::SUB64ri32: case X86::SUB64ri8: case X86::SUB32ri:
3416  case X86::SUB32ri8: case X86::SUB16ri: case X86::SUB16ri8:
3417  case X86::SUB8ri: case X86::SUB64rr: case X86::SUB32rr:
3418  case X86::SUB16rr: case X86::SUB8rr: case X86::SUB64rm:
3419  case X86::SUB32rm: case X86::SUB16rm: case X86::SUB8rm:
3420  case X86::DEC64r: case X86::DEC32r: case X86::DEC16r: case X86::DEC8r:
3421  case X86::ADD64ri32: case X86::ADD64ri8: case X86::ADD32ri:
3422  case X86::ADD32ri8: case X86::ADD16ri: case X86::ADD16ri8:
3423  case X86::ADD8ri: case X86::ADD64rr: case X86::ADD32rr:
3424  case X86::ADD16rr: case X86::ADD8rr: case X86::ADD64rm:
3425  case X86::ADD32rm: case X86::ADD16rm: case X86::ADD8rm:
3426  case X86::INC64r: case X86::INC32r: case X86::INC16r: case X86::INC8r:
3427  case X86::AND64ri32: case X86::AND64ri8: case X86::AND32ri:
3428  case X86::AND32ri8: case X86::AND16ri: case X86::AND16ri8:
3429  case X86::AND8ri: case X86::AND64rr: case X86::AND32rr:
3430  case X86::AND16rr: case X86::AND8rr: case X86::AND64rm:
3431  case X86::AND32rm: case X86::AND16rm: case X86::AND8rm:
3432  case X86::XOR64ri32: case X86::XOR64ri8: case X86::XOR32ri:
3433  case X86::XOR32ri8: case X86::XOR16ri: case X86::XOR16ri8:
3434  case X86::XOR8ri: case X86::XOR64rr: case X86::XOR32rr:
3435  case X86::XOR16rr: case X86::XOR8rr: case X86::XOR64rm:
3436  case X86::XOR32rm: case X86::XOR16rm: case X86::XOR8rm:
3437  case X86::OR64ri32: case X86::OR64ri8: case X86::OR32ri:
3438  case X86::OR32ri8: case X86::OR16ri: case X86::OR16ri8:
3439  case X86::OR8ri: case X86::OR64rr: case X86::OR32rr:
3440  case X86::OR16rr: case X86::OR8rr: case X86::OR64rm:
3441  case X86::OR32rm: case X86::OR16rm: case X86::OR8rm:
3442  case X86::ADC64ri32: case X86::ADC64ri8: case X86::ADC32ri:
3443  case X86::ADC32ri8: case X86::ADC16ri: case X86::ADC16ri8:
3444  case X86::ADC8ri: case X86::ADC64rr: case X86::ADC32rr:
3445  case X86::ADC16rr: case X86::ADC8rr: case X86::ADC64rm:
3446  case X86::ADC32rm: case X86::ADC16rm: case X86::ADC8rm:
3447  case X86::SBB64ri32: case X86::SBB64ri8: case X86::SBB32ri:
3448  case X86::SBB32ri8: case X86::SBB16ri: case X86::SBB16ri8:
3449  case X86::SBB8ri: case X86::SBB64rr: case X86::SBB32rr:
3450  case X86::SBB16rr: case X86::SBB8rr: case X86::SBB64rm:
3451  case X86::SBB32rm: case X86::SBB16rm: case X86::SBB8rm:
3452  case X86::NEG8r: case X86::NEG16r: case X86::NEG32r: case X86::NEG64r:
3453  case X86::SAR8r1: case X86::SAR16r1: case X86::SAR32r1:case X86::SAR64r1:
3454  case X86::SHR8r1: case X86::SHR16r1: case X86::SHR32r1:case X86::SHR64r1:
3455  case X86::SHL8r1: case X86::SHL16r1: case X86::SHL32r1:case X86::SHL64r1:
3456  case X86::ANDN32rr: case X86::ANDN32rm:
3457  case X86::ANDN64rr: case X86::ANDN64rm:
3458  case X86::BLSI32rr: case X86::BLSI32rm:
3459  case X86::BLSI64rr: case X86::BLSI64rm:
3460  case X86::BLSMSK32rr:case X86::BLSMSK32rm:
3461  case X86::BLSMSK64rr:case X86::BLSMSK64rm:
3462  case X86::BLSR32rr: case X86::BLSR32rm:
3463  case X86::BLSR64rr: case X86::BLSR64rm:
3464  case X86::BZHI32rr: case X86::BZHI32rm:
3465  case X86::BZHI64rr: case X86::BZHI64rm:
3466  case X86::LZCNT16rr: case X86::LZCNT16rm:
3467  case X86::LZCNT32rr: case X86::LZCNT32rm:
3468  case X86::LZCNT64rr: case X86::LZCNT64rm:
3469  case X86::POPCNT16rr:case X86::POPCNT16rm:
3470  case X86::POPCNT32rr:case X86::POPCNT32rm:
3471  case X86::POPCNT64rr:case X86::POPCNT64rm:
3472  case X86::TZCNT16rr: case X86::TZCNT16rm:
3473  case X86::TZCNT32rr: case X86::TZCNT32rm:
3474  case X86::TZCNT64rr: case X86::TZCNT64rm:
3475  case X86::BLCFILL32rr: case X86::BLCFILL32rm:
3476  case X86::BLCFILL64rr: case X86::BLCFILL64rm:
3477  case X86::BLCI32rr: case X86::BLCI32rm:
3478  case X86::BLCI64rr: case X86::BLCI64rm:
3479  case X86::BLCIC32rr: case X86::BLCIC32rm:
3480  case X86::BLCIC64rr: case X86::BLCIC64rm:
3481  case X86::BLCMSK32rr: case X86::BLCMSK32rm:
3482  case X86::BLCMSK64rr: case X86::BLCMSK64rm:
3483  case X86::BLCS32rr: case X86::BLCS32rm:
3484  case X86::BLCS64rr: case X86::BLCS64rm:
3485  case X86::BLSFILL32rr: case X86::BLSFILL32rm:
3486  case X86::BLSFILL64rr: case X86::BLSFILL64rm:
3487  case X86::BLSIC32rr: case X86::BLSIC32rm:
3488  case X86::BLSIC64rr: case X86::BLSIC64rm:
3489  case X86::T1MSKC32rr: case X86::T1MSKC32rm:
3490  case X86::T1MSKC64rr: case X86::T1MSKC64rm:
3491  case X86::TZMSK32rr: case X86::TZMSK32rm:
3492  case X86::TZMSK64rr: case X86::TZMSK64rm:
3493  return true;
3494  case X86::BEXTR32rr: case X86::BEXTR64rr:
3495  case X86::BEXTR32rm: case X86::BEXTR64rm:
3496  case X86::BEXTRI32ri: case X86::BEXTRI32mi:
3497  case X86::BEXTRI64ri: case X86::BEXTRI64mi:
3498  // BEXTR doesn't update the sign flag so we can't use it.
3499  NoSignFlag = true;
3500  return true;
3501  }
3502 }
3503 
3504 /// Check whether the use can be converted to remove a comparison against zero.
3506  switch (MI.getOpcode()) {
3507  default: return X86::COND_INVALID;
3508  case X86::NEG8r:
3509  case X86::NEG16r:
3510  case X86::NEG32r:
3511  case X86::NEG64r:
3512  return X86::COND_AE;
3513  case X86::LZCNT16rr:
3514  case X86::LZCNT32rr:
3515  case X86::LZCNT64rr:
3516  return X86::COND_B;
3517  case X86::POPCNT16rr:
3518  case X86::POPCNT32rr:
3519  case X86::POPCNT64rr:
3520  return X86::COND_E;
3521  case X86::TZCNT16rr:
3522  case X86::TZCNT32rr:
3523  case X86::TZCNT64rr:
3524  return X86::COND_B;
3525  case X86::BSF16rr:
3526  case X86::BSF32rr:
3527  case X86::BSF64rr:
3528  case X86::BSR16rr:
3529  case X86::BSR32rr:
3530  case X86::BSR64rr:
3531  return X86::COND_E;
3532  case X86::BLSI32rr:
3533  case X86::BLSI64rr:
3534  return X86::COND_AE;
3535  case X86::BLSR32rr:
3536  case X86::BLSR64rr:
3537  case X86::BLSMSK32rr:
3538  case X86::BLSMSK64rr:
3539  return X86::COND_B;
3540  // TODO: TBM instructions.
3541  }
3542 }
3543 
3544 /// Check if there exists an earlier instruction that
3545 /// operates on the same source operands and sets flags in the same way as
3546 /// Compare; remove Compare if possible.
3547 bool X86InstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
3548  unsigned SrcReg2, int CmpMask,
3549  int CmpValue,
3550  const MachineRegisterInfo *MRI) const {
3551  // Check whether we can replace SUB with CMP.
3552  switch (CmpInstr.getOpcode()) {
3553  default: break;
3554  case X86::SUB64ri32:
3555  case X86::SUB64ri8:
3556  case X86::SUB32ri:
3557  case X86::SUB32ri8:
3558  case X86::SUB16ri:
3559  case X86::SUB16ri8:
3560  case X86::SUB8ri:
3561  case X86::SUB64rm:
3562  case X86::SUB32rm:
3563  case X86::SUB16rm:
3564  case X86::SUB8rm:
3565  case X86::SUB64rr:
3566  case X86::SUB32rr:
3567  case X86::SUB16rr:
3568  case X86::SUB8rr: {
3569  if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
3570  return false;
3571  // There is no use of the destination register, we can replace SUB with CMP.
3572  unsigned NewOpcode = 0;
3573  switch (CmpInstr.getOpcode()) {
3574  default: llvm_unreachable("Unreachable!");
3575  case X86::SUB64rm: NewOpcode = X86::CMP64rm; break;
3576  case X86::SUB32rm: NewOpcode = X86::CMP32rm; break;
3577  case X86::SUB16rm: NewOpcode = X86::CMP16rm; break;
3578  case X86::SUB8rm: NewOpcode = X86::CMP8rm; break;
3579  case X86::SUB64rr: NewOpcode = X86::CMP64rr; break;
3580  case X86::SUB32rr: NewOpcode = X86::CMP32rr; break;
3581  case X86::SUB16rr: NewOpcode = X86::CMP16rr; break;
3582  case X86::SUB8rr: NewOpcode = X86::CMP8rr; break;
3583  case X86::SUB64ri32: NewOpcode = X86::CMP64ri32; break;
3584  case X86::SUB64ri8: NewOpcode = X86::CMP64ri8; break;
3585  case X86::SUB32ri: NewOpcode = X86::CMP32ri; break;
3586  case X86::SUB32ri8: NewOpcode = X86::CMP32ri8; break;
3587  case X86::SUB16ri: NewOpcode = X86::CMP16ri; break;
3588  case X86::SUB16ri8: NewOpcode = X86::CMP16ri8; break;
3589  case X86::SUB8ri: NewOpcode = X86::CMP8ri; break;
3590  }
3591  CmpInstr.setDesc(get(NewOpcode));
3592  CmpInstr.RemoveOperand(0);
3593  // Fall through to optimize Cmp if Cmp is CMPrr or CMPri.
3594  if (NewOpcode == X86::CMP64rm || NewOpcode == X86::CMP32rm ||
3595  NewOpcode == X86::CMP16rm || NewOpcode == X86::CMP8rm)
3596  return false;
3597  }
3598  }
3599 
3600  // Get the unique definition of SrcReg.
3601  MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
3602  if (!MI) return false;
3603 
3604  // CmpInstr is the first instruction of the BB.
3605  MachineBasicBlock::iterator I = CmpInstr, Def = MI;
3606 
3607  // If we are comparing against zero, check whether we can use MI to update
3608  // EFLAGS. If MI is not in the same BB as CmpInstr, do not optimize.
3609  bool IsCmpZero = (CmpMask != 0 && CmpValue == 0);
3610  if (IsCmpZero && MI->getParent() != CmpInstr.getParent())
3611  return false;
3612 
3613  // If we have a use of the source register between the def and our compare
3614  // instruction we can eliminate the compare iff the use sets EFLAGS in the
3615  // right way.
3616  bool ShouldUpdateCC = false;
3617  bool NoSignFlag = false;
3619  if (IsCmpZero && !isDefConvertible(*MI, NoSignFlag)) {
3620  // Scan forward from the use until we hit the use we're looking for or the
3621  // compare instruction.
3622  for (MachineBasicBlock::iterator J = MI;; ++J) {
3623  // Do we have a convertible instruction?
3624  NewCC = isUseDefConvertible(*J);
3625  if (NewCC != X86::COND_INVALID && J->getOperand(1).isReg() &&
3626  J->getOperand(1).getReg() == SrcReg) {
3627  assert(J->definesRegister(X86::EFLAGS) && "Must be an EFLAGS def!");
3628  ShouldUpdateCC = true; // Update CC later on.
3629  // This is not a def of SrcReg, but still a def of EFLAGS. Keep going
3630  // with the new def.
3631  Def = J;
3632  MI = &*Def;
3633  break;
3634  }
3635 
3636  if (J == I)
3637  return false;
3638  }
3639  }
3640 
3641  // We are searching for an earlier instruction that can make CmpInstr
3642  // redundant and that instruction will be saved in Sub.
3643  MachineInstr *Sub = nullptr;
3645 
3646  // We iterate backward, starting from the instruction before CmpInstr and
3647  // stop when reaching the definition of a source register or done with the BB.
3648  // RI points to the instruction before CmpInstr.
3649  // If the definition is in this basic block, RE points to the definition;
3650  // otherwise, RE is the rend of the basic block.
3652  RI = ++I.getReverse(),
3653  RE = CmpInstr.getParent() == MI->getParent()
3654  ? Def.getReverse() /* points to MI */
3655  : CmpInstr.getParent()->rend();
3656  MachineInstr *Movr0Inst = nullptr;
3657  for (; RI != RE; ++RI) {
3658  MachineInstr &Instr = *RI;
3659  // Check whether CmpInstr can be made redundant by the current instruction.
3660  if (!IsCmpZero && isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpMask,
3661  CmpValue, Instr)) {
3662  Sub = &Instr;
3663  break;
3664  }
3665 
3666  if (Instr.modifiesRegister(X86::EFLAGS, TRI) ||
3667  Instr.readsRegister(X86::EFLAGS, TRI)) {
3668  // This instruction modifies or uses EFLAGS.
3669 
3670  // MOV32r0 etc. are implemented with xor which clobbers condition code.
3671  // They are safe to move up, if the definition to EFLAGS is dead and
3672  // earlier instructions do not read or write EFLAGS.
3673  if (!Movr0Inst && Instr.getOpcode() == X86::MOV32r0 &&
3674  Instr.registerDefIsDead(X86::EFLAGS, TRI)) {
3675  Movr0Inst = &Instr;
3676  continue;
3677  }
3678 
3679  // We can't remove CmpInstr.
3680  return false;
3681  }
3682  }
3683 
3684  // Return false if no candidates exist.
3685  if (!IsCmpZero && !Sub)
3686  return false;
3687 
3688  bool IsSwapped =
3689  (SrcReg2 != 0 && Sub && Sub->getOperand(1).getReg() == SrcReg2 &&
3690  Sub->getOperand(2).getReg() == SrcReg);
3691 
3692  // Scan forward from the instruction after CmpInstr for uses of EFLAGS.
3693  // It is safe to remove CmpInstr if EFLAGS is redefined or killed.
3694  // If we are done with the basic block, we need to check whether EFLAGS is
3695  // live-out.
3696  bool IsSafe = false;
3698  MachineBasicBlock::iterator E = CmpInstr.getParent()->end();
3699  for (++I; I != E; ++I) {
3700  const MachineInstr &Instr = *I;
3701  bool ModifyEFLAGS = Instr.modifiesRegister(X86::EFLAGS, TRI);
3702  bool UseEFLAGS = Instr.readsRegister(X86::EFLAGS, TRI);
3703  // We should check the usage if this instruction uses and updates EFLAGS.
3704  if (!UseEFLAGS && ModifyEFLAGS) {
3705  // It is safe to remove CmpInstr if EFLAGS is updated again.
3706  IsSafe = true;
3707  break;
3708  }
3709  if (!UseEFLAGS && !ModifyEFLAGS)
3710  continue;
3711 
3712  // EFLAGS is used by this instruction.
3714  if (IsCmpZero || IsSwapped) {
3715  // We decode the condition code from opcode.
3716  if (Instr.isBranch())
3717  OldCC = X86::getCondFromBranch(Instr);
3718  else {
3719  OldCC = X86::getCondFromSETCC(Instr);
3720  if (OldCC == X86::COND_INVALID)
3721  OldCC = X86::getCondFromCMov(Instr);
3722  }
3723  if (OldCC == X86::COND_INVALID) return false;
3724  }
3725  X86::CondCode ReplacementCC = X86::COND_INVALID;
3726  if (IsCmpZero) {
3727  switch (OldCC) {
3728  default: break;
3729  case X86::COND_A: case X86::COND_AE:
3730  case X86::COND_B: case X86::COND_BE:
3731  case X86::COND_G: case X86::COND_GE:
3732  case X86::COND_L: case X86::COND_LE:
3733  case X86::COND_O: case X86::COND_NO:
3734  // CF and OF are used, we can't perform this optimization.
3735  return false;
3736  case X86::COND_S: case X86::COND_NS:
3737  // If SF is used, but the instruction doesn't update the SF, then we
3738  // can't do the optimization.
3739  if (NoSignFlag)
3740  return false;
3741  break;
3742  }
3743 
3744  // If we're updating the condition code check if we have to reverse the
3745  // condition.
3746  if (ShouldUpdateCC)
3747  switch (OldCC) {
3748  default:
3749  return false;
3750  case X86::COND_E:
3751  ReplacementCC = NewCC;
3752  break;
3753  case X86::COND_NE:
3754  ReplacementCC = GetOppositeBranchCondition(NewCC);
3755  break;
3756  }
3757  } else if (IsSwapped) {
3758  // If we have SUB(r1, r2) and CMP(r2, r1), the condition code needs
3759  // to be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3760  // We swap the condition code and synthesize the new opcode.
3761  ReplacementCC = getSwappedCondition(OldCC);
3762  if (ReplacementCC == X86::COND_INVALID) return false;
3763  }
3764 
3765  if ((ShouldUpdateCC || IsSwapped) && ReplacementCC != OldCC) {
3766  // Push the MachineInstr to OpsToUpdate.
3767  // If it is safe to remove CmpInstr, the condition code of these
3768  // instructions will be modified.
3769  OpsToUpdate.push_back(std::make_pair(&*I, ReplacementCC));
3770  }
3771  if (ModifyEFLAGS || Instr.killsRegister(X86::EFLAGS, TRI)) {
3772  // It is safe to remove CmpInstr if EFLAGS is updated again or killed.
3773  IsSafe = true;
3774  break;
3775  }
3776  }
3777 
3778  // If EFLAGS is not killed nor re-defined, we should check whether it is
3779  // live-out. If it is live-out, do not optimize.
3780  if ((IsCmpZero || IsSwapped) && !IsSafe) {
3781  MachineBasicBlock *MBB = CmpInstr.getParent();
3782  for (MachineBasicBlock *Successor : MBB->successors())
3783  if (Successor->isLiveIn(X86::EFLAGS))
3784  return false;
3785  }
3786 
3787  // The instruction to be updated is either Sub or MI.
3788  Sub = IsCmpZero ? MI : Sub;
3789  // Move Movr0Inst to the appropriate place before Sub.
3790  if (Movr0Inst) {
3791  // Look backwards until we find a def that doesn't use the current EFLAGS.
3792  Def = Sub;
3794  InsertE = Sub->getParent()->rend();
3795  for (; InsertI != InsertE; ++InsertI) {
3796  MachineInstr *Instr = &*InsertI;
3797  if (!Instr->readsRegister(X86::EFLAGS, TRI) &&
3798  Instr->modifiesRegister(X86::EFLAGS, TRI)) {
3799  Sub->getParent()->remove(Movr0Inst);
3800  Instr->getParent()->insert(MachineBasicBlock::iterator(Instr),
3801  Movr0Inst);
3802  break;
3803  }
3804  }
3805  if (InsertI == InsertE)
3806  return false;
3807  }
3808 
3809  // Make sure Sub instruction defines EFLAGS and mark the def live.
3810  MachineOperand *FlagDef = Sub->findRegisterDefOperand(X86::EFLAGS);
3811  assert(FlagDef && "Unable to locate a def EFLAGS operand");
3812  FlagDef->setIsDead(false);
3813 
3814  CmpInstr.eraseFromParent();
3815 
3816  // Modify the condition code of instructions in OpsToUpdate.
3817  for (auto &Op : OpsToUpdate) {
3818  Op.first->getOperand(Op.first->getDesc().getNumOperands() - 1)
3819  .setImm(Op.second);
3820  }
3821  return true;
3822 }
3823 
3824 /// Try to remove the load by folding it to a register
3825 /// operand at the use. We fold the load instructions if load defines a virtual
3826 /// register, the virtual register is used once in the same BB, and the
3827 /// instructions in-between do not load or store, and have no side effects.
3829  const MachineRegisterInfo *MRI,
3830  unsigned &FoldAsLoadDefReg,
3831  MachineInstr *&DefMI) const {
3832  // Check whether we can move DefMI here.
3833  DefMI = MRI->getVRegDef(FoldAsLoadDefReg);
3834  assert(DefMI);
3835  bool SawStore = false;
3836  if (!DefMI->isSafeToMove(nullptr, SawStore))
3837  return nullptr;
3838 
3839  // Collect information about virtual register operands of MI.
3840  SmallVector<unsigned, 1> SrcOperandIds;
3841  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3842  MachineOperand &MO = MI.getOperand(i);
3843  if (!MO.isReg())
3844  continue;
3845  Register Reg = MO.getReg();
3846  if (Reg != FoldAsLoadDefReg)
3847  continue;
3848  // Do not fold if we have a subreg use or a def.
3849  if (MO.getSubReg() || MO.isDef())
3850  return nullptr;
3851  SrcOperandIds.push_back(i);
3852  }
3853  if (SrcOperandIds.empty())
3854  return nullptr;
3855 
3856  // Check whether we can fold the def into SrcOperandId.
3857  if (MachineInstr *FoldMI = foldMemoryOperand(MI, SrcOperandIds, *DefMI)) {
3858  FoldAsLoadDefReg = 0;
3859  return FoldMI;
3860  }
3861 
3862  return nullptr;
3863 }
3864 
3865 /// Expand a single-def pseudo instruction to a two-addr
3866 /// instruction with two undef reads of the register being defined.
3867 /// This is used for mapping:
3868 /// %xmm4 = V_SET0
3869 /// to:
3870 /// %xmm4 = PXORrr undef %xmm4, undef %xmm4
3871 ///
3873  const MCInstrDesc &Desc) {
3874  assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
3875  Register Reg = MIB->getOperand(0).getReg();
3876  MIB->setDesc(Desc);
3877 
3878  // MachineInstr::addOperand() will insert explicit operands before any
3879  // implicit operands.
3880  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
3881  // But we don't trust that.
3882  assert(MIB->getOperand(1).getReg() == Reg &&
3883  MIB->getOperand(2).getReg() == Reg && "Misplaced operand");
3884  return true;
3885 }
3886 
3887 /// Expand a single-def pseudo instruction to a two-addr
3888 /// instruction with two %k0 reads.
3889 /// This is used for mapping:
3890 /// %k4 = K_SET1
3891 /// to:
3892 /// %k4 = KXNORrr %k0, %k0
3894  const MCInstrDesc &Desc, unsigned Reg) {
3895  assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
3896  MIB->setDesc(Desc);
3897  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
3898  return true;
3899 }
3900 
3902  bool MinusOne) {
3903  MachineBasicBlock &MBB = *MIB->getParent();
3904  DebugLoc DL = MIB->getDebugLoc();
3905  Register Reg = MIB->getOperand(0).getReg();
3906 
3907  // Insert the XOR.
3908  BuildMI(MBB, MIB.getInstr(), DL, TII.get(X86::XOR32rr), Reg)
3909  .addReg(Reg, RegState::Undef)
3910  .addReg(Reg, RegState::Undef);
3911 
3912  // Turn the pseudo into an INC or DEC.
3913  MIB->setDesc(TII.get(MinusOne ? X86::DEC32r : X86::INC32r));
3914  MIB.addReg(Reg);
3915 
3916  return true;
3917 }
3918 
3920  const TargetInstrInfo &TII,
3921  const X86Subtarget &Subtarget) {
3922  MachineBasicBlock &MBB = *MIB->getParent();
3923  DebugLoc DL = MIB->getDebugLoc();
3924  int64_t Imm = MIB->getOperand(1).getImm();
3925  assert(Imm != 0 && "Using push/pop for 0 is not efficient.");
3927 
3928  int StackAdjustment;
3929 
3930  if (Subtarget.is64Bit()) {
3931  assert(MIB->getOpcode() == X86::MOV64ImmSExti8 ||
3932  MIB->getOpcode() == X86::MOV32ImmSExti8);
3933 
3934  // Can't use push/pop lowering if the function might write to the red zone.
3935  X86MachineFunctionInfo *X86FI =
3937  if (X86FI->getUsesRedZone()) {
3938  MIB->setDesc(TII.get(MIB->getOpcode() ==
3939  X86::MOV32ImmSExti8 ? X86::MOV32ri : X86::MOV64ri));
3940  return true;
3941  }
3942 
3943  // 64-bit mode doesn't have 32-bit push/pop, so use 64-bit operations and
3944  // widen the register if necessary.
3945  StackAdjustment = 8;
3946  BuildMI(MBB, I, DL, TII.get(X86::PUSH64i8)).addImm(Imm);
3947  MIB->setDesc(TII.get(X86::POP64r));
3948  MIB->getOperand(0)
3950  } else {
3951  assert(MIB->getOpcode() == X86::MOV32ImmSExti8);
3952  StackAdjustment = 4;
3953  BuildMI(MBB, I, DL, TII.get(X86::PUSH32i8)).addImm(Imm);
3954  MIB->setDesc(TII.get(X86::POP32r));
3955  }
3956 
3957  // Build CFI if necessary.
3958  MachineFunction &MF = *MBB.getParent();
3959  const X86FrameLowering *TFL = Subtarget.getFrameLowering();
3960  bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
3961  bool NeedsDwarfCFI =
3962  !IsWin64Prologue &&
3964  bool EmitCFI = !TFL->hasFP(MF) && NeedsDwarfCFI;
3965  if (EmitCFI) {
3966  TFL->BuildCFI(MBB, I, DL,
3967  MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
3968  TFL->BuildCFI(MBB, std::next(I), DL,
3969  MCCFIInstruction::createAdjustCfaOffset(nullptr, -StackAdjustment));
3970  }
3971 
3972  return true;
3973 }
3974 
3975 // LoadStackGuard has so far only been implemented for 64-bit MachO. Different
3976 // code sequence is needed for other targets.
3978  const TargetInstrInfo &TII) {
3979  MachineBasicBlock &MBB = *MIB->getParent();
3980  DebugLoc DL = MIB->getDebugLoc();
3981  Register Reg = MIB->getOperand(0).getReg();
3982  const GlobalValue *GV =
3983  cast<GlobalValue>((*MIB->memoperands_begin())->getValue());
3984  auto Flags = MachineMemOperand::MOLoad |
3988  MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 8, 8);
3990 
3991  BuildMI(MBB, I, DL, TII.get(X86::MOV64rm), Reg).addReg(X86::RIP).addImm(1)
3993  .addMemOperand(MMO);
3994  MIB->setDebugLoc(DL);
3995  MIB->setDesc(TII.get(X86::MOV64rm));
3996  MIB.addReg(Reg, RegState::Kill).addImm(1).addReg(0).addImm(0).addReg(0);
3997 }
3998 
4000  MachineBasicBlock &MBB = *MIB->getParent();
4001  MachineFunction &MF = *MBB.getParent();
4002  const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
4003  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4004  unsigned XorOp =
4005  MIB->getOpcode() == X86::XOR64_FP ? X86::XOR64rr : X86::XOR32rr;
4006  MIB->setDesc(TII.get(XorOp));
4007  MIB.addReg(TRI->getFrameRegister(MF), RegState::Undef);
4008  return true;
4009 }
4010 
4011 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4012 // but not VLX. If it uses an extended register we need to use an instruction
4013 // that loads the lower 128/256-bit, but is available with only AVX512F.
4015  const TargetRegisterInfo *TRI,
4016  const MCInstrDesc &LoadDesc,
4017  const MCInstrDesc &BroadcastDesc,
4018  unsigned SubIdx) {
4019  Register DestReg = MIB->getOperand(0).getReg();
4020  // Check if DestReg is XMM16-31 or YMM16-31.
4021  if (TRI->getEncodingValue(DestReg) < 16) {
4022  // We can use a normal VEX encoded load.
4023  MIB->setDesc(LoadDesc);
4024  } else {
4025  // Use a 128/256-bit VBROADCAST instruction.
4026  MIB->setDesc(BroadcastDesc);
4027  // Change the destination to a 512-bit register.
4028  DestReg = TRI->getMatchingSuperReg(DestReg, SubIdx, &X86::VR512RegClass);
4029  MIB->getOperand(0).setReg(DestReg);
4030  }
4031  return true;
4032 }
4033 
4034 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4035 // but not VLX. If it uses an extended register we need to use an instruction
4036 // that stores the lower 128/256-bit, but is available with only AVX512F.
4038  const TargetRegisterInfo *TRI,
4039  const MCInstrDesc &StoreDesc,
4040  const MCInstrDesc &ExtractDesc,
4041  unsigned SubIdx) {
4043  // Check if DestReg is XMM16-31 or YMM16-31.
4044  if (TRI->getEncodingValue(SrcReg) < 16) {
4045  // We can use a normal VEX encoded store.
4046  MIB->setDesc(StoreDesc);
4047  } else {
4048  // Use a VEXTRACTF instruction.
4049  MIB->setDesc(ExtractDesc);
4050  // Change the destination to a 512-bit register.
4051  SrcReg = TRI->getMatchingSuperReg(SrcReg, SubIdx, &X86::VR512RegClass);
4052  MIB->getOperand(X86::AddrNumOperands).setReg(SrcReg);
4053  MIB.addImm(0x0); // Append immediate to extract from the lower bits.
4054  }
4055 
4056  return true;
4057 }
4058 
4059 static bool expandSHXDROT(MachineInstrBuilder &MIB, const MCInstrDesc &Desc) {
4060  MIB->setDesc(Desc);
4061  int64_t ShiftAmt = MIB->getOperand(2).getImm();
4062  // Temporarily remove the immediate so we can add another source register.
4063  MIB->RemoveOperand(2);
4064  // Add the register. Don't copy the kill flag if there is one.
4065  MIB.addReg(MIB->getOperand(1).getReg(),
4066  getUndefRegState(MIB->getOperand(1).isUndef()));
4067  // Add back the immediate.
4068  MIB.addImm(ShiftAmt);
4069  return true;
4070 }
4071 
4073  bool HasAVX = Subtarget.hasAVX();
4074  MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4075  switch (MI.getOpcode()) {
4076  case X86::MOV32r0:
4077  return Expand2AddrUndef(MIB, get(X86::XOR32rr));
4078  case X86::MOV32r1:
4079  return expandMOV32r1(MIB, *this, /*MinusOne=*/ false);
4080  case X86::MOV32r_1:
4081  return expandMOV32r1(MIB, *this, /*MinusOne=*/ true);
4082  case X86::MOV32ImmSExti8:
4083  case X86::MOV64ImmSExti8:
4084  return ExpandMOVImmSExti8(MIB, *this, Subtarget);
4085  case X86::SETB_C8r:
4086  return Expand2AddrUndef(MIB, get(X86::SBB8rr));
4087  case X86::SETB_C16r:
4088  return Expand2AddrUndef(MIB, get(X86::SBB16rr));
4089  case X86::SETB_C32r:
4090  return Expand2AddrUndef(MIB, get(X86::SBB32rr));
4091  case X86::SETB_C64r:
4092  return Expand2AddrUndef(MIB, get(X86::SBB64rr));
4093  case X86::MMX_SET0:
4094  return Expand2AddrUndef(MIB, get(X86::MMX_PXORirr));
4095  case X86::V_SET0:
4096  case X86::FsFLD0SS:
4097  case X86::FsFLD0SD:
4098  case X86::FsFLD0F128:
4099  return Expand2AddrUndef(MIB, get(HasAVX ? X86::VXORPSrr : X86::XORPSrr));
4100  case X86::AVX_SET0: {
4101  assert(HasAVX && "AVX not supported");
4103  Register SrcReg = MIB->getOperand(0).getReg();
4104  Register XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
4105  MIB->getOperand(0).setReg(XReg);
4106  Expand2AddrUndef(MIB, get(X86::VXORPSrr));
4107  MIB.addReg(SrcReg, RegState::ImplicitDefine);
4108  return true;
4109  }
4110  case X86::AVX512_128_SET0:
4111  case X86::AVX512_FsFLD0SS:
4112  case X86::AVX512_FsFLD0SD:
4113  case X86::AVX512_FsFLD0F128: {
4114  bool HasVLX = Subtarget.hasVLX();
4115  Register SrcReg = MIB->getOperand(0).getReg();
4117  if (HasVLX || TRI->getEncodingValue(SrcReg) < 16)
4118  return Expand2AddrUndef(MIB,
4119  get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
4120  // Extended register without VLX. Use a larger XOR.
4121  SrcReg =
4122  TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm, &X86::VR512RegClass);
4123  MIB->getOperand(0).setReg(SrcReg);
4124  return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
4125  }
4126  case X86::AVX512_256_SET0:
4127  case X86::AVX512_512_SET0: {
4128  bool HasVLX = Subtarget.hasVLX();
4129  Register SrcReg = MIB->getOperand(0).getReg();
4131  if (HasVLX || TRI->getEncodingValue(SrcReg) < 16) {
4132  Register XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
4133  MIB->getOperand(0).setReg(XReg);
4134  Expand2AddrUndef(MIB,
4135  get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
4136  MIB.addReg(SrcReg, RegState::ImplicitDefine);
4137  return true;
4138  }
4139  if (MI.getOpcode() == X86::AVX512_256_SET0) {
4140  // No VLX so we must reference a zmm.
4141  unsigned ZReg =
4142  TRI->getMatchingSuperReg(SrcReg, X86::sub_ymm, &X86::VR512RegClass);
4143  MIB->getOperand(0).setReg(ZReg);
4144  }
4145  return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
4146  }
4147  case X86::V_SETALLONES:
4148  return Expand2AddrUndef(MIB, get(HasAVX ? X86::VPCMPEQDrr : X86::PCMPEQDrr));
4149  case X86::AVX2_SETALLONES:
4150  return Expand2AddrUndef(MIB, get(X86::VPCMPEQDYrr));
4151  case X86::AVX1_SETALLONES: {
4152  Register Reg = MIB->getOperand(0).getReg();
4153  // VCMPPSYrri with an immediate 0xf should produce VCMPTRUEPS.
4154  MIB->setDesc(get(X86::VCMPPSYrri));
4155  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xf);
4156  return true;
4157  }
4158  case X86::AVX512_512_SETALLONES: {
4159  Register Reg = MIB->getOperand(0).getReg();
4160  MIB->setDesc(get(X86::VPTERNLOGDZrri));
4161  // VPTERNLOGD needs 3 register inputs and an immediate.
4162  // 0xff will return 1s for any input.
4163  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef)
4164  .addReg(Reg, RegState::Undef).addImm(0xff);
4165  return true;
4166  }
4167  case X86::AVX512_512_SEXT_MASK_32:
4168  case X86::AVX512_512_SEXT_MASK_64: {
4169  Register Reg = MIB->getOperand(0).getReg();
4170  Register MaskReg = MIB->getOperand(1).getReg();
4171  unsigned MaskState = getRegState(MIB->getOperand(1));
4172  unsigned Opc = (MI.getOpcode() == X86::AVX512_512_SEXT_MASK_64) ?
4173  X86::VPTERNLOGQZrrikz : X86::VPTERNLOGDZrrikz;
4174  MI.RemoveOperand(1);
4175  MIB->setDesc(get(Opc));
4176  // VPTERNLOG needs 3 register inputs and an immediate.
4177  // 0xff will return 1s for any input.
4178  MIB.addReg(Reg, RegState::Undef).addReg(MaskReg, MaskState)
4179  .addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xff);
4180  return true;
4181  }
4182  case X86::VMOVAPSZ128rm_NOVLX:
4183  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSrm),
4184  get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
4185  case X86::VMOVUPSZ128rm_NOVLX:
4186  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSrm),
4187  get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
4188  case X86::VMOVAPSZ256rm_NOVLX:
4189  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSYrm),
4190  get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
4191  case X86::VMOVUPSZ256rm_NOVLX:
4192  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSYrm),
4193  get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
4194  case X86::VMOVAPSZ128mr_NOVLX:
4195  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSmr),
4196  get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
4197  case X86::VMOVUPSZ128mr_NOVLX:
4198  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSmr),
4199  get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
4200  case X86::VMOVAPSZ256mr_NOVLX:
4201  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSYmr),
4202  get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
4203  case X86::VMOVUPSZ256mr_NOVLX:
4204  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSYmr),
4205  get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
4206  case X86::MOV32ri64: {
4207  Register Reg = MIB->getOperand(0).getReg();
4208  Register Reg32 = RI.getSubReg(Reg, X86::sub_32bit);
4209  MI.setDesc(get(X86::MOV32ri));
4210  MIB->getOperand(0).setReg(Reg32);
4211  MIB.addReg(Reg, RegState::ImplicitDefine);
4212  return true;
4213  }
4214 
4215  // KNL does not recognize dependency-breaking idioms for mask registers,
4216  // so kxnor %k1, %k1, %k2 has a RAW dependence on %k1.
4217  // Using %k0 as the undef input register is a performance heuristic based
4218  // on the assumption that %k0 is used less frequently than the other mask
4219  // registers, since it is not usable as a write mask.
4220  // FIXME: A more advanced approach would be to choose the best input mask
4221  // register based on context.
4222  case X86::KSET0W: return Expand2AddrKreg(MIB, get(X86::KXORWrr), X86::K0);
4223  case X86::KSET0D: return Expand2AddrKreg(MIB, get(X86::KXORDrr), X86::K0);
4224  case X86::KSET0Q: return Expand2AddrKreg(MIB, get(X86::KXORQrr), X86::K0);
4225  case X86::KSET1W: return Expand2AddrKreg(MIB, get(X86::KXNORWrr), X86::K0);
4226  case X86::KSET1D: return Expand2AddrKreg(MIB, get(X86::KXNORDrr), X86::K0);
4227  case X86::KSET1Q: return Expand2AddrKreg(MIB, get(X86::KXNORQrr), X86::K0);
4228  case TargetOpcode::LOAD_STACK_GUARD:
4229  expandLoadStackGuard(MIB, *this);
4230  return true;
4231  case X86::XOR64_FP:
4232  case X86::XOR32_FP:
4233  return expandXorFP(MIB, *this);
4234  case X86::SHLDROT32ri: return expandSHXDROT(MIB, get(X86::SHLD32rri8));
4235  case X86::SHLDROT64ri: return expandSHXDROT(MIB, get(X86::SHLD64rri8));
4236  case X86::SHRDROT32ri: return expandSHXDROT(MIB, get(X86::SHRD32rri8));
4237  case X86::SHRDROT64ri: return expandSHXDROT(MIB, get(X86::SHRD64rri8));
4238  case X86::ADD8rr_DB: MIB->setDesc(get(X86::OR8rr)); break;
4239  case X86::ADD16rr_DB: MIB->setDesc(get(X86::OR16rr)); break;
4240  case X86::ADD32rr_DB: MIB->setDesc(get(X86::OR32rr)); break;
4241  case X86::ADD64rr_DB: MIB->setDesc(get(X86::OR64rr)); break;
4242  case X86::ADD8ri_DB: MIB->setDesc(get(X86::OR8ri)); break;
4243  case X86::ADD16ri_DB: MIB->setDesc(get(X86::OR16ri)); break;
4244  case X86::ADD32ri_DB: MIB->setDesc(get(X86::OR32ri)); break;
4245  case X86::ADD64ri32_DB: MIB->setDesc(get(X86::OR64ri32)); break;
4246  case X86::ADD16ri8_DB: MIB->setDesc(get(X86::OR16ri8)); break;
4247  case X86::ADD32ri8_DB: MIB->setDesc(get(X86::OR32ri8)); break;
4248  case X86::ADD64ri8_DB: MIB->setDesc(get(X86::OR64ri8)); break;
4249  }
4250  return false;
4251 }
4252 
4253 /// Return true for all instructions that only update
4254 /// the first 32 or 64-bits of the destination register and leave the rest
4255 /// unmodified. This can be used to avoid folding loads if the instructions
4256 /// only update part of the destination register, and the non-updated part is
4257 /// not needed. e.g. cvtss2sd, sqrtss. Unfolding the load from these
4258 /// instructions breaks the partial register dependency and it can improve
4259 /// performance. e.g.:
4260 ///
4261 /// movss (%rdi), %xmm0
4262 /// cvtss2sd %xmm0, %xmm0
4263 ///
4264 /// Instead of
4265 /// cvtss2sd (%rdi), %xmm0
4266 ///
4267 /// FIXME: This should be turned into a TSFlags.
4268 ///
4269 static bool hasPartialRegUpdate(unsigned Opcode,
4270  const X86Subtarget &Subtarget,
4271  bool ForLoadFold = false) {
4272  switch (Opcode) {
4273  case X86::CVTSI2SSrr:
4274  case X86::CVTSI2SSrm:
4275  case X86::CVTSI642SSrr:
4276  case X86::CVTSI642SSrm:
4277  case X86::CVTSI2SDrr:
4278  case X86::CVTSI2SDrm:
4279  case X86::CVTSI642SDrr:
4280  case X86::CVTSI642SDrm:
4281  // Load folding won't effect the undef register update since the input is
4282  // a GPR.
4283  return !ForLoadFold;
4284  case X86::CVTSD2SSrr:
4285  case X86::CVTSD2SSrm:
4286  case X86::CVTSS2SDrr:
4287  case X86::CVTSS2SDrm:
4288  case X86::MOVHPDrm:
4289  case X86::MOVHPSrm:
4290  case X86::MOVLPDrm:
4291  case X86::MOVLPSrm:
4292  case X86::RCPSSr:
4293  case X86::RCPSSm:
4294  case X86::RCPSSr_Int:
4295  case X86::RCPSSm_Int:
4296  case X86::ROUNDSDr:
4297  case X86::ROUNDSDm:
4298  case X86::ROUNDSSr:
4299  case X86::ROUNDSSm:
4300  case X86::RSQRTSSr:
4301  case X86::RSQRTSSm:
4302  case X86::RSQRTSSr_Int:
4303  case X86::RSQRTSSm_Int:
4304  case X86::SQRTSSr:
4305  case X86::SQRTSSm:
4306  case X86::SQRTSSr_Int:
4307  case X86::SQRTSSm_Int:
4308  case X86::SQRTSDr:
4309  case X86::SQRTSDm:
4310  case X86::SQRTSDr_Int:
4311  case X86::SQRTSDm_Int:
4312  return true;
4313  // GPR
4314  case X86::POPCNT32rm:
4315  case X86::POPCNT32rr:
4316  case X86::POPCNT64rm:
4317  case X86::POPCNT64rr:
4318  return Subtarget.hasPOPCNTFalseDeps();
4319  case X86::LZCNT32rm:
4320  case X86::LZCNT32rr:
4321  case X86::LZCNT64rm:
4322  case X86::LZCNT64rr:
4323  case X86::TZCNT32rm:
4324  case X86::TZCNT32rr:
4325  case X86::TZCNT64rm:
4326  case X86::TZCNT64rr:
4327  return Subtarget.hasLZCNTFalseDeps();
4328  }
4329 
4330  return false;
4331 }
4332 
4333 /// Inform the BreakFalseDeps pass how many idle
4334 /// instructions we would like before a partial register update.
4336  const MachineInstr &MI, unsigned OpNum,
4337  const TargetRegisterInfo *TRI) const {
4338  if (OpNum != 0 || !hasPartialRegUpdate(MI.getOpcode(), Subtarget))
4339  return 0;
4340 
4341  // If MI is marked as reading Reg, the partial register update is wanted.
4342  const MachineOperand &MO = MI.getOperand(0);
4343  Register Reg = MO.getReg();
4344  if (Register::isVirtualRegister(Reg)) {
4345  if (MO.readsReg() || MI.readsVirtualRegister(Reg))
4346  return 0;
4347  } else {
4348  if (MI.readsRegister(Reg, TRI))
4349  return 0;
4350  }
4351 
4352  // If any instructions in the clearance range are reading Reg, insert a
4353  // dependency breaking instruction, which is inexpensive and is likely to
4354  // be hidden in other instruction's cycles.
4356 }
4357 
4358 // Return true for any instruction the copies the high bits of the first source
4359 // operand into the unused high bits of the destination operand.
4360 static bool hasUndefRegUpdate(unsigned Opcode, bool ForLoadFold = false) {
4361  switch (Opcode) {
4362  case X86::VCVTSI2SSrr:
4363  case X86::VCVTSI2SSrm:
4364  case X86::VCVTSI2SSrr_Int:
4365  case X86::VCVTSI2SSrm_Int:
4366  case X86::VCVTSI642SSrr:
4367  case X86::VCVTSI642SSrm:
4368  case X86::VCVTSI642SSrr_Int:
4369  case X86::VCVTSI642SSrm_Int:
4370  case X86::VCVTSI2SDrr:
4371  case X86::VCVTSI2SDrm:
4372  case X86::VCVTSI2SDrr_Int:
4373  case X86::VCVTSI2SDrm_Int:
4374  case X86::VCVTSI642SDrr:
4375  case X86::VCVTSI642SDrm:
4376  case X86::VCVTSI642SDrr_Int:
4377  case X86::VCVTSI642SDrm_Int:
4378  // AVX-512
4379  case X86::VCVTSI2SSZrr:
4380  case X86::VCVTSI2SSZrm:
4381  case X86::VCVTSI2SSZrr_Int:
4382  case X86::VCVTSI2SSZrrb_Int:
4383  case X86::VCVTSI2SSZrm_Int:
4384  case X86::VCVTSI642SSZrr:
4385  case X86::VCVTSI642SSZrm:
4386  case X86::VCVTSI642SSZrr_Int:
4387  case X86::VCVTSI642SSZrrb_Int:
4388  case X86::VCVTSI642SSZrm_Int:
4389  case X86::VCVTSI2SDZrr:
4390  case X86::VCVTSI2SDZrm:
4391  case X86::VCVTSI2SDZrr_Int:
4392  case X86::VCVTSI2SDZrm_Int:
4393  case X86::VCVTSI642SDZrr:
4394  case X86::VCVTSI642SDZrm:
4395  case X86::VCVTSI642SDZrr_Int:
4396  case X86::VCVTSI642SDZrrb_Int:
4397  case X86::VCVTSI642SDZrm_Int:
4398  case X86::VCVTUSI2SSZrr:
4399  case X86::VCVTUSI2SSZrm:
4400  case X86::VCVTUSI2SSZrr_Int:
4401  case X86::VCVTUSI2SSZrrb_Int:
4402  case X86::VCVTUSI2SSZrm_Int:
4403  case X86::VCVTUSI642SSZrr:
4404  case X86::VCVTUSI642SSZrm:
4405  case X86::VCVTUSI642SSZrr_Int:
4406  case X86::VCVTUSI642SSZrrb_Int:
4407  case X86::VCVTUSI642SSZrm_Int:
4408  case X86::VCVTUSI2SDZrr:
4409  case X86::VCVTUSI2SDZrm:
4410  case X86::VCVTUSI2SDZrr_Int:
4411  case X86::VCVTUSI2SDZrm_Int:
4412  case X86::VCVTUSI642SDZrr:
4413  case X86::VCVTUSI642SDZrm:
4414  case X86::VCVTUSI642SDZrr_Int:
4415  case X86::VCVTUSI642SDZrrb_Int:
4416  case X86::VCVTUSI642SDZrm_Int:
4417  // Load folding won't effect the undef register update since the input is
4418  // a GPR.
4419  return !ForLoadFold;
4420  case X86::VCVTSD2SSrr:
4421  case X86::VCVTSD2SSrm:
4422  case X86::VCVTSD2SSrr_Int:
4423  case X86::VCVTSD2SSrm_Int:
4424  case X86::VCVTSS2SDrr:
4425  case X86::VCVTSS2SDrm:
4426  case X86::VCVTSS2SDrr_Int:
4427  case X86::VCVTSS2SDrm_Int:
4428  case X86::VRCPSSr:
4429  case X86::VRCPSSr_Int:
4430  case X86::VRCPSSm:
4431  case X86::VRCPSSm_Int:
4432  case X86::VROUNDSDr:
4433  case X86::VROUNDSDm:
4434  case X86::VROUNDSDr_Int:
4435  case X86::VROUNDSDm_Int:
4436  case X86::VROUNDSSr:
4437  case X86::VROUNDSSm:
4438  case X86::VROUNDSSr_Int:
4439  case X86::VROUNDSSm_Int:
4440  case X86::VRSQRTSSr:
4441  case X86::VRSQRTSSr_Int:
4442  case X86::VRSQRTSSm:
4443  case X86::VRSQRTSSm_Int:
4444  case X86::VSQRTSSr:
4445  case X86::VSQRTSSr_Int:
4446  case X86::VSQRTSSm:
4447  case X86::VSQRTSSm_Int:
4448  case X86::VSQRTSDr:
4449  case X86::VSQRTSDr_Int:
4450  case X86::VSQRTSDm:
4451  case X86::VSQRTSDm_Int:
4452  // AVX-512
4453  case X86::VCVTSD2SSZrr:
4454  case X86::VCVTSD2SSZrr_Int:
4455  case X86::VCVTSD2SSZrrb_Int:
4456  case X86::VCVTSD2SSZrm:
4457  case X86::VCVTSD2SSZrm_Int:
4458  case X86::VCVTSS2SDZrr:
4459  case X86::VCVTSS2SDZrr_Int:
4460  case X86::VCVTSS2SDZrrb_Int:
4461  case X86::VCVTSS2SDZrm:
4462  case X86::VCVTSS2SDZrm_Int:
4463  case X86::VGETEXPSDZr:
4464  case X86::VGETEXPSDZrb:
4465  case X86::VGETEXPSDZm:
4466  case X86::VGETEXPSSZr:
4467  case X86::VGETEXPSSZrb:
4468  case X86::VGETEXPSSZm:
4469  case X86::VGETMANTSDZrri:
4470  case X86::VGETMANTSDZrrib:
4471  case X86::VGETMANTSDZrmi:
4472  case X86::VGETMANTSSZrri:
4473  case X86::VGETMANTSSZrrib:
4474  case X86::VGETMANTSSZrmi:
4475  case X86::VRNDSCALESDZr:
4476  case X86::VRNDSCALESDZr_Int:
4477  case X86::VRNDSCALESDZrb_Int:
4478  case X86::VRNDSCALESDZm:
4479  case X86::VRNDSCALESDZm_Int:
4480  case X86::VRNDSCALESSZr:
4481  case X86::VRNDSCALESSZr_Int:
4482  case X86::VRNDSCALESSZrb_Int:
4483  case X86::VRNDSCALESSZm:
4484  case X86::VRNDSCALESSZm_Int:
4485  case X86::VRCP14SDZrr:
4486  case X86::VRCP14SDZrm:
4487  case X86::VRCP14SSZrr:
4488  case X86::VRCP14SSZrm:
4489  case X86::VRCP28SDZr:
4490  case X86::VRCP28SDZrb:
4491  case X86::VRCP28SDZm:
4492  case X86::VRCP28SSZr:
4493  case X86::VRCP28SSZrb:
4494  case X86::VRCP28SSZm:
4495  case X86::VREDUCESSZrmi:
4496  case X86::VREDUCESSZrri:
4497  case X86::VREDUCESSZrrib:
4498  case X86::VRSQRT14SDZrr:
4499  case X86::VRSQRT14SDZrm:
4500  case X86::VRSQRT14SSZrr:
4501  case X86::VRSQRT14SSZrm:
4502  case X86::VRSQRT28SDZr:
4503  case X86::VRSQRT28SDZrb:
4504  case X86::VRSQRT28SDZm:
4505  case X86::VRSQRT28SSZr:
4506  case X86::VRSQRT28SSZrb:
4507  case X86::VRSQRT28SSZm:
4508  case X86::VSQRTSSZr:
4509  case X86::VSQRTSSZr_Int:
4510  case X86::VSQRTSSZrb_Int:
4511  case X86::VSQRTSSZm:
4512  case X86::VSQRTSSZm_Int:
4513  case X86::VSQRTSDZr:
4514  case X86::VSQRTSDZr_Int:
4515  case X86::VSQRTSDZrb_Int:
4516  case X86::VSQRTSDZm:
4517  case X86::VSQRTSDZm_Int:
4518  return true;
4519  }
4520 
4521  return false;
4522 }
4523 
4524 /// Inform the BreakFalseDeps pass how many idle instructions we would like
4525 /// before certain undef register reads.
4526 ///
4527 /// This catches the VCVTSI2SD family of instructions:
4528 ///
4529 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
4530 ///
4531 /// We should to be careful *not* to catch VXOR idioms which are presumably
4532 /// handled specially in the pipeline:
4533 ///
4534 /// vxorps undef %xmm1, undef %xmm1, %xmm1
4535 ///
4536 /// Like getPartialRegUpdateClearance, this makes a strong assumption that the
4537 /// high bits that are passed-through are not live.
4538 unsigned
4540  const TargetRegisterInfo *TRI) const {
4541  if (!hasUndefRegUpdate(MI.getOpcode()))
4542  return 0;
4543 
4544  // Set the OpNum parameter to the first source operand.
4545  OpNum = 1;
4546 
4547  const MachineOperand &MO = MI.getOperand(OpNum);
4548  if (MO.isUndef() && Register::isPhysicalRegister(MO.getReg())) {
4549  return UndefRegClearance;
4550  }
4551  return 0;
4552 }
4553 
4555  MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
4556  Register Reg = MI.getOperand(OpNum).getReg();
4557  // If MI kills this register, the false dependence is already broken.
4558  if (MI.killsRegister(Reg, TRI))
4559  return;
4560 
4561  if (X86::VR128RegClass.contains(Reg)) {
4562  // These instructions are all floating point domain, so xorps is the best
4563  // choice.
4564  unsigned Opc = Subtarget.hasAVX() ? X86::VXORPSrr : X86::XORPSrr;
4565  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(Opc), Reg)
4566  .addReg(Reg, RegState::Undef)
4567  .addReg(Reg, RegState::Undef);
4568  MI.addRegisterKilled(Reg, TRI, true);
4569  } else if (X86::VR256RegClass.contains(Reg)) {
4570  // Use vxorps to clear the full ymm register.
4571  // It wants to read and write the xmm sub-register.
4572  Register XReg = TRI->getSubReg(Reg, X86::sub_xmm);
4573  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::VXORPSrr), XReg)
4574  .addReg(XReg, RegState::Undef)
4575  .addReg(XReg, RegState::Undef)
4577  MI.addRegisterKilled(Reg, TRI, true);
4578  } else if (X86::GR64RegClass.contains(Reg)) {
4579  // Using XOR32rr because it has shorter encoding and zeros up the upper bits
4580  // as well.
4581  Register XReg = TRI->getSubReg(Reg, X86::sub_32bit);
4582  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), XReg)
4583  .addReg(XReg, RegState::Undef)
4584  .addReg(XReg, RegState::Undef)
4586  MI.addRegisterKilled(Reg, TRI, true);
4587  } else if (X86::GR32RegClass.contains(Reg)) {
4588  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), Reg)
4589  .addReg(Reg, RegState::Undef)
4590  .addReg(Reg, RegState::Undef);
4591  MI.addRegisterKilled(Reg, TRI, true);
4592  }
4593 }
4594 
4596  int PtrOffset = 0) {
4597  unsigned NumAddrOps = MOs.size();
4598 
4599  if (NumAddrOps < 4) {
4600  // FrameIndex only - add an immediate offset (whether its zero or not).
4601  for (unsigned i = 0; i != NumAddrOps; ++i)
4602  MIB.add(MOs[i]);
4603  addOffset(MIB, PtrOffset);
4604  } else {
4605  // General Memory Addressing - we need to add any offset to an existing
4606  // offset.
4607  assert(MOs.size() == 5 && "Unexpected memory operand list length");
4608  for (unsigned i = 0; i != NumAddrOps; ++i) {
4609  const MachineOperand &MO = MOs[i];
4610  if (i == 3 && PtrOffset != 0) {
4611  MIB.addDisp(MO, PtrOffset);
4612  } else {
4613  MIB.add(MO);
4614  }
4615  }
4616  }
4617 }
4618 
4620  MachineInstr &NewMI,
4621  const TargetInstrInfo &TII) {
4624 
4625  for (int Idx : llvm::seq<int>(0, NewMI.getNumOperands())) {
4626  MachineOperand &MO = NewMI.getOperand(Idx);
4627  // We only need to update constraints on virtual register operands.
4628  if (!MO.isReg())
4629  continue;
4630  Register Reg = MO.getReg();
4631  if (!Register::isVirtualRegister(Reg))
4632  continue;
4633 
4634  auto *NewRC = MRI.constrainRegClass(
4635  Reg, TII.getRegClass(NewMI.getDesc(), Idx, &TRI, MF));
4636  if (!NewRC) {
4637  LLVM_DEBUG(
4638  dbgs() << "WARNING: Unable to update register constraint for operand "
4639  << Idx << " of instruction:\n";
4640  NewMI.dump(); dbgs() << "\n");
4641  }
4642  }
4643 }
4644 
4645 static MachineInstr *FuseTwoAddrInst(MachineFunction &MF, unsigned Opcode,
4647  MachineBasicBlock::iterator InsertPt,
4648  MachineInstr &MI,
4649  const TargetInstrInfo &TII) {
4650  // Create the base instruction with the memory operand as the first part.
4651  // Omit the implicit operands, something BuildMI can't do.
4652  MachineInstr *NewMI =
4653  MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
4654  MachineInstrBuilder MIB(MF, NewMI);
4655  addOperands(MIB, MOs);
4656 
4657  // Loop over the rest of the ri operands, converting them over.
4658  unsigned NumOps = MI.getDesc().getNumOperands() - 2;
4659  for (unsigned i = 0; i != NumOps; ++i) {
4660  MachineOperand &MO = MI.getOperand(i + 2);
4661  MIB.add(MO);
4662  }
4663  for (unsigned i = NumOps + 2, e = MI.getNumOperands(); i != e; ++i) {
4664  MachineOperand &MO = MI.getOperand(i);
4665  MIB.add(MO);
4666  }
4667 
4668  updateOperandRegConstraints(MF, *NewMI, TII);
4669 
4670  MachineBasicBlock *MBB = InsertPt->getParent();
4671  MBB->insert(InsertPt, NewMI);
4672 
4673  return MIB;
4674 }
4675 
4676 static MachineInstr *FuseInst(MachineFunction &MF, unsigned Opcode,
4677  unsigned OpNo, ArrayRef<MachineOperand> MOs,
4678  MachineBasicBlock::iterator InsertPt,
4679  MachineInstr &MI, const TargetInstrInfo &TII,
4680  int PtrOffset = 0) {
4681  // Omit the implicit operands, something BuildMI can't do.
4682  MachineInstr *NewMI =
4683  MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
4684  MachineInstrBuilder MIB(MF, NewMI);
4685 
4686  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4687  MachineOperand &MO = MI.getOperand(i);
4688  if (i == OpNo) {
4689  assert(MO.isReg() && "Expected to fold into reg operand!");
4690  addOperands(MIB, MOs, PtrOffset);
4691  } else {
4692  MIB.add(MO);
4693  }
4694  }
4695 
4696  updateOperandRegConstraints(MF, *NewMI, TII);
4697 
4698  MachineBasicBlock *MBB = InsertPt->getParent();
4699  MBB->insert(InsertPt, NewMI);
4700 
4701  return MIB;
4702 }
4703 
4704 static MachineInstr *MakeM0Inst(const TargetInstrInfo &TII, unsigned Opcode,
4706  MachineBasicBlock::iterator InsertPt,
4707  MachineInstr &MI) {
4708  MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
4709  MI.getDebugLoc(), TII.get(Opcode));
4710  addOperands(MIB, MOs);
4711  return MIB.addImm(0);
4712 }
4713 
4714 MachineInstr *X86InstrInfo::foldMemoryOperandCustom(
4715  MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
4717  unsigned Size, unsigned Align) const {
4718  switch (MI.getOpcode()) {
4719  case X86::INSERTPSrr:
4720  case X86::VINSERTPSrr:
4721  case X86::VINSERTPSZrr:
4722  // Attempt to convert the load of inserted vector into a fold load
4723  // of a single float.
4724  if (OpNum == 2) {
4725  unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm();
4726  unsigned ZMask = Imm & 15;
4727  unsigned DstIdx = (Imm >> 4) & 3;
4728  unsigned SrcIdx = (Imm >> 6) & 3;
4729 
4731  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4732  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4733  if ((Size == 0 || Size >= 16) && RCSize >= 16 && 4 <= Align) {
4734  int PtrOffset = SrcIdx * 4;
4735  unsigned NewImm = (DstIdx << 4) | ZMask;
4736  unsigned NewOpCode =
4737  (MI.getOpcode() == X86::VINSERTPSZrr) ? X86::VINSERTPSZrm :
4738  (MI.getOpcode() == X86::VINSERTPSrr) ? X86::VINSERTPSrm :
4739  X86::INSERTPSrm;
4740  MachineInstr *NewMI =
4741  FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, PtrOffset);
4742  NewMI->getOperand(NewMI->getNumOperands() - 1).setImm(NewImm);
4743  return NewMI;
4744  }
4745  }
4746  break;
4747  case X86::MOVHLPSrr:
4748  case X86::VMOVHLPSrr:
4749  case X86::VMOVHLPSZrr:
4750  // Move the upper 64-bits of the second operand to the lower 64-bits.
4751  // To fold the load, adjust the pointer to the upper and use (V)MOVLPS.
4752  // TODO: In most cases AVX doesn't have a 8-byte alignment requirement.
4753  if (OpNum == 2) {
4755  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4756  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4757  if ((Size == 0 || Size >= 16) && RCSize >= 16 && 8 <= Align) {
4758  unsigned NewOpCode =
4759  (MI.getOpcode() == X86::VMOVHLPSZrr) ? X86::VMOVLPSZ128rm :
4760  (MI.getOpcode() == X86::VMOVHLPSrr) ? X86::VMOVLPSrm :
4761  X86::MOVLPSrm;
4762  MachineInstr *NewMI =
4763  FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, 8);
4764  return NewMI;
4765  }
4766  }
4767  break;
4768  case X86::UNPCKLPDrr:
4769  // If we won't be able to fold this to the memory form of UNPCKL, use
4770  // MOVHPD instead. Done as custom because we can't have this in the load
4771  // table twice.
4772  if (OpNum == 2) {
4774  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4775  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4776  if ((Size == 0 || Size >= 16) && RCSize >= 16 && Align < 16) {
4777  MachineInstr *NewMI =
4778  FuseInst(MF, X86::MOVHPDrm, OpNum, MOs, InsertPt, MI, *this);
4779  return NewMI;
4780  }
4781  }
4782  break;
4783  }
4784 
4785  return nullptr;
4786 }
4787 
4789  MachineInstr &MI) {
4790  if (!hasUndefRegUpdate(MI.getOpcode(), /*ForLoadFold*/true) ||
4791  !MI.getOperand(1).isReg())
4792  return false;
4793 
4794  // The are two cases we need to handle depending on where in the pipeline
4795  // the folding attempt is being made.
4796  // -Register has the undef flag set.
4797  // -Register is produced by the IMPLICIT_DEF instruction.
4798 
4799  if (MI.getOperand(1).isUndef())
4800  return true;
4801 
4802  MachineRegisterInfo &RegInfo = MF.getRegInfo();
4803  MachineInstr *VRegDef = RegInfo.getUniqueVRegDef(MI.getOperand(1).getReg());
4804  return VRegDef && VRegDef->isImplicitDef();
4805 }
4806 
4807 
4809  MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
4811  unsigned Size, unsigned Align, bool AllowCommute) const {
4812  bool isSlowTwoMemOps = Subtarget.slowTwoMemOps();
4813  bool isTwoAddrFold = false;
4814 
4815  // For CPUs that favor the register form of a call or push,
4816  // do not fold loads into calls or pushes, unless optimizing for size
4817  // aggressively.
4818  if (isSlowTwoMemOps && !MF.getFunction().hasMinSize() &&
4819  (MI.getOpcode() == X86::CALL32r || MI.getOpcode() == X86::CALL64r ||
4820  MI.getOpcode() == X86::PUSH16r || MI.getOpcode() == X86::PUSH32r ||
4821  MI.getOpcode() == X86::PUSH64r))
4822  return nullptr;
4823 
4824  // Avoid partial and undef register update stalls unless optimizing for size.
4825  if (!MF.getFunction().hasOptSize() &&
4826  (hasPartialRegUpdate(MI.getOpcode(), Subtarget, /*ForLoadFold*/true) ||
4828  return nullptr;
4829 
4830  unsigned NumOps = MI.getDesc().getNumOperands();
4831  bool isTwoAddr =
4832  NumOps > 1 && MI.getDesc().getOperandConstraint(1, MCOI::TIED_TO) != -1;
4833 
4834  // FIXME: AsmPrinter doesn't know how to handle
4835  // X86II::MO_GOT_ABSOLUTE_ADDRESS after folding.
4836  if (MI.getOpcode() == X86::ADD32ri &&
4838  return nullptr;
4839 
4840  // GOTTPOFF relocation loads can only be folded into add instructions.
4841  // FIXME: Need to exclude other relocations that only support specific
4842  // instructions.
4843  if (MOs.size() == X86::AddrNumOperands &&
4844  MOs[X86::AddrDisp].getTargetFlags() == X86II::MO_GOTTPOFF &&
4845  MI.getOpcode() != X86::ADD64rr)
4846  return nullptr;
4847 
4848  MachineInstr *NewMI = nullptr;
4849 
4850  // Attempt to fold any custom cases we have.
4851  if (MachineInstr *CustomMI =
4852  foldMemoryOperandCustom(MF, MI, OpNum, MOs, InsertPt, Size, Align))
4853  return CustomMI;
4854 
4855  const X86MemoryFoldTableEntry *I = nullptr;
4856 
4857  // Folding a memory location into the two-address part of a two-address
4858  // instruction is different than folding it other places. It requires
4859  // replacing the *two* registers with the memory location.
4860  if (isTwoAddr && NumOps >= 2 && OpNum < 2 && MI.getOperand(0).isReg() &&
4861  MI.getOperand(1).isReg() &&
4862  MI.getOperand(0).getReg() == MI.getOperand(1).getReg()) {
4864  isTwoAddrFold = true;
4865  } else {
4866  if (OpNum == 0) {
4867  if (MI.getOpcode() == X86::MOV32r0) {
4868  NewMI = MakeM0Inst(*this, X86::MOV32mi, MOs, InsertPt, MI);
4869  if (NewMI)
4870  return NewMI;
4871  }
4872  }
4873 
4874  I = lookupFoldTable(MI.getOpcode(), OpNum);
4875  }
4876 
4877  if (I != nullptr) {
4878  unsigned Opcode = I->DstOp;
4879  unsigned MinAlign = (I->Flags & TB_ALIGN_MASK) >> TB_ALIGN_SHIFT;
4880  MinAlign = MinAlign ? 1 << (MinAlign - 1) : 0;
4881  if (Align < MinAlign)
4882  return nullptr;
4883  bool NarrowToMOV32rm = false;
4884  if (Size) {
4886  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum,
4887  &RI, MF);
4888  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4889  if (Size < RCSize) {
4890  // FIXME: Allow scalar intrinsic instructions like ADDSSrm_Int.
4891  // Check if it's safe to fold the load. If the size of the object is
4892  // narrower than the load width, then it's not.
4893  if (Opcode != X86::MOV64rm || RCSize != 8 || Size != 4)
4894  return nullptr;
4895  // If this is a 64-bit load, but the spill slot is 32, then we can do
4896  // a 32-bit load which is implicitly zero-extended. This likely is
4897  // due to live interval analysis remat'ing a load from stack slot.
4898  if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
4899  return nullptr;
4900  Opcode = X86::MOV32rm;
4901  NarrowToMOV32rm = true;
4902  }
4903  }
4904 
4905  if (isTwoAddrFold)
4906  NewMI = FuseTwoAddrInst(MF, Opcode, MOs, InsertPt, MI, *this);
4907  else
4908  NewMI = FuseInst(MF, Opcode, OpNum, MOs, InsertPt, MI, *this);
4909 
4910  if (NarrowToMOV32rm) {
4911  // If this is the special case where we use a MOV32rm to load a 32-bit
4912  // value and zero-extend the top bits. Change the destination register
4913  // to a 32-bit one.
4914  Register DstReg = NewMI->getOperand(0).getReg();
4915  if (Register::isPhysicalRegister(DstReg))
4916  NewMI->getOperand(0).setReg(RI.getSubReg(DstReg, X86::sub_32bit));
4917  else
4918  NewMI->getOperand(0).setSubReg(X86::sub_32bit);
4919  }
4920  return NewMI;
4921  }
4922 
4923  // If the instruction and target operand are commutable, commute the
4924  // instruction and try again.
4925  if (AllowCommute) {
4926  unsigned CommuteOpIdx1 = OpNum, CommuteOpIdx2 = CommuteAnyOperandIndex;
4927  if (findCommutedOpIndices(MI, CommuteOpIdx1, CommuteOpIdx2)) {
4928  bool HasDef = MI.getDesc().getNumDefs();
4929  Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register();
4930  Register Reg1 = MI.getOperand(CommuteOpIdx1).getReg();
4931  Register Reg2 = MI.getOperand(CommuteOpIdx2).getReg();
4932  bool Tied1 =
4933  0 == MI.getDesc().getOperandConstraint(CommuteOpIdx1, MCOI::TIED_TO);
4934  bool Tied2 =
4935  0 == MI.getDesc().getOperandConstraint(CommuteOpIdx2, MCOI::TIED_TO);
4936 
4937  // If either of the commutable operands are tied to the destination
4938  // then we can not commute + fold.
4939  if ((HasDef && Reg0 == Reg1 && Tied1) ||
4940  (HasDef && Reg0 == Reg2 && Tied2))
4941  return nullptr;
4942 
4943  MachineInstr *CommutedMI =
4944  commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
4945  if (!CommutedMI) {
4946  // Unable to commute.
4947  return nullptr;
4948  }
4949  if (CommutedMI != &MI) {
4950  // New instruction. We can't fold from this.
4951  CommutedMI->eraseFromParent();
4952  return nullptr;
4953  }
4954 
4955  // Attempt to fold with the commuted version of the instruction.
4956  NewMI = foldMemoryOperandImpl(MF, MI, CommuteOpIdx2, MOs, InsertPt,
4957  Size, Align, /*AllowCommute=*/false);
4958  if (NewMI)
4959  return NewMI;
4960 
4961  // Folding failed again - undo the commute before returning.
4962  MachineInstr *UncommutedMI =
4963  commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
4964  if (!UncommutedMI) {
4965  // Unable to commute.
4966  return nullptr;
4967  }
4968  if (UncommutedMI != &MI) {
4969  // New instruction. It doesn't need to be kept.
4970  UncommutedMI->eraseFromParent();
4971  return nullptr;
4972  }
4973 
4974  // Return here to prevent duplicate fuse failure report.
4975  return nullptr;
4976  }
4977  }
4978 
4979  // No fusion
4980  if (PrintFailedFusing && !MI.isCopy())
4981  dbgs() << "We failed to fuse operand " << OpNum << " in " << MI;
4982  return nullptr;
4983 }
4984 
4985 MachineInstr *
4987  ArrayRef<unsigned> Ops,
4988  MachineBasicBlock::iterator InsertPt,
4989  int FrameIndex, LiveIntervals *LIS,
4990  VirtRegMap *VRM) const {
4991  // Check switch flag
4992  if (NoFusing)
4993  return nullptr;
4994 
4995  // Avoid partial and undef register update stalls unless optimizing for size.
4996  if (!MF.getFunction().hasOptSize() &&
4997  (hasPartialRegUpdate(MI.getOpcode(), Subtarget, /*ForLoadFold*/true) ||
4999  return nullptr;
5000 
5001  // Don't fold subreg spills, or reloads that use a high subreg.
5002  for (auto Op : Ops) {
5003  MachineOperand &MO = MI.getOperand(Op);
5004  auto SubReg = MO.getSubReg();
5005  if (SubReg && (MO.isDef() || SubReg == X86::sub_8bit_hi))
5006  return nullptr;
5007  }
5008 
5009  const MachineFrameInfo &MFI = MF.getFrameInfo();
5010  unsigned Size = MFI.getObjectSize(FrameIndex);
5011  unsigned Alignment = MFI.getObjectAlignment(FrameIndex);
5012  // If the function stack isn't realigned we don't want to fold instructions
5013  // that need increased alignment.
5014  if (!RI.needsStackRealignment(MF))
5015  Alignment =
5016  std::min(Alignment, Subtarget.getFrameLowering()->getStackAlignment());
5017  if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
5018  unsigned NewOpc = 0;
5019  unsigned RCSize = 0;
5020  switch (MI.getOpcode()) {
5021  default: return nullptr;
5022  case X86::TEST8rr: NewOpc = X86::CMP8ri; RCSize = 1; break;
5023  case X86::TEST16rr: NewOpc = X86::CMP16ri8; RCSize = 2; break;
5024  case X86::TEST32rr: NewOpc = X86::CMP32ri8; RCSize = 4; break;
5025  case X86::TEST64rr: NewOpc = X86::CMP64ri8; RCSize = 8; break;
5026  }
5027  // Check if it's safe to fold the load. If the size of the object is
5028  // narrower than the load width, then it's not.
5029  if (Size < RCSize)
5030  return nullptr;
5031  // Change to CMPXXri r, 0 first.
5032  MI.setDesc(get(NewOpc));
5033  MI.getOperand(1).ChangeToImmediate(0);
5034  } else if (Ops.size() != 1)
5035  return nullptr;
5036 
5037  return foldMemoryOperandImpl(MF, MI, Ops[0],
5038  MachineOperand::CreateFI(FrameIndex), InsertPt,
5039  Size, Alignment, /*AllowCommute=*/true);
5040 }
5041 
5042 /// Check if \p LoadMI is a partial register load that we can't fold into \p MI
5043 /// because the latter uses contents that wouldn't be defined in the folded
5044 /// version. For instance, this transformation isn't legal:
5045 /// movss (%rdi), %xmm0
5046 /// addps %xmm0, %xmm0
5047 /// ->
5048 /// addps (%rdi), %xmm0
5049 ///
5050 /// But this one is:
5051 /// movss (%rdi), %xmm0
5052 /// addss %xmm0, %xmm0
5053 /// ->
5054 /// addss (%rdi), %xmm0
5055 ///
5057  const MachineInstr &UserMI,
5058  const MachineFunction &MF) {
5059  unsigned Opc = LoadMI.getOpcode();
5060  unsigned UserOpc = UserMI.getOpcode();
5062  const TargetRegisterClass *RC =
5063  MF.getRegInfo().getRegClass(LoadMI.getOperand(0).getReg());
5064  unsigned RegSize = TRI.getRegSizeInBits(*RC);
5065 
5066  if ((Opc == X86::MOVSSrm || Opc == X86::VMOVSSrm || Opc == X86::VMOVSSZrm ||
5067  Opc == X86::MOVSSrm_alt || Opc == X86::VMOVSSrm_alt ||
5068  Opc == X86::VMOVSSZrm_alt) &&
5069  RegSize > 32) {
5070  // These instructions only load 32 bits, we can't fold them if the
5071  // destination register is wider than 32 bits (4 bytes), and its user
5072  // instruction isn't scalar (SS).
5073  switch (UserOpc) {
5074  case X86::ADDSSrr_Int: case X86::VADDSSrr_Int: case X86::VADDSSZrr_Int:
5075  case X86::CMPSSrr_Int: case X86::VCMPSSrr_Int: case X86::VCMPSSZrr_Int:
5076  case X86::DIVSSrr_Int: case X86::VDIVSSrr_Int: case X86::VDIVSSZrr_Int:
5077  case X86::MAXSSrr_Int: case X86::VMAXSSrr_Int: case X86::VMAXSSZrr_Int:
5078  case X86::MINSSrr_Int: case X86::VMINSSrr_Int: case X86::VMINSSZrr_Int:
5079  case X86::MULSSrr_Int: case X86::VMULSSrr_Int: case X86::VMULSSZrr_Int:
5080  case X86::SUBSSrr_Int: case X86::VSUBSSrr_Int: case X86::VSUBSSZrr_Int:
5081  case X86::VADDSSZrr_Intk: case X86::VADDSSZrr_Intkz:
5082  case X86::VCMPSSZrr_Intk:
5083  case X86::VDIVSSZrr_Intk: case X86::VDIVSSZrr_Intkz:
5084  case X86::VMAXSSZrr_Intk: case X86::VMAXSSZrr_Intkz:
5085  case X86::VMINSSZrr_Intk: case X86::VMINSSZrr_Intkz:
5086  case X86::VMULSSZrr_Intk: case X86::VMULSSZrr_Intkz:
5087  case X86::VSUBSSZrr_Intk: case X86::VSUBSSZrr_Intkz:
5088  case X86::VFMADDSS4rr_Int: case X86::VFNMADDSS4rr_Int:
5089  case X86::VFMSUBSS4rr_Int: case X86::VFNMSUBSS4rr_Int:
5090  case X86::VFMADD132SSr_Int: case X86::VFNMADD132SSr_Int:
5091  case X86::VFMADD213SSr_Int: case X86::VFNMADD213SSr_Int:
5092  case X86::VFMADD231SSr_Int: case X86::VFNMADD231SSr_Int:
5093  case X86::VFMSUB132SSr_Int: case X86::VFNMSUB132SSr_Int:
5094  case X86::VFMSUB213SSr_Int: case X86::VFNMSUB213SSr_Int:
5095  case X86::VFMSUB231SSr_Int: case X86::VFNMSUB231SSr_Int:
5096  case X86::VFMADD132SSZr_Int: case X86::VFNMADD132SSZr_Int:
5097  case X86::VFMADD213SSZr_Int: case X86::VFNMADD213SSZr_Int:
5098  case X86::VFMADD231SSZr_Int: case X86::VFNMADD231SSZr_Int:
5099  case X86::VFMSUB132SSZr_Int: case X86::VFNMSUB132SSZr_Int:
5100  case X86::VFMSUB213SSZr_Int: case X86::VFNMSUB213SSZr_Int:
5101  case X86::VFMSUB231SSZr_Int: case X86::VFNMSUB231SSZr_Int:
5102  case X86::VFMADD132SSZr_Intk: case X86::VFNMADD132SSZr_Intk:
5103  case X86::VFMADD213SSZr_Intk: case X86::VFNMADD213SSZr_Intk:
5104  case X86::VFMADD231SSZr_Intk: case X86::VFNMADD231SSZr_Intk:
5105  case X86::VFMSUB132SSZr_Intk: case X86::VFNMSUB132SSZr_Intk:
5106  case X86::VFMSUB213SSZr_Intk: case X86::VFNMSUB213SSZr_Intk:
5107  case X86::VFMSUB231SSZr_Intk: case X86::VFNMSUB231SSZr_Intk:
5108  case X86::VFMADD132SSZr_Intkz: case X86::VFNMADD132SSZr_Intkz:
5109  case X86::VFMADD213SSZr_Intkz: case X86::VFNMADD213SSZr_Intkz:
5110  case X86::VFMADD231SSZr_Intkz: case X86::VFNMADD231SSZr_Intkz:
5111  case X86::VFMSUB132SSZr_Intkz: case X86::VFNMSUB132SSZr_Intkz:
5112  case X86::VFMSUB213SSZr_Intkz: case X86::VFNMSUB213SSZr_Intkz:
5113  case X86::VFMSUB231SSZr_Intkz: case X86::VFNMSUB231SSZr_Intkz:
5114  return false;
5115  default:
5116  return true;
5117  }
5118  }
5119 
5120  if ((Opc == X86::MOVSDrm || Opc == X86::VMOVSDrm || Opc == X86::VMOVSDZrm ||
5121  Opc == X86::MOVSDrm_alt || Opc == X86::VMOVSDrm_alt ||
5122  Opc == X86::VMOVSDZrm_alt) &&
5123  RegSize > 64) {
5124  // These instructions only load 64 bits, we can't fold them if the
5125  // destination register is wider than 64 bits (8 bytes), and its user
5126  // instruction isn't scalar (SD).
5127  switch (UserOpc) {
5128  case X86::ADDSDrr_Int: case X86::VADDSDrr_Int: case X86::VADDSDZrr_Int:
5129  case X86::CMPSDrr_Int: case X86::VCMPSDrr_Int: case X86::VCMPSDZrr_Int:
5130  case X86::DIVSDrr_Int: case X86::VDIVSDrr_Int: case X86::VDIVSDZrr_Int:
5131  case X86::MAXSDrr_Int: case X86::VMAXSDrr_Int: case X86::VMAXSDZrr_Int:
5132  case X86::MINSDrr_Int: case X86::VMINSDrr_Int: case X86::VMINSDZrr_Int:
5133  case X86::MULSDrr_Int: case X86::VMULSDrr_Int: case X86::VMULSDZrr_Int:
5134  case X86::SUBSDrr_Int: case X86::VSUBSDrr_Int: case X86::VSUBSDZrr_Int:
5135  case X86::VADDSDZrr_Intk: case X86::VADDSDZrr_Intkz:
5136  case X86::VCMPSDZrr_Intk:
5137  case X86::VDIVSDZrr_Intk: case X86::VDIVSDZrr_Intkz:
5138  case X86::VMAXSDZrr_Intk: case X86::VMAXSDZrr_Intkz:
5139  case X86::VMINSDZrr_Intk: case X86::VMINSDZrr_Intkz:
5140  case X86::VMULSDZrr_Intk: case X86::VMULSDZrr_Intkz:
5141  case X86::VSUBSDZrr_Intk: case X86::VSUBSDZrr_Intkz:
5142  case X86::VFMADDSD4rr_Int: case X86::VFNMADDSD4rr_Int:
5143  case X86::VFMSUBSD4rr_Int: case X86::VFNMSUBSD4rr_Int:
5144  case X86::VFMADD132SDr_Int: case X86::VFNMADD132SDr_Int:
5145  case X86::VFMADD213SDr_Int: case X86::VFNMADD213SDr_Int:
5146  case X86::VFMADD231SDr_Int: case X86::VFNMADD231SDr_Int:
5147  case X86::VFMSUB132SDr_Int: case X86::VFNMSUB132SDr_Int:
5148  case X86::VFMSUB213SDr_Int: case X86::VFNMSUB213SDr_Int:
5149  case X86::VFMSUB231SDr_Int: case X86::VFNMSUB231SDr_Int:
5150  case X86::VFMADD132SDZr_Int: case X86::VFNMADD132SDZr_Int:
5151  case X86::VFMADD213SDZr_Int: case X86::VFNMADD213SDZr_Int:
5152  case X86::VFMADD231SDZr_Int: case X86::VFNMADD231SDZr_Int:
5153  case X86::VFMSUB132SDZr_Int: case X86::VFNMSUB132SDZr_Int:
5154  case X86::VFMSUB213SDZr_Int: case X86::VFNMSUB213SDZr_Int:
5155  case X86::VFMSUB231SDZr_Int: case X86::VFNMSUB231SDZr_Int:
5156  case X86::VFMADD132SDZr_Intk: case X86::VFNMADD132SDZr_Intk:
5157  case X86::VFMADD213SDZr_Intk: case X86::VFNMADD213SDZr_Intk:
5158  case X86::VFMADD231SDZr_Intk: case X86::VFNMADD231SDZr_Intk:
5159  case X86::VFMSUB132SDZr_Intk: case X86::VFNMSUB132SDZr_Intk:
5160  case X86::VFMSUB213SDZr_Intk: case X86::VFNMSUB213SDZr_Intk:
5161  case X86::VFMSUB231SDZr_Intk: case X86::VFNMSUB231SDZr_Intk:
5162  case X86::VFMADD132SDZr_Intkz: case X86::VFNMADD132SDZr_Intkz:
5163  case X86::VFMADD213SDZr_Intkz: case X86::VFNMADD213SDZr_Intkz:
5164  case X86::VFMADD231SDZr_Intkz: case X86::VFNMADD231SDZr_Intkz:
5165  case X86::VFMSUB132SDZr_Intkz: case X86::VFNMSUB132SDZr_Intkz:
5166  case X86::VFMSUB213SDZr_Intkz: case X86::VFNMSUB213SDZr_Intkz:
5167  case X86::VFMSUB231SDZr_Intkz: case X86::VFNMSUB231SDZr_Intkz:
5168  return false;
5169  default:
5170  return true;
5171  }
5172  }
5173 
5174  return false;
5175 }
5176 
5179  MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
5180  LiveIntervals *LIS) const {
5181 
5182  // TODO: Support the case where LoadMI loads a wide register, but MI
5183  // only uses a subreg.
5184  for (auto Op : Ops) {
5185  if (MI.getOperand(Op).getSubReg())
5186  return nullptr;
5187  }
5188 
5189  // If loading from a FrameIndex, fold directly from the FrameIndex.
5190  unsigned NumOps = LoadMI.getDesc().getNumOperands();
5191  int FrameIndex;
5192  if (isLoadFromStackSlot(LoadMI, FrameIndex)) {
5193  if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
5194  return nullptr;
5195  return foldMemoryOperandImpl(MF, MI, Ops, InsertPt, FrameIndex, LIS);
5196  }
5197 
5198  // Check switch flag
5199  if (NoFusing) return nullptr;
5200 
5201  // Avoid partial and undef register update stalls unless optimizing for size.
5202  if (!MF.getFunction().hasOptSize() &&
5203  (hasPartialRegUpdate(MI.getOpcode(), Subtarget, /*ForLoadFold*/true) ||
5205  return nullptr;
5206 
5207  // Determine the alignment of the load.
5208  unsigned Alignment = 0;
5209  if (LoadMI.hasOneMemOperand())
5210  Alignment = (*LoadMI.memoperands_begin())->getAlignment();
5211  else
5212  switch (LoadMI.getOpcode()) {
5213  case X86::AVX512_512_SET0:
5214  case X86::AVX512_512_SETALLONES:
5215  Alignment = 64;
5216  break;
5217  case X86::AVX2_SETALLONES:
5218  case X86::AVX1_SETALLONES:
5219  case X86::AVX_SET0:
5220  case X86::AVX512_256_SET0:
5221  Alignment = 32;
5222  break;
5223  case X86::V_SET0:
5224  case X86::V_SETALLONES:
5225  case X86::AVX512_128_SET0:
5226  case X86::FsFLD0F128:
5227  case X86::AVX512_FsFLD0F128:
5228  Alignment = 16;
5229  break;
5230  case X86::MMX_SET0:
5231  case X86::FsFLD0SD:
5232  case X86::AVX512_FsFLD0SD:
5233  Alignment = 8;
5234  break;
5235  case X86::FsFLD0SS:
5236  case X86::AVX512_FsFLD0SS:
5237  Alignment = 4;
5238  break;
5239  default:
5240  return nullptr;
5241  }
5242  if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
5243  unsigned NewOpc = 0;
5244  switch (MI.getOpcode()) {
5245  default: return nullptr;
5246  case X86::TEST8rr: NewOpc = X86::CMP8ri; break;
5247  case X86::TEST16rr: NewOpc = X86::CMP16ri8; break;
5248  case X86::TEST32rr: NewOpc = X86::CMP32ri8; break;
5249  case X86::TEST64rr: NewOpc = X86::CMP64ri8; break;
5250  }
5251  // Change to CMPXXri r, 0 first.
5252  MI.setDesc(get(NewOpc));
5253  MI.getOperand(1).ChangeToImmediate(0);
5254  } else if (Ops.size() != 1)
5255  return nullptr;
5256 
5257  // Make sure the subregisters match.
5258  // Otherwise we risk changing the size of the load.
5259  if (LoadMI.getOperand(0).getSubReg() != MI.getOperand(Ops[0]).getSubReg())
5260  return nullptr;
5261 
5263  switch (LoadMI.getOpcode()) {
5264  case X86::MMX_SET0:
5265  case X86::V_SET0:
5266  case X86::V_SETALLONES:
5267  case X86::AVX2_SETALLONES:
5268  case X86::AVX1_SETALLONES:
5269  case X86::AVX_SET0:
5270  case X86::AVX512_128_SET0:
5271  case X86::AVX512_256_SET0:
5272  case X86::AVX512_512_SET0:
5273  case X86::AVX512_512_SETALLONES:
5274  case X86::FsFLD0SD:
5275  case X86::AVX512_FsFLD0SD:
5276  case X86::FsFLD0SS:
5277  case X86::AVX512_FsFLD0SS:
5278  case X86::FsFLD0F128:
5279  case X86::AVX512_FsFLD0F128: {
5280  // Folding a V_SET0 or V_SETALLONES as a load, to ease register pressure.
5281  // Create a constant-pool entry and operands to load from it.
5282 
5283  // Medium and large mode can't fold loads this way.
5284  if (MF.getTarget().getCodeModel() != CodeModel::Small &&
5286  return nullptr;
5287 
5288  // x86-32 PIC requires a PIC base register for constant pools.
5289  unsigned PICBase = 0;
5290  if (MF.getTarget().isPositionIndependent()) {
5291  if (Subtarget.is64Bit())
5292  PICBase = X86::RIP;
5293  else
5294  // FIXME: PICBase = getGlobalBaseReg(&MF);
5295  // This doesn't work for several reasons.
5296  // 1. GlobalBaseReg may have been spilled.
5297  // 2. It may not be live at MI.
5298  return nullptr;
5299  }
5300 
5301  // Create a constant-pool entry.
5302  MachineConstantPool &MCP = *MF.getConstantPool();
5303  Type *Ty;
5304  unsigned Opc = LoadMI.getOpcode();
5305  if (Opc == X86::FsFLD0SS || Opc == X86::AVX512_FsFLD0SS)
5307  else if (Opc == X86::FsFLD0SD || Opc == X86::AVX512_FsFLD0SD)
5309  else if (Opc == X86::FsFLD0F128 || Opc == X86::AVX512_FsFLD0F128)
5311  else if (Opc == X86::AVX512_512_SET0 || Opc == X86::AVX512_512_SETALLONES)
5313  else if (Opc == X86::AVX2_SETALLONES || Opc == X86::AVX_SET0 ||
5314  Opc == X86::AVX512_256_SET0 || Opc == X86::AVX1_SETALLONES)
5316  else if (Opc == X86::MMX_SET0)
5318  else
5320 
5321  bool IsAllOnes = (Opc == X86::V_SETALLONES || Opc == X86::AVX2_SETALLONES ||
5322  Opc == X86::AVX512_512_SETALLONES ||
5323  Opc == X86::AVX1_SETALLONES);
5324  const Constant *C = IsAllOnes ? Constant::getAllOnesValue(Ty) :
5326  unsigned CPI = MCP.getConstantPoolIndex(C, Alignment);
5327 
5328  // Create operands to load from the constant pool entry.
5329  MOs.push_back(MachineOperand::CreateReg(PICBase, false));
5331  MOs.push_back(MachineOperand::CreateReg(0, false));
5332  MOs.push_back(MachineOperand::CreateCPI(CPI, 0));
5333  MOs.push_back(MachineOperand::CreateReg(0, false));
5334  break;
5335  }
5336  default: {
5337  if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
5338  return nullptr;
5339 
5340  // Folding a normal load. Just copy the load's address operands.
5341  MOs.append(LoadMI.operands_begin() + NumOps - X86::AddrNumOperands,
5342  LoadMI.operands_begin() + NumOps);
5343  break;
5344  }
5345  }
5346  return foldMemoryOperandImpl(MF, MI, Ops[0], MOs, InsertPt,
5347  /*Size=*/0, Alignment, /*AllowCommute=*/true);
5348 }
5349 
5353 
5354  for (MachineMemOperand *MMO : MMOs) {
5355  if (!MMO->isLoad())
5356  continue;
5357 
5358  if (!MMO->isStore()) {
5359  // Reuse the MMO.
5360  LoadMMOs.push_back(MMO);
5361  } else {
5362  // Clone the MMO and unset the store flag.
5363  LoadMMOs.push_back(MF.getMachineMemOperand(
5364  MMO, MMO->getFlags() & ~MachineMemOperand::MOStore));
5365  }
5366  }
5367 
5368  return LoadMMOs;
5369 }
5370 
5374 
5375  for (MachineMemOperand *MMO : MMOs) {
5376  if (!MMO->isStore())
5377  continue;
5378 
5379  if (!MMO->isLoad()) {
5380  // Reuse the MMO.
5381  StoreMMOs.push_back(MMO);
5382  } else {
5383  // Clone the MMO and unset the load flag.
5384  StoreMMOs.push_back(MF.getMachineMemOperand(
5385  MMO, MMO->getFlags() & ~MachineMemOperand::MOLoad));
5386  }
5387  }
5388 
5389  return StoreMMOs;
5390 }
5391 
5393  const TargetRegisterClass *RC,
5394  const X86Subtarget &STI) {
5395  assert(STI.hasAVX512() && "Expected at least AVX512!");
5396  unsigned SpillSize = STI.getRegisterInfo()->getSpillSize(*RC);
5397  assert((SpillSize == 64