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