LLVM  5.0.0
X86FastISel.cpp
Go to the documentation of this file.
1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "X86.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86RegisterInfo.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
25 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCSymbol.h"
44 using namespace llvm;
45 
46 namespace {
47 
48 class X86FastISel final : public FastISel {
49  /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50  /// make the right decision when generating code for different targets.
51  const X86Subtarget *Subtarget;
52 
53  /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54  /// floating point ops.
55  /// When SSE is available, use it for f32 operations.
56  /// When SSE2 is available, use it for f64 operations.
57  bool X86ScalarSSEf64;
58  bool X86ScalarSSEf32;
59 
60 public:
61  explicit X86FastISel(FunctionLoweringInfo &funcInfo,
62  const TargetLibraryInfo *libInfo)
63  : FastISel(funcInfo, libInfo) {
64  Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
65  X86ScalarSSEf64 = Subtarget->hasSSE2();
66  X86ScalarSSEf32 = Subtarget->hasSSE1();
67  }
68 
69  bool fastSelectInstruction(const Instruction *I) override;
70 
71  /// \brief The specified machine instr operand is a vreg, and that
72  /// vreg is being provided by the specified load instruction. If possible,
73  /// try to fold the load as an operand to the instruction, returning true if
74  /// possible.
75  bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76  const LoadInst *LI) override;
77 
78  bool fastLowerArguments() override;
79  bool fastLowerCall(CallLoweringInfo &CLI) override;
80  bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81 
82 #include "X86GenFastISel.inc"
83 
84 private:
85  bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
86  const DebugLoc &DL);
87 
88  bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
89  unsigned &ResultReg, unsigned Alignment = 1);
90 
91  bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
92  MachineMemOperand *MMO = nullptr, bool Aligned = false);
93  bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
94  X86AddressMode &AM,
95  MachineMemOperand *MMO = nullptr, bool Aligned = false);
96 
97  bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98  unsigned &ResultReg);
99 
100  bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101  bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
102 
103  bool X86SelectLoad(const Instruction *I);
104 
105  bool X86SelectStore(const Instruction *I);
106 
107  bool X86SelectRet(const Instruction *I);
108 
109  bool X86SelectCmp(const Instruction *I);
110 
111  bool X86SelectZExt(const Instruction *I);
112 
113  bool X86SelectBranch(const Instruction *I);
114 
115  bool X86SelectShift(const Instruction *I);
116 
117  bool X86SelectDivRem(const Instruction *I);
118 
119  bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
120 
121  bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
122 
123  bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
124 
125  bool X86SelectSelect(const Instruction *I);
126 
127  bool X86SelectTrunc(const Instruction *I);
128 
129  bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130  const TargetRegisterClass *RC);
131 
132  bool X86SelectFPExt(const Instruction *I);
133  bool X86SelectFPTrunc(const Instruction *I);
134  bool X86SelectSIToFP(const Instruction *I);
135 
136  const X86InstrInfo *getInstrInfo() const {
137  return Subtarget->getInstrInfo();
138  }
139  const X86TargetMachine *getTargetMachine() const {
140  return static_cast<const X86TargetMachine *>(&TM);
141  }
142 
143  bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
144 
145  unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
146  unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
147  unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
148  unsigned fastMaterializeConstant(const Constant *C) override;
149 
150  unsigned fastMaterializeAlloca(const AllocaInst *C) override;
151 
152  unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
153 
154  /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155  /// computed in an SSE register, not on the X87 floating point stack.
156  bool isScalarFPTypeInSSEReg(EVT VT) const {
157  return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158  (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
159  }
160 
161  bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
162 
163  bool IsMemcpySmall(uint64_t Len);
164 
165  bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166  X86AddressMode SrcAM, uint64_t Len);
167 
168  bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
169  const Value *Cond);
170 
172  X86AddressMode &AM);
173 
174  unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
175  const TargetRegisterClass *RC, unsigned Op0,
176  bool Op0IsKill, unsigned Op1, bool Op1IsKill,
177  unsigned Op2, bool Op2IsKill, unsigned Op3,
178  bool Op3IsKill);
179 };
180 
181 } // end anonymous namespace.
182 
183 static std::pair<unsigned, bool>
185  unsigned CC;
186  bool NeedSwap = false;
187 
188  // SSE Condition code mapping:
189  // 0 - EQ
190  // 1 - LT
191  // 2 - LE
192  // 3 - UNORD
193  // 4 - NEQ
194  // 5 - NLT
195  // 6 - NLE
196  // 7 - ORD
197  switch (Predicate) {
198  default: llvm_unreachable("Unexpected predicate");
199  case CmpInst::FCMP_OEQ: CC = 0; break;
200  case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
201  case CmpInst::FCMP_OLT: CC = 1; break;
202  case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
203  case CmpInst::FCMP_OLE: CC = 2; break;
204  case CmpInst::FCMP_UNO: CC = 3; break;
205  case CmpInst::FCMP_UNE: CC = 4; break;
206  case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
207  case CmpInst::FCMP_UGE: CC = 5; break;
208  case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
209  case CmpInst::FCMP_UGT: CC = 6; break;
210  case CmpInst::FCMP_ORD: CC = 7; break;
211  case CmpInst::FCMP_UEQ:
212  case CmpInst::FCMP_ONE: CC = 8; break;
213  }
214 
215  return std::make_pair(CC, NeedSwap);
216 }
217 
218 /// \brief Adds a complex addressing mode to the given machine instr builder.
219 /// Note, this will constrain the index register. If its not possible to
220 /// constrain the given index register, then a new one will be created. The
221 /// IndexReg field of the addressing mode will be updated to match in this case.
222 const MachineInstrBuilder &
224  X86AddressMode &AM) {
225  // First constrain the index register. It needs to be a GR64_NOSP.
227  MIB->getNumOperands() +
229  return ::addFullAddress(MIB, AM);
230 }
231 
232 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
233 /// into the user. The condition code will only be updated on success.
234 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
235  const Value *Cond) {
236  if (!isa<ExtractValueInst>(Cond))
237  return false;
238 
239  const auto *EV = cast<ExtractValueInst>(Cond);
240  if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
241  return false;
242 
243  const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
244  MVT RetVT;
245  const Function *Callee = II->getCalledFunction();
246  Type *RetTy =
247  cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
248  if (!isTypeLegal(RetTy, RetVT))
249  return false;
250 
251  if (RetVT != MVT::i32 && RetVT != MVT::i64)
252  return false;
253 
254  X86::CondCode TmpCC;
255  switch (II->getIntrinsicID()) {
256  default: return false;
257  case Intrinsic::sadd_with_overflow:
258  case Intrinsic::ssub_with_overflow:
259  case Intrinsic::smul_with_overflow:
260  case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
261  case Intrinsic::uadd_with_overflow:
262  case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
263  }
264 
265  // Check if both instructions are in the same basic block.
266  if (II->getParent() != I->getParent())
267  return false;
268 
269  // Make sure nothing is in the way
272  for (auto Itr = std::prev(Start); Itr != End; --Itr) {
273  // We only expect extractvalue instructions between the intrinsic and the
274  // instruction to be selected.
275  if (!isa<ExtractValueInst>(Itr))
276  return false;
277 
278  // Check that the extractvalue operand comes from the intrinsic.
279  const auto *EVI = cast<ExtractValueInst>(Itr);
280  if (EVI->getAggregateOperand() != II)
281  return false;
282  }
283 
284  CC = TmpCC;
285  return true;
286 }
287 
288 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
289  EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
290  if (evt == MVT::Other || !evt.isSimple())
291  // Unhandled type. Halt "fast" selection and bail.
292  return false;
293 
294  VT = evt.getSimpleVT();
295  // For now, require SSE/SSE2 for performing floating-point operations,
296  // since x87 requires additional work.
297  if (VT == MVT::f64 && !X86ScalarSSEf64)
298  return false;
299  if (VT == MVT::f32 && !X86ScalarSSEf32)
300  return false;
301  // Similarly, no f80 support yet.
302  if (VT == MVT::f80)
303  return false;
304  // We only handle legal types. For example, on x86-32 the instruction
305  // selector contains all of the 64-bit instructions from x86-64,
306  // under the assumption that i64 won't be used if the target doesn't
307  // support it.
308  return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
309 }
310 
311 #include "X86GenCallingConv.inc"
312 
313 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
314 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
315 /// Return true and the result register by reference if it is possible.
316 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
317  MachineMemOperand *MMO, unsigned &ResultReg,
318  unsigned Alignment) {
319  bool HasSSE41 = Subtarget->hasSSE41();
320  bool HasAVX = Subtarget->hasAVX();
321  bool HasAVX2 = Subtarget->hasAVX2();
322  bool HasAVX512 = Subtarget->hasAVX512();
323  bool HasVLX = Subtarget->hasVLX();
324  bool IsNonTemporal = MMO && MMO->isNonTemporal();
325 
326  // Get opcode and regclass of the output for the given load instruction.
327  unsigned Opc = 0;
328  const TargetRegisterClass *RC = nullptr;
329  switch (VT.getSimpleVT().SimpleTy) {
330  default: return false;
331  case MVT::i1:
332  // TODO: Support this properly.
333  if (Subtarget->hasAVX512())
334  return false;
336  case MVT::i8:
337  Opc = X86::MOV8rm;
338  RC = &X86::GR8RegClass;
339  break;
340  case MVT::i16:
341  Opc = X86::MOV16rm;
342  RC = &X86::GR16RegClass;
343  break;
344  case MVT::i32:
345  Opc = X86::MOV32rm;
346  RC = &X86::GR32RegClass;
347  break;
348  case MVT::i64:
349  // Must be in x86-64 mode.
350  Opc = X86::MOV64rm;
351  RC = &X86::GR64RegClass;
352  break;
353  case MVT::f32:
354  if (X86ScalarSSEf32) {
355  Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
356  RC = &X86::FR32RegClass;
357  } else {
358  Opc = X86::LD_Fp32m;
359  RC = &X86::RFP32RegClass;
360  }
361  break;
362  case MVT::f64:
363  if (X86ScalarSSEf64) {
364  Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
365  RC = &X86::FR64RegClass;
366  } else {
367  Opc = X86::LD_Fp64m;
368  RC = &X86::RFP64RegClass;
369  }
370  break;
371  case MVT::f80:
372  // No f80 support yet.
373  return false;
374  case MVT::v4f32:
375  if (IsNonTemporal && Alignment >= 16 && HasSSE41)
376  Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
377  HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
378  else if (Alignment >= 16)
379  Opc = HasVLX ? X86::VMOVAPSZ128rm :
380  HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
381  else
382  Opc = HasVLX ? X86::VMOVUPSZ128rm :
383  HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
384  RC = &X86::VR128RegClass;
385  break;
386  case MVT::v2f64:
387  if (IsNonTemporal && Alignment >= 16 && HasSSE41)
388  Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
389  HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
390  else if (Alignment >= 16)
391  Opc = HasVLX ? X86::VMOVAPDZ128rm :
392  HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
393  else
394  Opc = HasVLX ? X86::VMOVUPDZ128rm :
395  HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
396  RC = &X86::VR128RegClass;
397  break;
398  case MVT::v4i32:
399  case MVT::v2i64:
400  case MVT::v8i16:
401  case MVT::v16i8:
402  if (IsNonTemporal && Alignment >= 16)
403  Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
404  HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
405  else if (Alignment >= 16)
406  Opc = HasVLX ? X86::VMOVDQA64Z128rm :
407  HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
408  else
409  Opc = HasVLX ? X86::VMOVDQU64Z128rm :
410  HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
411  RC = &X86::VR128RegClass;
412  break;
413  case MVT::v8f32:
414  assert(HasAVX);
415  if (IsNonTemporal && Alignment >= 32 && HasAVX2)
416  Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
417  else if (IsNonTemporal && Alignment >= 16)
418  return false; // Force split for X86::VMOVNTDQArm
419  else if (Alignment >= 32)
420  Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
421  else
422  Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
423  RC = &X86::VR256RegClass;
424  break;
425  case MVT::v4f64:
426  assert(HasAVX);
427  if (IsNonTemporal && Alignment >= 32 && HasAVX2)
428  Opc = X86::VMOVNTDQAYrm;
429  else if (IsNonTemporal && Alignment >= 16)
430  return false; // Force split for X86::VMOVNTDQArm
431  else if (Alignment >= 32)
432  Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
433  else
434  Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
435  RC = &X86::VR256RegClass;
436  break;
437  case MVT::v8i32:
438  case MVT::v4i64:
439  case MVT::v16i16:
440  case MVT::v32i8:
441  assert(HasAVX);
442  if (IsNonTemporal && Alignment >= 32 && HasAVX2)
443  Opc = X86::VMOVNTDQAYrm;
444  else if (IsNonTemporal && Alignment >= 16)
445  return false; // Force split for X86::VMOVNTDQArm
446  else if (Alignment >= 32)
447  Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
448  else
449  Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
450  RC = &X86::VR256RegClass;
451  break;
452  case MVT::v16f32:
453  assert(HasAVX512);
454  if (IsNonTemporal && Alignment >= 64)
455  Opc = X86::VMOVNTDQAZrm;
456  else
457  Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
458  RC = &X86::VR512RegClass;
459  break;
460  case MVT::v8f64:
461  assert(HasAVX512);
462  if (IsNonTemporal && Alignment >= 64)
463  Opc = X86::VMOVNTDQAZrm;
464  else
465  Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
466  RC = &X86::VR512RegClass;
467  break;
468  case MVT::v8i64:
469  case MVT::v16i32:
470  case MVT::v32i16:
471  case MVT::v64i8:
472  assert(HasAVX512);
473  // Note: There are a lot more choices based on type with AVX-512, but
474  // there's really no advantage when the load isn't masked.
475  if (IsNonTemporal && Alignment >= 64)
476  Opc = X86::VMOVNTDQAZrm;
477  else
478  Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
479  RC = &X86::VR512RegClass;
480  break;
481  }
482 
483  ResultReg = createResultReg(RC);
484  MachineInstrBuilder MIB =
485  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
486  addFullAddress(MIB, AM);
487  if (MMO)
488  MIB->addMemOperand(*FuncInfo.MF, MMO);
489  return true;
490 }
491 
492 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
493 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
494 /// and a displacement offset, or a GlobalAddress,
495 /// i.e. V. Return true if it is possible.
496 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
497  X86AddressMode &AM,
498  MachineMemOperand *MMO, bool Aligned) {
499  bool HasSSE1 = Subtarget->hasSSE1();
500  bool HasSSE2 = Subtarget->hasSSE2();
501  bool HasSSE4A = Subtarget->hasSSE4A();
502  bool HasAVX = Subtarget->hasAVX();
503  bool HasAVX512 = Subtarget->hasAVX512();
504  bool HasVLX = Subtarget->hasVLX();
505  bool IsNonTemporal = MMO && MMO->isNonTemporal();
506 
507  // Get opcode and regclass of the output for the given store instruction.
508  unsigned Opc = 0;
509  switch (VT.getSimpleVT().SimpleTy) {
510  case MVT::f80: // No f80 support yet.
511  default: return false;
512  case MVT::i1: {
513  // In case ValReg is a K register, COPY to a GPR
514  if (MRI.getRegClass(ValReg) == &X86::VK1RegClass) {
515  unsigned KValReg = ValReg;
516  ValReg = createResultReg(&X86::GR32RegClass);
517  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
518  TII.get(TargetOpcode::COPY), ValReg)
519  .addReg(KValReg);
520  ValReg = fastEmitInst_extractsubreg(MVT::i8, ValReg, /*Kill=*/true,
521  X86::sub_8bit);
522  }
523  // Mask out all but lowest bit.
524  unsigned AndResult = createResultReg(&X86::GR8RegClass);
525  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
526  TII.get(X86::AND8ri), AndResult)
527  .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
528  ValReg = AndResult;
529  LLVM_FALLTHROUGH; // handle i1 as i8.
530  }
531  case MVT::i8: Opc = X86::MOV8mr; break;
532  case MVT::i16: Opc = X86::MOV16mr; break;
533  case MVT::i32:
534  Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
535  break;
536  case MVT::i64:
537  // Must be in x86-64 mode.
538  Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
539  break;
540  case MVT::f32:
541  if (X86ScalarSSEf32) {
542  if (IsNonTemporal && HasSSE4A)
543  Opc = X86::MOVNTSS;
544  else
545  Opc = HasAVX512 ? X86::VMOVSSZmr :
546  HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
547  } else
548  Opc = X86::ST_Fp32m;
549  break;
550  case MVT::f64:
551  if (X86ScalarSSEf32) {
552  if (IsNonTemporal && HasSSE4A)
553  Opc = X86::MOVNTSD;
554  else
555  Opc = HasAVX512 ? X86::VMOVSDZmr :
556  HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
557  } else
558  Opc = X86::ST_Fp64m;
559  break;
560  case MVT::x86mmx:
561  Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
562  break;
563  case MVT::v4f32:
564  if (Aligned) {
565  if (IsNonTemporal)
566  Opc = HasVLX ? X86::VMOVNTPSZ128mr :
567  HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
568  else
569  Opc = HasVLX ? X86::VMOVAPSZ128mr :
570  HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
571  } else
572  Opc = HasVLX ? X86::VMOVUPSZ128mr :
573  HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
574  break;
575  case MVT::v2f64:
576  if (Aligned) {
577  if (IsNonTemporal)
578  Opc = HasVLX ? X86::VMOVNTPDZ128mr :
579  HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
580  else
581  Opc = HasVLX ? X86::VMOVAPDZ128mr :
582  HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
583  } else
584  Opc = HasVLX ? X86::VMOVUPDZ128mr :
585  HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
586  break;
587  case MVT::v4i32:
588  case MVT::v2i64:
589  case MVT::v8i16:
590  case MVT::v16i8:
591  if (Aligned) {
592  if (IsNonTemporal)
593  Opc = HasVLX ? X86::VMOVNTDQZ128mr :
594  HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
595  else
596  Opc = HasVLX ? X86::VMOVDQA64Z128mr :
597  HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
598  } else
599  Opc = HasVLX ? X86::VMOVDQU64Z128mr :
600  HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
601  break;
602  case MVT::v8f32:
603  assert(HasAVX);
604  if (Aligned) {
605  if (IsNonTemporal)
606  Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
607  else
608  Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
609  } else
610  Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
611  break;
612  case MVT::v4f64:
613  assert(HasAVX);
614  if (Aligned) {
615  if (IsNonTemporal)
616  Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
617  else
618  Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
619  } else
620  Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
621  break;
622  case MVT::v8i32:
623  case MVT::v4i64:
624  case MVT::v16i16:
625  case MVT::v32i8:
626  assert(HasAVX);
627  if (Aligned) {
628  if (IsNonTemporal)
629  Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
630  else
631  Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
632  } else
633  Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
634  break;
635  case MVT::v16f32:
636  assert(HasAVX512);
637  if (Aligned)
638  Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
639  else
640  Opc = X86::VMOVUPSZmr;
641  break;
642  case MVT::v8f64:
643  assert(HasAVX512);
644  if (Aligned) {
645  Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
646  } else
647  Opc = X86::VMOVUPDZmr;
648  break;
649  case MVT::v8i64:
650  case MVT::v16i32:
651  case MVT::v32i16:
652  case MVT::v64i8:
653  assert(HasAVX512);
654  // Note: There are a lot more choices based on type with AVX-512, but
655  // there's really no advantage when the store isn't masked.
656  if (Aligned)
657  Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
658  else
659  Opc = X86::VMOVDQU64Zmr;
660  break;
661  }
662 
663  const MCInstrDesc &Desc = TII.get(Opc);
664  // Some of the instructions in the previous switch use FR128 instead
665  // of FR32 for ValReg. Make sure the register we feed the instruction
666  // matches its register class constraints.
667  // Note: This is fine to do a copy from FR32 to FR128, this is the
668  // same registers behind the scene and actually why it did not trigger
669  // any bugs before.
670  ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
671  MachineInstrBuilder MIB =
672  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
673  addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
674  if (MMO)
675  MIB->addMemOperand(*FuncInfo.MF, MMO);
676 
677  return true;
678 }
679 
680 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
681  X86AddressMode &AM,
682  MachineMemOperand *MMO, bool Aligned) {
683  // Handle 'null' like i32/i64 0.
684  if (isa<ConstantPointerNull>(Val))
686 
687  // If this is a store of a simple constant, fold the constant into the store.
688  if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
689  unsigned Opc = 0;
690  bool Signed = true;
691  switch (VT.getSimpleVT().SimpleTy) {
692  default: break;
693  case MVT::i1:
694  Signed = false;
695  LLVM_FALLTHROUGH; // Handle as i8.
696  case MVT::i8: Opc = X86::MOV8mi; break;
697  case MVT::i16: Opc = X86::MOV16mi; break;
698  case MVT::i32: Opc = X86::MOV32mi; break;
699  case MVT::i64:
700  // Must be a 32-bit sign extended value.
701  if (isInt<32>(CI->getSExtValue()))
702  Opc = X86::MOV64mi32;
703  break;
704  }
705 
706  if (Opc) {
707  MachineInstrBuilder MIB =
708  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
709  addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
710  : CI->getZExtValue());
711  if (MMO)
712  MIB->addMemOperand(*FuncInfo.MF, MMO);
713  return true;
714  }
715  }
716 
717  unsigned ValReg = getRegForValue(Val);
718  if (ValReg == 0)
719  return false;
720 
721  bool ValKill = hasTrivialKill(Val);
722  return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
723 }
724 
725 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
726 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
727 /// ISD::SIGN_EXTEND).
728 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
729  unsigned Src, EVT SrcVT,
730  unsigned &ResultReg) {
731  unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
732  Src, /*TODO: Kill=*/false);
733  if (RR == 0)
734  return false;
735 
736  ResultReg = RR;
737  return true;
738 }
739 
740 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
741  // Handle constant address.
742  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
743  // Can't handle alternate code models yet.
744  if (TM.getCodeModel() != CodeModel::Small)
745  return false;
746 
747  // Can't handle TLS yet.
748  if (GV->isThreadLocal())
749  return false;
750 
751  // RIP-relative addresses can't have additional register operands, so if
752  // we've already folded stuff into the addressing mode, just force the
753  // global value into its own register, which we can use as the basereg.
754  if (!Subtarget->isPICStyleRIPRel() ||
755  (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
756  // Okay, we've committed to selecting this global. Set up the address.
757  AM.GV = GV;
758 
759  // Allow the subtarget to classify the global.
760  unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
761 
762  // If this reference is relative to the pic base, set it now.
763  if (isGlobalRelativeToPICBase(GVFlags)) {
764  // FIXME: How do we know Base.Reg is free??
765  AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
766  }
767 
768  // Unless the ABI requires an extra load, return a direct reference to
769  // the global.
770  if (!isGlobalStubReference(GVFlags)) {
771  if (Subtarget->isPICStyleRIPRel()) {
772  // Use rip-relative addressing if we can. Above we verified that the
773  // base and index registers are unused.
774  assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
775  AM.Base.Reg = X86::RIP;
776  }
777  AM.GVOpFlags = GVFlags;
778  return true;
779  }
780 
781  // Ok, we need to do a load from a stub. If we've already loaded from
782  // this stub, reuse the loaded pointer, otherwise emit the load now.
783  DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
784  unsigned LoadReg;
785  if (I != LocalValueMap.end() && I->second != 0) {
786  LoadReg = I->second;
787  } else {
788  // Issue load from stub.
789  unsigned Opc = 0;
790  const TargetRegisterClass *RC = nullptr;
791  X86AddressMode StubAM;
792  StubAM.Base.Reg = AM.Base.Reg;
793  StubAM.GV = GV;
794  StubAM.GVOpFlags = GVFlags;
795 
796  // Prepare for inserting code in the local-value area.
797  SavePoint SaveInsertPt = enterLocalValueArea();
798 
799  if (TLI.getPointerTy(DL) == MVT::i64) {
800  Opc = X86::MOV64rm;
801  RC = &X86::GR64RegClass;
802 
803  if (Subtarget->isPICStyleRIPRel())
804  StubAM.Base.Reg = X86::RIP;
805  } else {
806  Opc = X86::MOV32rm;
807  RC = &X86::GR32RegClass;
808  }
809 
810  LoadReg = createResultReg(RC);
811  MachineInstrBuilder LoadMI =
812  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
813  addFullAddress(LoadMI, StubAM);
814 
815  // Ok, back to normal mode.
816  leaveLocalValueArea(SaveInsertPt);
817 
818  // Prevent loading GV stub multiple times in same MBB.
819  LocalValueMap[V] = LoadReg;
820  }
821 
822  // Now construct the final address. Note that the Disp, Scale,
823  // and Index values may already be set here.
824  AM.Base.Reg = LoadReg;
825  AM.GV = nullptr;
826  return true;
827  }
828  }
829 
830  // If all else fails, try to materialize the value in a register.
831  if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
832  if (AM.Base.Reg == 0) {
833  AM.Base.Reg = getRegForValue(V);
834  return AM.Base.Reg != 0;
835  }
836  if (AM.IndexReg == 0) {
837  assert(AM.Scale == 1 && "Scale with no index!");
838  AM.IndexReg = getRegForValue(V);
839  return AM.IndexReg != 0;
840  }
841  }
842 
843  return false;
844 }
845 
846 /// X86SelectAddress - Attempt to fill in an address from the given value.
847 ///
850 redo_gep:
851  const User *U = nullptr;
852  unsigned Opcode = Instruction::UserOp1;
853  if (const Instruction *I = dyn_cast<Instruction>(V)) {
854  // Don't walk into other basic blocks; it's possible we haven't
855  // visited them yet, so the instructions may not yet be assigned
856  // virtual registers.
857  if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
858  FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
859  Opcode = I->getOpcode();
860  U = I;
861  }
862  } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
863  Opcode = C->getOpcode();
864  U = C;
865  }
866 
867  if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
868  if (Ty->getAddressSpace() > 255)
869  // Fast instruction selection doesn't support the special
870  // address spaces.
871  return false;
872 
873  switch (Opcode) {
874  default: break;
875  case Instruction::BitCast:
876  // Look past bitcasts.
877  return X86SelectAddress(U->getOperand(0), AM);
878 
879  case Instruction::IntToPtr:
880  // Look past no-op inttoptrs.
881  if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
882  TLI.getPointerTy(DL))
883  return X86SelectAddress(U->getOperand(0), AM);
884  break;
885 
886  case Instruction::PtrToInt:
887  // Look past no-op ptrtoints.
888  if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
889  return X86SelectAddress(U->getOperand(0), AM);
890  break;
891 
892  case Instruction::Alloca: {
893  // Do static allocas.
894  const AllocaInst *A = cast<AllocaInst>(V);
896  FuncInfo.StaticAllocaMap.find(A);
897  if (SI != FuncInfo.StaticAllocaMap.end()) {
899  AM.Base.FrameIndex = SI->second;
900  return true;
901  }
902  break;
903  }
904 
905  case Instruction::Add: {
906  // Adds of constants are common and easy enough.
907  if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
908  uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
909  // They have to fit in the 32-bit signed displacement field though.
910  if (isInt<32>(Disp)) {
911  AM.Disp = (uint32_t)Disp;
912  return X86SelectAddress(U->getOperand(0), AM);
913  }
914  }
915  break;
916  }
917 
918  case Instruction::GetElementPtr: {
919  X86AddressMode SavedAM = AM;
920 
921  // Pattern-match simple GEPs.
922  uint64_t Disp = (int32_t)AM.Disp;
923  unsigned IndexReg = AM.IndexReg;
924  unsigned Scale = AM.Scale;
926  // Iterate through the indices, folding what we can. Constants can be
927  // folded, and one dynamic index can be handled, if the scale is supported.
928  for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
929  i != e; ++i, ++GTI) {
930  const Value *Op = *i;
931  if (StructType *STy = GTI.getStructTypeOrNull()) {
932  const StructLayout *SL = DL.getStructLayout(STy);
933  Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
934  continue;
935  }
936 
937  // A array/variable index is always of the form i*S where S is the
938  // constant scale size. See if we can push the scale into immediates.
939  uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
940  for (;;) {
941  if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
942  // Constant-offset addressing.
943  Disp += CI->getSExtValue() * S;
944  break;
945  }
946  if (canFoldAddIntoGEP(U, Op)) {
947  // A compatible add with a constant operand. Fold the constant.
948  ConstantInt *CI =
949  cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
950  Disp += CI->getSExtValue() * S;
951  // Iterate on the other operand.
952  Op = cast<AddOperator>(Op)->getOperand(0);
953  continue;
954  }
955  if (IndexReg == 0 &&
956  (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
957  (S == 1 || S == 2 || S == 4 || S == 8)) {
958  // Scaled-index addressing.
959  Scale = S;
960  IndexReg = getRegForGEPIndex(Op).first;
961  if (IndexReg == 0)
962  return false;
963  break;
964  }
965  // Unsupported.
966  goto unsupported_gep;
967  }
968  }
969 
970  // Check for displacement overflow.
971  if (!isInt<32>(Disp))
972  break;
973 
974  AM.IndexReg = IndexReg;
975  AM.Scale = Scale;
976  AM.Disp = (uint32_t)Disp;
977  GEPs.push_back(V);
978 
979  if (const GetElementPtrInst *GEP =
980  dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
981  // Ok, the GEP indices were covered by constant-offset and scaled-index
982  // addressing. Update the address state and move on to examining the base.
983  V = GEP;
984  goto redo_gep;
985  } else if (X86SelectAddress(U->getOperand(0), AM)) {
986  return true;
987  }
988 
989  // If we couldn't merge the gep value into this addr mode, revert back to
990  // our address and just match the value instead of completely failing.
991  AM = SavedAM;
992 
993  for (const Value *I : reverse(GEPs))
994  if (handleConstantAddresses(I, AM))
995  return true;
996 
997  return false;
998  unsupported_gep:
999  // Ok, the GEP indices weren't all covered.
1000  break;
1001  }
1002  }
1003 
1004  return handleConstantAddresses(V, AM);
1005 }
1006 
1007 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
1008 ///
1009 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1010  const User *U = nullptr;
1011  unsigned Opcode = Instruction::UserOp1;
1012  const Instruction *I = dyn_cast<Instruction>(V);
1013  // Record if the value is defined in the same basic block.
1014  //
1015  // This information is crucial to know whether or not folding an
1016  // operand is valid.
1017  // Indeed, FastISel generates or reuses a virtual register for all
1018  // operands of all instructions it selects. Obviously, the definition and
1019  // its uses must use the same virtual register otherwise the produced
1020  // code is incorrect.
1021  // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1022  // registers for values that are alive across basic blocks. This ensures
1023  // that the values are consistently set between across basic block, even
1024  // if different instruction selection mechanisms are used (e.g., a mix of
1025  // SDISel and FastISel).
1026  // For values local to a basic block, the instruction selection process
1027  // generates these virtual registers with whatever method is appropriate
1028  // for its needs. In particular, FastISel and SDISel do not share the way
1029  // local virtual registers are set.
1030  // Therefore, this is impossible (or at least unsafe) to share values
1031  // between basic blocks unless they use the same instruction selection
1032  // method, which is not guarantee for X86.
1033  // Moreover, things like hasOneUse could not be used accurately, if we
1034  // allow to reference values across basic blocks whereas they are not
1035  // alive across basic blocks initially.
1036  bool InMBB = true;
1037  if (I) {
1038  Opcode = I->getOpcode();
1039  U = I;
1040  InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1041  } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1042  Opcode = C->getOpcode();
1043  U = C;
1044  }
1045 
1046  switch (Opcode) {
1047  default: break;
1048  case Instruction::BitCast:
1049  // Look past bitcasts if its operand is in the same BB.
1050  if (InMBB)
1051  return X86SelectCallAddress(U->getOperand(0), AM);
1052  break;
1053 
1054  case Instruction::IntToPtr:
1055  // Look past no-op inttoptrs if its operand is in the same BB.
1056  if (InMBB &&
1057  TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1058  TLI.getPointerTy(DL))
1059  return X86SelectCallAddress(U->getOperand(0), AM);
1060  break;
1061 
1062  case Instruction::PtrToInt:
1063  // Look past no-op ptrtoints if its operand is in the same BB.
1064  if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
1065  return X86SelectCallAddress(U->getOperand(0), AM);
1066  break;
1067  }
1068 
1069  // Handle constant address.
1070  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1071  // Can't handle alternate code models yet.
1072  if (TM.getCodeModel() != CodeModel::Small)
1073  return false;
1074 
1075  // RIP-relative addresses can't have additional register operands.
1076  if (Subtarget->isPICStyleRIPRel() &&
1077  (AM.Base.Reg != 0 || AM.IndexReg != 0))
1078  return false;
1079 
1080  // Can't handle DLL Import.
1081  if (GV->hasDLLImportStorageClass())
1082  return false;
1083 
1084  // Can't handle TLS.
1085  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1086  if (GVar->isThreadLocal())
1087  return false;
1088 
1089  // Okay, we've committed to selecting this global. Set up the basic address.
1090  AM.GV = GV;
1091 
1092  // No ABI requires an extra load for anything other than DLLImport, which
1093  // we rejected above. Return a direct reference to the global.
1094  if (Subtarget->isPICStyleRIPRel()) {
1095  // Use rip-relative addressing if we can. Above we verified that the
1096  // base and index registers are unused.
1097  assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1098  AM.Base.Reg = X86::RIP;
1099  } else {
1100  AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
1101  }
1102 
1103  return true;
1104  }
1105 
1106  // If all else fails, try to materialize the value in a register.
1107  if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1108  if (AM.Base.Reg == 0) {
1109  AM.Base.Reg = getRegForValue(V);
1110  return AM.Base.Reg != 0;
1111  }
1112  if (AM.IndexReg == 0) {
1113  assert(AM.Scale == 1 && "Scale with no index!");
1114  AM.IndexReg = getRegForValue(V);
1115  return AM.IndexReg != 0;
1116  }
1117  }
1118 
1119  return false;
1120 }
1121 
1122 
1123 /// X86SelectStore - Select and emit code to implement store instructions.
1124 bool X86FastISel::X86SelectStore(const Instruction *I) {
1125  // Atomic stores need special handling.
1126  const StoreInst *S = cast<StoreInst>(I);
1127 
1128  if (S->isAtomic())
1129  return false;
1130 
1131  const Value *PtrV = I->getOperand(1);
1132  if (TLI.supportSwiftError()) {
1133  // Swifterror values can come from either a function parameter with
1134  // swifterror attribute or an alloca with swifterror attribute.
1135  if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1136  if (Arg->hasSwiftErrorAttr())
1137  return false;
1138  }
1139 
1140  if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1141  if (Alloca->isSwiftError())
1142  return false;
1143  }
1144  }
1145 
1146  const Value *Val = S->getValueOperand();
1147  const Value *Ptr = S->getPointerOperand();
1148 
1149  MVT VT;
1150  if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1151  return false;
1152 
1153  unsigned Alignment = S->getAlignment();
1154  unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1155  if (Alignment == 0) // Ensure that codegen never sees alignment 0
1156  Alignment = ABIAlignment;
1157  bool Aligned = Alignment >= ABIAlignment;
1158 
1159  X86AddressMode AM;
1160  if (!X86SelectAddress(Ptr, AM))
1161  return false;
1162 
1163  return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1164 }
1165 
1166 /// X86SelectRet - Select and emit code to implement ret instructions.
1167 bool X86FastISel::X86SelectRet(const Instruction *I) {
1168  const ReturnInst *Ret = cast<ReturnInst>(I);
1169  const Function &F = *I->getParent()->getParent();
1170  const X86MachineFunctionInfo *X86MFInfo =
1171  FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1172 
1173  if (!FuncInfo.CanLowerReturn)
1174  return false;
1175 
1176  if (TLI.supportSwiftError() &&
1177  F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1178  return false;
1179 
1180  if (TLI.supportSplitCSR(FuncInfo.MF))
1181  return false;
1182 
1183  CallingConv::ID CC = F.getCallingConv();
1184  if (CC != CallingConv::C &&
1185  CC != CallingConv::Fast &&
1186  CC != CallingConv::X86_FastCall &&
1187  CC != CallingConv::X86_StdCall &&
1188  CC != CallingConv::X86_ThisCall &&
1189  CC != CallingConv::X86_64_SysV &&
1190  CC != CallingConv::Win64)
1191  return false;
1192 
1193  // Don't handle popping bytes if they don't fit the ret's immediate.
1194  if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
1195  return false;
1196 
1197  // fastcc with -tailcallopt is intended to provide a guaranteed
1198  // tail call optimization. Fastisel doesn't know how to do that.
1199  if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1200  return false;
1201 
1202  // Let SDISel handle vararg functions.
1203  if (F.isVarArg())
1204  return false;
1205 
1206  // Build a list of return value registers.
1207  SmallVector<unsigned, 4> RetRegs;
1208 
1209  if (Ret->getNumOperands() > 0) {
1211  GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1212 
1213  // Analyze operands of the call, assigning locations to each operand.
1215  CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1216  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1217 
1218  const Value *RV = Ret->getOperand(0);
1219  unsigned Reg = getRegForValue(RV);
1220  if (Reg == 0)
1221  return false;
1222 
1223  // Only handle a single return value for now.
1224  if (ValLocs.size() != 1)
1225  return false;
1226 
1227  CCValAssign &VA = ValLocs[0];
1228 
1229  // Don't bother handling odd stuff for now.
1230  if (VA.getLocInfo() != CCValAssign::Full)
1231  return false;
1232  // Only handle register returns for now.
1233  if (!VA.isRegLoc())
1234  return false;
1235 
1236  // The calling-convention tables for x87 returns don't tell
1237  // the whole story.
1238  if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1239  return false;
1240 
1241  unsigned SrcReg = Reg + VA.getValNo();
1242  EVT SrcVT = TLI.getValueType(DL, RV->getType());
1243  EVT DstVT = VA.getValVT();
1244  // Special handling for extended integers.
1245  if (SrcVT != DstVT) {
1246  if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1247  return false;
1248 
1249  if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1250  return false;
1251 
1252  assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1253 
1254  if (SrcVT == MVT::i1) {
1255  if (Outs[0].Flags.isSExt())
1256  return false;
1257  // In case SrcReg is a K register, COPY to a GPR
1258  if (MRI.getRegClass(SrcReg) == &X86::VK1RegClass) {
1259  unsigned KSrcReg = SrcReg;
1260  SrcReg = createResultReg(&X86::GR32RegClass);
1261  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1262  TII.get(TargetOpcode::COPY), SrcReg)
1263  .addReg(KSrcReg);
1264  SrcReg = fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
1265  X86::sub_8bit);
1266  }
1267  SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1268  SrcVT = MVT::i8;
1269  }
1270  unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1272  SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1273  SrcReg, /*TODO: Kill=*/false);
1274  }
1275 
1276  // Make the copy.
1277  unsigned DstReg = VA.getLocReg();
1278  const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1279  // Avoid a cross-class copy. This is very unlikely.
1280  if (!SrcRC->contains(DstReg))
1281  return false;
1282  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1283  TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1284 
1285  // Add register to return instruction.
1286  RetRegs.push_back(VA.getLocReg());
1287  }
1288 
1289  // Swift calling convention does not require we copy the sret argument
1290  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1291 
1292  // All x86 ABIs require that for returning structs by value we copy
1293  // the sret argument into %rax/%eax (depending on ABI) for the return.
1294  // We saved the argument into a virtual register in the entry block,
1295  // so now we copy the value out and into %rax/%eax.
1296  if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
1297  unsigned Reg = X86MFInfo->getSRetReturnReg();
1298  assert(Reg &&
1299  "SRetReturnReg should have been set in LowerFormalArguments()!");
1300  unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1301  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1302  TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1303  RetRegs.push_back(RetReg);
1304  }
1305 
1306  // Now emit the RET.
1307  MachineInstrBuilder MIB;
1308  if (X86MFInfo->getBytesToPopOnReturn()) {
1309  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1310  TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1311  .addImm(X86MFInfo->getBytesToPopOnReturn());
1312  } else {
1313  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1314  TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1315  }
1316  for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1317  MIB.addReg(RetRegs[i], RegState::Implicit);
1318  return true;
1319 }
1320 
1321 /// X86SelectLoad - Select and emit code to implement load instructions.
1322 ///
1323 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1324  const LoadInst *LI = cast<LoadInst>(I);
1325 
1326  // Atomic loads need special handling.
1327  if (LI->isAtomic())
1328  return false;
1329 
1330  const Value *SV = I->getOperand(0);
1331  if (TLI.supportSwiftError()) {
1332  // Swifterror values can come from either a function parameter with
1333  // swifterror attribute or an alloca with swifterror attribute.
1334  if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1335  if (Arg->hasSwiftErrorAttr())
1336  return false;
1337  }
1338 
1339  if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1340  if (Alloca->isSwiftError())
1341  return false;
1342  }
1343  }
1344 
1345  MVT VT;
1346  if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1347  return false;
1348 
1349  const Value *Ptr = LI->getPointerOperand();
1350 
1351  X86AddressMode AM;
1352  if (!X86SelectAddress(Ptr, AM))
1353  return false;
1354 
1355  unsigned Alignment = LI->getAlignment();
1356  unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1357  if (Alignment == 0) // Ensure that codegen never sees alignment 0
1358  Alignment = ABIAlignment;
1359 
1360  unsigned ResultReg = 0;
1361  if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1362  Alignment))
1363  return false;
1364 
1365  updateValueMap(I, ResultReg);
1366  return true;
1367 }
1368 
1369 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1370  bool HasAVX = Subtarget->hasAVX();
1371  bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1372  bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1373 
1374  switch (VT.getSimpleVT().SimpleTy) {
1375  default: return 0;
1376  case MVT::i8: return X86::CMP8rr;
1377  case MVT::i16: return X86::CMP16rr;
1378  case MVT::i32: return X86::CMP32rr;
1379  case MVT::i64: return X86::CMP64rr;
1380  case MVT::f32:
1381  return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1382  case MVT::f64:
1383  return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1384  }
1385 }
1386 
1387 /// If we have a comparison with RHS as the RHS of the comparison, return an
1388 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1389 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1390  int64_t Val = RHSC->getSExtValue();
1391  switch (VT.getSimpleVT().SimpleTy) {
1392  // Otherwise, we can't fold the immediate into this comparison.
1393  default:
1394  return 0;
1395  case MVT::i8:
1396  return X86::CMP8ri;
1397  case MVT::i16:
1398  if (isInt<8>(Val))
1399  return X86::CMP16ri8;
1400  return X86::CMP16ri;
1401  case MVT::i32:
1402  if (isInt<8>(Val))
1403  return X86::CMP32ri8;
1404  return X86::CMP32ri;
1405  case MVT::i64:
1406  if (isInt<8>(Val))
1407  return X86::CMP64ri8;
1408  // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1409  // field.
1410  if (isInt<32>(Val))
1411  return X86::CMP64ri32;
1412  return 0;
1413  }
1414 }
1415 
1416 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1417  const DebugLoc &CurDbgLoc) {
1418  unsigned Op0Reg = getRegForValue(Op0);
1419  if (Op0Reg == 0) return false;
1420 
1421  // Handle 'null' like i32/i64 0.
1422  if (isa<ConstantPointerNull>(Op1))
1424 
1425  // We have two options: compare with register or immediate. If the RHS of
1426  // the compare is an immediate that we can fold into this compare, use
1427  // CMPri, otherwise use CMPrr.
1428  if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1429  if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1430  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1431  .addReg(Op0Reg)
1432  .addImm(Op1C->getSExtValue());
1433  return true;
1434  }
1435  }
1436 
1437  unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1438  if (CompareOpc == 0) return false;
1439 
1440  unsigned Op1Reg = getRegForValue(Op1);
1441  if (Op1Reg == 0) return false;
1442  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1443  .addReg(Op0Reg)
1444  .addReg(Op1Reg);
1445 
1446  return true;
1447 }
1448 
1449 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1450  const CmpInst *CI = cast<CmpInst>(I);
1451 
1452  MVT VT;
1453  if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1454  return false;
1455 
1456  if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1457  return false;
1458 
1459  // Try to optimize or fold the cmp.
1460  CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1461  unsigned ResultReg = 0;
1462  switch (Predicate) {
1463  default: break;
1464  case CmpInst::FCMP_FALSE: {
1465  ResultReg = createResultReg(&X86::GR32RegClass);
1466  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1467  ResultReg);
1468  ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1469  X86::sub_8bit);
1470  if (!ResultReg)
1471  return false;
1472  break;
1473  }
1474  case CmpInst::FCMP_TRUE: {
1475  ResultReg = createResultReg(&X86::GR8RegClass);
1476  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1477  ResultReg).addImm(1);
1478  break;
1479  }
1480  }
1481 
1482  if (ResultReg) {
1483  updateValueMap(I, ResultReg);
1484  return true;
1485  }
1486 
1487  const Value *LHS = CI->getOperand(0);
1488  const Value *RHS = CI->getOperand(1);
1489 
1490  // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1491  // We don't have to materialize a zero constant for this case and can just use
1492  // %x again on the RHS.
1493  if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1494  const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1495  if (RHSC && RHSC->isNullValue())
1496  RHS = LHS;
1497  }
1498 
1499  // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1500  static const uint16_t SETFOpcTable[2][3] = {
1501  { X86::SETEr, X86::SETNPr, X86::AND8rr },
1502  { X86::SETNEr, X86::SETPr, X86::OR8rr }
1503  };
1504  const uint16_t *SETFOpc = nullptr;
1505  switch (Predicate) {
1506  default: break;
1507  case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1508  case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1509  }
1510 
1511  ResultReg = createResultReg(&X86::GR8RegClass);
1512  if (SETFOpc) {
1513  if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1514  return false;
1515 
1516  unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1517  unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1518  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1519  FlagReg1);
1520  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1521  FlagReg2);
1522  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1523  ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1524  updateValueMap(I, ResultReg);
1525  return true;
1526  }
1527 
1528  X86::CondCode CC;
1529  bool SwapArgs;
1530  std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1531  assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1532  unsigned Opc = X86::getSETFromCond(CC);
1533 
1534  if (SwapArgs)
1535  std::swap(LHS, RHS);
1536 
1537  // Emit a compare of LHS/RHS.
1538  if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1539  return false;
1540 
1541  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1542  updateValueMap(I, ResultReg);
1543  return true;
1544 }
1545 
1546 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1547  EVT DstVT = TLI.getValueType(DL, I->getType());
1548  if (!TLI.isTypeLegal(DstVT))
1549  return false;
1550 
1551  unsigned ResultReg = getRegForValue(I->getOperand(0));
1552  if (ResultReg == 0)
1553  return false;
1554 
1555  // Handle zero-extension from i1 to i8, which is common.
1556  MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1557  if (SrcVT == MVT::i1) {
1558  // In case ResultReg is a K register, COPY to a GPR
1559  if (MRI.getRegClass(ResultReg) == &X86::VK1RegClass) {
1560  unsigned KResultReg = ResultReg;
1561  ResultReg = createResultReg(&X86::GR32RegClass);
1562  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1563  TII.get(TargetOpcode::COPY), ResultReg)
1564  .addReg(KResultReg);
1565  ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1566  X86::sub_8bit);
1567  }
1568 
1569  // Set the high bits to zero.
1570  ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1571  SrcVT = MVT::i8;
1572 
1573  if (ResultReg == 0)
1574  return false;
1575  }
1576 
1577  if (DstVT == MVT::i64) {
1578  // Handle extension to 64-bits via sub-register shenanigans.
1579  unsigned MovInst;
1580 
1581  switch (SrcVT.SimpleTy) {
1582  case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1583  case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1584  case MVT::i32: MovInst = X86::MOV32rr; break;
1585  default: llvm_unreachable("Unexpected zext to i64 source type");
1586  }
1587 
1588  unsigned Result32 = createResultReg(&X86::GR32RegClass);
1589  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1590  .addReg(ResultReg);
1591 
1592  ResultReg = createResultReg(&X86::GR64RegClass);
1593  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1594  ResultReg)
1595  .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1596  } else if (DstVT != MVT::i8) {
1597  ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1598  ResultReg, /*Kill=*/true);
1599  if (ResultReg == 0)
1600  return false;
1601  }
1602 
1603  updateValueMap(I, ResultReg);
1604  return true;
1605 }
1606 
1607 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1608  // Unconditional branches are selected by tablegen-generated code.
1609  // Handle a conditional branch.
1610  const BranchInst *BI = cast<BranchInst>(I);
1611  MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1612  MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1613 
1614  // Fold the common case of a conditional branch with a comparison
1615  // in the same block (values defined on other blocks may not have
1616  // initialized registers).
1617  X86::CondCode CC;
1618  if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1619  if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1620  EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1621 
1622  // Try to optimize or fold the cmp.
1623  CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1624  switch (Predicate) {
1625  default: break;
1626  case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1627  case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1628  }
1629 
1630  const Value *CmpLHS = CI->getOperand(0);
1631  const Value *CmpRHS = CI->getOperand(1);
1632 
1633  // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1634  // 0.0.
1635  // We don't have to materialize a zero constant for this case and can just
1636  // use %x again on the RHS.
1637  if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1638  const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1639  if (CmpRHSC && CmpRHSC->isNullValue())
1640  CmpRHS = CmpLHS;
1641  }
1642 
1643  // Try to take advantage of fallthrough opportunities.
1644  if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1645  std::swap(TrueMBB, FalseMBB);
1646  Predicate = CmpInst::getInversePredicate(Predicate);
1647  }
1648 
1649  // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1650  // code check. Instead two branch instructions are required to check all
1651  // the flags. First we change the predicate to a supported condition code,
1652  // which will be the first branch. Later one we will emit the second
1653  // branch.
1654  bool NeedExtraBranch = false;
1655  switch (Predicate) {
1656  default: break;
1657  case CmpInst::FCMP_OEQ:
1658  std::swap(TrueMBB, FalseMBB);
1660  case CmpInst::FCMP_UNE:
1661  NeedExtraBranch = true;
1662  Predicate = CmpInst::FCMP_ONE;
1663  break;
1664  }
1665 
1666  bool SwapArgs;
1667  unsigned BranchOpc;
1668  std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1669  assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1670 
1671  BranchOpc = X86::GetCondBranchFromCond(CC);
1672  if (SwapArgs)
1673  std::swap(CmpLHS, CmpRHS);
1674 
1675  // Emit a compare of the LHS and RHS, setting the flags.
1676  if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1677  return false;
1678 
1679  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1680  .addMBB(TrueMBB);
1681 
1682  // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1683  // to UNE above).
1684  if (NeedExtraBranch) {
1685  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1686  .addMBB(TrueMBB);
1687  }
1688 
1689  finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1690  return true;
1691  }
1692  } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1693  // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1694  // typically happen for _Bool and C++ bools.
1695  MVT SourceVT;
1696  if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1697  isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1698  unsigned TestOpc = 0;
1699  switch (SourceVT.SimpleTy) {
1700  default: break;
1701  case MVT::i8: TestOpc = X86::TEST8ri; break;
1702  case MVT::i16: TestOpc = X86::TEST16ri; break;
1703  case MVT::i32: TestOpc = X86::TEST32ri; break;
1704  case MVT::i64: TestOpc = X86::TEST64ri32; break;
1705  }
1706  if (TestOpc) {
1707  unsigned OpReg = getRegForValue(TI->getOperand(0));
1708  if (OpReg == 0) return false;
1709 
1710  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1711  .addReg(OpReg).addImm(1);
1712 
1713  unsigned JmpOpc = X86::JNE_1;
1714  if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1715  std::swap(TrueMBB, FalseMBB);
1716  JmpOpc = X86::JE_1;
1717  }
1718 
1719  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1720  .addMBB(TrueMBB);
1721 
1722  finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1723  return true;
1724  }
1725  }
1726  } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1727  // Fake request the condition, otherwise the intrinsic might be completely
1728  // optimized away.
1729  unsigned TmpReg = getRegForValue(BI->getCondition());
1730  if (TmpReg == 0)
1731  return false;
1732 
1733  unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1734 
1735  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1736  .addMBB(TrueMBB);
1737  finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1738  return true;
1739  }
1740 
1741  // Otherwise do a clumsy setcc and re-test it.
1742  // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1743  // in an explicit cast, so make sure to handle that correctly.
1744  unsigned OpReg = getRegForValue(BI->getCondition());
1745  if (OpReg == 0) return false;
1746 
1747  // In case OpReg is a K register, COPY to a GPR
1748  if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1749  unsigned KOpReg = OpReg;
1750  OpReg = createResultReg(&X86::GR32RegClass);
1751  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1752  TII.get(TargetOpcode::COPY), OpReg)
1753  .addReg(KOpReg);
1754  OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, /*Kill=*/true,
1755  X86::sub_8bit);
1756  }
1757  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1758  .addReg(OpReg)
1759  .addImm(1);
1760  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1761  .addMBB(TrueMBB);
1762  finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1763  return true;
1764 }
1765 
1766 bool X86FastISel::X86SelectShift(const Instruction *I) {
1767  unsigned CReg = 0, OpReg = 0;
1768  const TargetRegisterClass *RC = nullptr;
1769  if (I->getType()->isIntegerTy(8)) {
1770  CReg = X86::CL;
1771  RC = &X86::GR8RegClass;
1772  switch (I->getOpcode()) {
1773  case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1774  case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1775  case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1776  default: return false;
1777  }
1778  } else if (I->getType()->isIntegerTy(16)) {
1779  CReg = X86::CX;
1780  RC = &X86::GR16RegClass;
1781  switch (I->getOpcode()) {
1782  case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1783  case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1784  case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1785  default: return false;
1786  }
1787  } else if (I->getType()->isIntegerTy(32)) {
1788  CReg = X86::ECX;
1789  RC = &X86::GR32RegClass;
1790  switch (I->getOpcode()) {
1791  case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1792  case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1793  case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1794  default: return false;
1795  }
1796  } else if (I->getType()->isIntegerTy(64)) {
1797  CReg = X86::RCX;
1798  RC = &X86::GR64RegClass;
1799  switch (I->getOpcode()) {
1800  case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1801  case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1802  case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1803  default: return false;
1804  }
1805  } else {
1806  return false;
1807  }
1808 
1809  MVT VT;
1810  if (!isTypeLegal(I->getType(), VT))
1811  return false;
1812 
1813  unsigned Op0Reg = getRegForValue(I->getOperand(0));
1814  if (Op0Reg == 0) return false;
1815 
1816  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1817  if (Op1Reg == 0) return false;
1818  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1819  CReg).addReg(Op1Reg);
1820 
1821  // The shift instruction uses X86::CL. If we defined a super-register
1822  // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1823  if (CReg != X86::CL)
1824  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1825  TII.get(TargetOpcode::KILL), X86::CL)
1826  .addReg(CReg, RegState::Kill);
1827 
1828  unsigned ResultReg = createResultReg(RC);
1829  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1830  .addReg(Op0Reg);
1831  updateValueMap(I, ResultReg);
1832  return true;
1833 }
1834 
1835 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1836  const static unsigned NumTypes = 4; // i8, i16, i32, i64
1837  const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1838  const static bool S = true; // IsSigned
1839  const static bool U = false; // !IsSigned
1840  const static unsigned Copy = TargetOpcode::COPY;
1841  // For the X86 DIV/IDIV instruction, in most cases the dividend
1842  // (numerator) must be in a specific register pair highreg:lowreg,
1843  // producing the quotient in lowreg and the remainder in highreg.
1844  // For most data types, to set up the instruction, the dividend is
1845  // copied into lowreg, and lowreg is sign-extended or zero-extended
1846  // into highreg. The exception is i8, where the dividend is defined
1847  // as a single register rather than a register pair, and we
1848  // therefore directly sign-extend or zero-extend the dividend into
1849  // lowreg, instead of copying, and ignore the highreg.
1850  const static struct DivRemEntry {
1851  // The following portion depends only on the data type.
1852  const TargetRegisterClass *RC;
1853  unsigned LowInReg; // low part of the register pair
1854  unsigned HighInReg; // high part of the register pair
1855  // The following portion depends on both the data type and the operation.
1856  struct DivRemResult {
1857  unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1858  unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1859  // highreg, or copying a zero into highreg.
1860  unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1861  // zero/sign-extending into lowreg for i8.
1862  unsigned DivRemResultReg; // Register containing the desired result.
1863  bool IsOpSigned; // Whether to use signed or unsigned form.
1864  } ResultTable[NumOps];
1865  } OpTable[NumTypes] = {
1866  { &X86::GR8RegClass, X86::AX, 0, {
1867  { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1868  { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1869  { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1870  { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1871  }
1872  }, // i8
1873  { &X86::GR16RegClass, X86::AX, X86::DX, {
1874  { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1875  { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1876  { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1877  { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1878  }
1879  }, // i16
1880  { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1881  { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1882  { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1883  { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1884  { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1885  }
1886  }, // i32
1887  { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1888  { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1889  { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1890  { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1891  { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1892  }
1893  }, // i64
1894  };
1895 
1896  MVT VT;
1897  if (!isTypeLegal(I->getType(), VT))
1898  return false;
1899 
1900  unsigned TypeIndex, OpIndex;
1901  switch (VT.SimpleTy) {
1902  default: return false;
1903  case MVT::i8: TypeIndex = 0; break;
1904  case MVT::i16: TypeIndex = 1; break;
1905  case MVT::i32: TypeIndex = 2; break;
1906  case MVT::i64: TypeIndex = 3;
1907  if (!Subtarget->is64Bit())
1908  return false;
1909  break;
1910  }
1911 
1912  switch (I->getOpcode()) {
1913  default: llvm_unreachable("Unexpected div/rem opcode");
1914  case Instruction::SDiv: OpIndex = 0; break;
1915  case Instruction::SRem: OpIndex = 1; break;
1916  case Instruction::UDiv: OpIndex = 2; break;
1917  case Instruction::URem: OpIndex = 3; break;
1918  }
1919 
1920  const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1921  const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1922  unsigned Op0Reg = getRegForValue(I->getOperand(0));
1923  if (Op0Reg == 0)
1924  return false;
1925  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1926  if (Op1Reg == 0)
1927  return false;
1928 
1929  // Move op0 into low-order input register.
1930  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1931  TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1932  // Zero-extend or sign-extend into high-order input register.
1933  if (OpEntry.OpSignExtend) {
1934  if (OpEntry.IsOpSigned)
1935  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1936  TII.get(OpEntry.OpSignExtend));
1937  else {
1938  unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1939  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1940  TII.get(X86::MOV32r0), Zero32);
1941 
1942  // Copy the zero into the appropriate sub/super/identical physical
1943  // register. Unfortunately the operations needed are not uniform enough
1944  // to fit neatly into the table above.
1945  if (VT == MVT::i16) {
1946  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1947  TII.get(Copy), TypeEntry.HighInReg)
1948  .addReg(Zero32, 0, X86::sub_16bit);
1949  } else if (VT == MVT::i32) {
1950  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1951  TII.get(Copy), TypeEntry.HighInReg)
1952  .addReg(Zero32);
1953  } else if (VT == MVT::i64) {
1954  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1955  TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1956  .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1957  }
1958  }
1959  }
1960  // Generate the DIV/IDIV instruction.
1961  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1962  TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1963  // For i8 remainder, we can't reference AH directly, as we'll end
1964  // up with bogus copies like %R9B = COPY %AH. Reference AX
1965  // instead to prevent AH references in a REX instruction.
1966  //
1967  // The current assumption of the fast register allocator is that isel
1968  // won't generate explicit references to the GPR8_NOREX registers. If
1969  // the allocator and/or the backend get enhanced to be more robust in
1970  // that regard, this can be, and should be, removed.
1971  unsigned ResultReg = 0;
1972  if ((I->getOpcode() == Instruction::SRem ||
1973  I->getOpcode() == Instruction::URem) &&
1974  OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1975  unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1976  unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1977  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1978  TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1979 
1980  // Shift AX right by 8 bits instead of using AH.
1981  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1982  ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1983 
1984  // Now reference the 8-bit subreg of the result.
1985  ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1986  /*Kill=*/true, X86::sub_8bit);
1987  }
1988  // Copy the result out of the physreg if we haven't already.
1989  if (!ResultReg) {
1990  ResultReg = createResultReg(TypeEntry.RC);
1991  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1992  .addReg(OpEntry.DivRemResultReg);
1993  }
1994  updateValueMap(I, ResultReg);
1995 
1996  return true;
1997 }
1998 
1999 /// \brief Emit a conditional move instruction (if the are supported) to lower
2000 /// the select.
2001 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2002  // Check if the subtarget supports these instructions.
2003  if (!Subtarget->hasCMov())
2004  return false;
2005 
2006  // FIXME: Add support for i8.
2007  if (RetVT < MVT::i16 || RetVT > MVT::i64)
2008  return false;
2009 
2010  const Value *Cond = I->getOperand(0);
2011  const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2012  bool NeedTest = true;
2014 
2015  // Optimize conditions coming from a compare if both instructions are in the
2016  // same basic block (values defined in other basic blocks may not have
2017  // initialized registers).
2018  const auto *CI = dyn_cast<CmpInst>(Cond);
2019  if (CI && (CI->getParent() == I->getParent())) {
2020  CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2021 
2022  // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
2023  static const uint16_t SETFOpcTable[2][3] = {
2024  { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2025  { X86::SETPr, X86::SETNEr, X86::OR8rr }
2026  };
2027  const uint16_t *SETFOpc = nullptr;
2028  switch (Predicate) {
2029  default: break;
2030  case CmpInst::FCMP_OEQ:
2031  SETFOpc = &SETFOpcTable[0][0];
2032  Predicate = CmpInst::ICMP_NE;
2033  break;
2034  case CmpInst::FCMP_UNE:
2035  SETFOpc = &SETFOpcTable[1][0];
2036  Predicate = CmpInst::ICMP_NE;
2037  break;
2038  }
2039 
2040  bool NeedSwap;
2041  std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
2042  assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2043 
2044  const Value *CmpLHS = CI->getOperand(0);
2045  const Value *CmpRHS = CI->getOperand(1);
2046  if (NeedSwap)
2047  std::swap(CmpLHS, CmpRHS);
2048 
2049  EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2050  // Emit a compare of the LHS and RHS, setting the flags.
2051  if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2052  return false;
2053 
2054  if (SETFOpc) {
2055  unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2056  unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2057  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2058  FlagReg1);
2059  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2060  FlagReg2);
2061  auto const &II = TII.get(SETFOpc[2]);
2062  if (II.getNumDefs()) {
2063  unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2064  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2065  .addReg(FlagReg2).addReg(FlagReg1);
2066  } else {
2067  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2068  .addReg(FlagReg2).addReg(FlagReg1);
2069  }
2070  }
2071  NeedTest = false;
2072  } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2073  // Fake request the condition, otherwise the intrinsic might be completely
2074  // optimized away.
2075  unsigned TmpReg = getRegForValue(Cond);
2076  if (TmpReg == 0)
2077  return false;
2078 
2079  NeedTest = false;
2080  }
2081 
2082  if (NeedTest) {
2083  // Selects operate on i1, however, CondReg is 8 bits width and may contain
2084  // garbage. Indeed, only the less significant bit is supposed to be
2085  // accurate. If we read more than the lsb, we may see non-zero values
2086  // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2087  // the select. This is achieved by performing TEST against 1.
2088  unsigned CondReg = getRegForValue(Cond);
2089  if (CondReg == 0)
2090  return false;
2091  bool CondIsKill = hasTrivialKill(Cond);
2092 
2093  // In case OpReg is a K register, COPY to a GPR
2094  if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2095  unsigned KCondReg = CondReg;
2096  CondReg = createResultReg(&X86::GR32RegClass);
2097  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2098  TII.get(TargetOpcode::COPY), CondReg)
2099  .addReg(KCondReg, getKillRegState(CondIsKill));
2100  CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2101  X86::sub_8bit);
2102  }
2103  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2104  .addReg(CondReg, getKillRegState(CondIsKill))
2105  .addImm(1);
2106  }
2107 
2108  const Value *LHS = I->getOperand(1);
2109  const Value *RHS = I->getOperand(2);
2110 
2111  unsigned RHSReg = getRegForValue(RHS);
2112  bool RHSIsKill = hasTrivialKill(RHS);
2113 
2114  unsigned LHSReg = getRegForValue(LHS);
2115  bool LHSIsKill = hasTrivialKill(LHS);
2116 
2117  if (!LHSReg || !RHSReg)
2118  return false;
2119 
2120  const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
2121  unsigned Opc = X86::getCMovFromCond(CC, TRI.getRegSizeInBits(*RC)/8);
2122  unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2123  LHSReg, LHSIsKill);
2124  updateValueMap(I, ResultReg);
2125  return true;
2126 }
2127 
2128 /// \brief Emit SSE or AVX instructions to lower the select.
2129 ///
2130 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2131 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
2132 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
2133 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2134  // Optimize conditions coming from a compare if both instructions are in the
2135  // same basic block (values defined in other basic blocks may not have
2136  // initialized registers).
2137  const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2138  if (!CI || (CI->getParent() != I->getParent()))
2139  return false;
2140 
2141  if (I->getType() != CI->getOperand(0)->getType() ||
2142  !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2143  (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2144  return false;
2145 
2146  const Value *CmpLHS = CI->getOperand(0);
2147  const Value *CmpRHS = CI->getOperand(1);
2148  CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2149 
2150  // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2151  // We don't have to materialize a zero constant for this case and can just use
2152  // %x again on the RHS.
2153  if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2154  const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2155  if (CmpRHSC && CmpRHSC->isNullValue())
2156  CmpRHS = CmpLHS;
2157  }
2158 
2159  unsigned CC;
2160  bool NeedSwap;
2161  std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2162  if (CC > 7)
2163  return false;
2164 
2165  if (NeedSwap)
2166  std::swap(CmpLHS, CmpRHS);
2167 
2168  // Choose the SSE instruction sequence based on data type (float or double).
2169  static const uint16_t OpcTable[2][4] = {
2170  { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2171  { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
2172  };
2173 
2174  const uint16_t *Opc = nullptr;
2175  switch (RetVT.SimpleTy) {
2176  default: return false;
2177  case MVT::f32: Opc = &OpcTable[0][0]; break;
2178  case MVT::f64: Opc = &OpcTable[1][0]; break;
2179  }
2180 
2181  const Value *LHS = I->getOperand(1);
2182  const Value *RHS = I->getOperand(2);
2183 
2184  unsigned LHSReg = getRegForValue(LHS);
2185  bool LHSIsKill = hasTrivialKill(LHS);
2186 
2187  unsigned RHSReg = getRegForValue(RHS);
2188  bool RHSIsKill = hasTrivialKill(RHS);
2189 
2190  unsigned CmpLHSReg = getRegForValue(CmpLHS);
2191  bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2192 
2193  unsigned CmpRHSReg = getRegForValue(CmpRHS);
2194  bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2195 
2196  if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2197  return false;
2198 
2199  const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2200  unsigned ResultReg;
2201 
2202  if (Subtarget->hasAVX512()) {
2203  // If we have AVX512 we can use a mask compare and masked movss/sd.
2204  const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2205  const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2206 
2207  unsigned CmpOpcode =
2208  (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
2209  unsigned CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpLHSIsKill,
2210  CmpRHSReg, CmpRHSIsKill, CC);
2211 
2212  // Need an IMPLICIT_DEF for the input that is used to generate the upper
2213  // bits of the result register since its not based on any of the inputs.
2214  unsigned ImplicitDefReg = createResultReg(VR128X);
2215  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2216  TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2217 
2218  // Place RHSReg is the passthru of the masked movss/sd operation and put
2219  // LHS in the input. The mask input comes from the compare.
2220  unsigned MovOpcode =
2221  (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
2222  unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, RHSIsKill,
2223  CmpReg, true, ImplicitDefReg, true,
2224  LHSReg, LHSIsKill);
2225 
2226  ResultReg = createResultReg(RC);
2227  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2228  TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2229 
2230  } else if (Subtarget->hasAVX()) {
2231  const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2232 
2233  // If we have AVX, create 1 blendv instead of 3 logic instructions.
2234  // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2235  // uses XMM0 as the selection register. That may need just as many
2236  // instructions as the AND/ANDN/OR sequence due to register moves, so
2237  // don't bother.
2238  unsigned CmpOpcode =
2239  (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2240  unsigned BlendOpcode =
2241  (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2242 
2243  unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
2244  CmpRHSReg, CmpRHSIsKill, CC);
2245  unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2246  LHSReg, LHSIsKill, CmpReg, true);
2247  ResultReg = createResultReg(RC);
2248  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2249  TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
2250  } else {
2251  const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2252  unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2253  CmpRHSReg, CmpRHSIsKill, CC);
2254  unsigned AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, /*IsKill=*/false,
2255  LHSReg, LHSIsKill);
2256  unsigned AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, /*IsKill=*/true,
2257  RHSReg, RHSIsKill);
2258  unsigned OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, /*IsKill=*/true,
2259  AndReg, /*IsKill=*/true);
2260  ResultReg = createResultReg(RC);
2261  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2262  TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
2263  }
2264  updateValueMap(I, ResultReg);
2265  return true;
2266 }
2267 
2268 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2269  // These are pseudo CMOV instructions and will be later expanded into control-
2270  // flow.
2271  unsigned Opc;
2272  switch (RetVT.SimpleTy) {
2273  default: return false;
2274  case MVT::i8: Opc = X86::CMOV_GR8; break;
2275  case MVT::i16: Opc = X86::CMOV_GR16; break;
2276  case MVT::i32: Opc = X86::CMOV_GR32; break;
2277  case MVT::f32: Opc = X86::CMOV_FR32; break;
2278  case MVT::f64: Opc = X86::CMOV_FR64; break;
2279  }
2280 
2281  const Value *Cond = I->getOperand(0);
2283 
2284  // Optimize conditions coming from a compare if both instructions are in the
2285  // same basic block (values defined in other basic blocks may not have
2286  // initialized registers).
2287  const auto *CI = dyn_cast<CmpInst>(Cond);
2288  if (CI && (CI->getParent() == I->getParent())) {
2289  bool NeedSwap;
2290  std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
2291  if (CC > X86::LAST_VALID_COND)
2292  return false;
2293 
2294  const Value *CmpLHS = CI->getOperand(0);
2295  const Value *CmpRHS = CI->getOperand(1);
2296 
2297  if (NeedSwap)
2298  std::swap(CmpLHS, CmpRHS);
2299 
2300  EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2301  if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2302  return false;
2303  } else {
2304  unsigned CondReg = getRegForValue(Cond);
2305  if (CondReg == 0)
2306  return false;
2307  bool CondIsKill = hasTrivialKill(Cond);
2308 
2309  // In case OpReg is a K register, COPY to a GPR
2310  if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2311  unsigned KCondReg = CondReg;
2312  CondReg = createResultReg(&X86::GR32RegClass);
2313  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2314  TII.get(TargetOpcode::COPY), CondReg)
2315  .addReg(KCondReg, getKillRegState(CondIsKill));
2316  CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2317  X86::sub_8bit);
2318  }
2319  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2320  .addReg(CondReg, getKillRegState(CondIsKill))
2321  .addImm(1);
2322  }
2323 
2324  const Value *LHS = I->getOperand(1);
2325  const Value *RHS = I->getOperand(2);
2326 
2327  unsigned LHSReg = getRegForValue(LHS);
2328  bool LHSIsKill = hasTrivialKill(LHS);
2329 
2330  unsigned RHSReg = getRegForValue(RHS);
2331  bool RHSIsKill = hasTrivialKill(RHS);
2332 
2333  if (!LHSReg || !RHSReg)
2334  return false;
2335 
2336  const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2337 
2338  unsigned ResultReg =
2339  fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2340  updateValueMap(I, ResultReg);
2341  return true;
2342 }
2343 
2344 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2345  MVT RetVT;
2346  if (!isTypeLegal(I->getType(), RetVT))
2347  return false;
2348 
2349  // Check if we can fold the select.
2350  if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2351  CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2352  const Value *Opnd = nullptr;
2353  switch (Predicate) {
2354  default: break;
2355  case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2356  case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2357  }
2358  // No need for a select anymore - this is an unconditional move.
2359  if (Opnd) {
2360  unsigned OpReg = getRegForValue(Opnd);
2361  if (OpReg == 0)
2362  return false;
2363  bool OpIsKill = hasTrivialKill(Opnd);
2364  const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2365  unsigned ResultReg = createResultReg(RC);
2366  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2367  TII.get(TargetOpcode::COPY), ResultReg)
2368  .addReg(OpReg, getKillRegState(OpIsKill));
2369  updateValueMap(I, ResultReg);
2370  return true;
2371  }
2372  }
2373 
2374  // First try to use real conditional move instructions.
2375  if (X86FastEmitCMoveSelect(RetVT, I))
2376  return true;
2377 
2378  // Try to use a sequence of SSE instructions to simulate a conditional move.
2379  if (X86FastEmitSSESelect(RetVT, I))
2380  return true;
2381 
2382  // Fall-back to pseudo conditional move instructions, which will be later
2383  // converted to control-flow.
2384  if (X86FastEmitPseudoSelect(RetVT, I))
2385  return true;
2386 
2387  return false;
2388 }
2389 
2390 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2391  // The target-independent selection algorithm in FastISel already knows how
2392  // to select a SINT_TO_FP if the target is SSE but not AVX.
2393  // Early exit if the subtarget doesn't have AVX.
2394  if (!Subtarget->hasAVX())
2395  return false;
2396 
2397  if (!I->getOperand(0)->getType()->isIntegerTy(32))
2398  return false;
2399 
2400  // Select integer to float/double conversion.
2401  unsigned OpReg = getRegForValue(I->getOperand(0));
2402  if (OpReg == 0)
2403  return false;
2404 
2405  const TargetRegisterClass *RC = nullptr;
2406  unsigned Opcode;
2407 
2408  if (I->getType()->isDoubleTy()) {
2409  // sitofp int -> double
2410  Opcode = X86::VCVTSI2SDrr;
2411  RC = &X86::FR64RegClass;
2412  } else if (I->getType()->isFloatTy()) {
2413  // sitofp int -> float
2414  Opcode = X86::VCVTSI2SSrr;
2415  RC = &X86::FR32RegClass;
2416  } else
2417  return false;
2418 
2419  unsigned ImplicitDefReg = createResultReg(RC);
2420  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2421  TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2422  unsigned ResultReg =
2423  fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2424  updateValueMap(I, ResultReg);
2425  return true;
2426 }
2427 
2428 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2429 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2430  unsigned TargetOpc,
2431  const TargetRegisterClass *RC) {
2432  assert((I->getOpcode() == Instruction::FPExt ||
2433  I->getOpcode() == Instruction::FPTrunc) &&
2434  "Instruction must be an FPExt or FPTrunc!");
2435 
2436  unsigned OpReg = getRegForValue(I->getOperand(0));
2437  if (OpReg == 0)
2438  return false;
2439 
2440  unsigned ImplicitDefReg;
2441  if (Subtarget->hasAVX()) {
2442  ImplicitDefReg = createResultReg(RC);
2443  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2444  TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2445 
2446  }
2447 
2448  unsigned ResultReg = createResultReg(RC);
2449  MachineInstrBuilder MIB;
2450  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2451  ResultReg);
2452 
2453  if (Subtarget->hasAVX())
2454  MIB.addReg(ImplicitDefReg);
2455 
2456  MIB.addReg(OpReg);
2457  updateValueMap(I, ResultReg);
2458  return true;
2459 }
2460 
2461 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2462  if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2463  I->getOperand(0)->getType()->isFloatTy()) {
2464  // fpext from float to double.
2465  unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2466  return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2467  }
2468 
2469  return false;
2470 }
2471 
2472 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2473  if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2474  I->getOperand(0)->getType()->isDoubleTy()) {
2475  // fptrunc from double to float.
2476  unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2477  return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2478  }
2479 
2480  return false;
2481 }
2482 
2483 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2484  EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2485  EVT DstVT = TLI.getValueType(DL, I->getType());
2486 
2487  // This code only handles truncation to byte.
2488  // TODO: Support truncate to i1 with AVX512.
2489  if (DstVT != MVT::i8 && (DstVT != MVT::i1 || Subtarget->hasAVX512()))
2490  return false;
2491  if (!TLI.isTypeLegal(SrcVT))
2492  return false;
2493 
2494  unsigned InputReg = getRegForValue(I->getOperand(0));
2495  if (!InputReg)
2496  // Unhandled operand. Halt "fast" selection and bail.
2497  return false;
2498 
2499  if (SrcVT == MVT::i8) {
2500  // Truncate from i8 to i1; no code needed.
2501  updateValueMap(I, InputReg);
2502  return true;
2503  }
2504 
2505  bool KillInputReg = false;
2506  if (!Subtarget->is64Bit()) {
2507  // If we're on x86-32; we can't extract an i8 from a general register.
2508  // First issue a copy to GR16_ABCD or GR32_ABCD.
2509  const TargetRegisterClass *CopyRC =
2510  (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2511  unsigned CopyReg = createResultReg(CopyRC);
2512  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2513  TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2514  InputReg = CopyReg;
2515  KillInputReg = true;
2516  }
2517 
2518  // Issue an extract_subreg.
2519  unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2520  InputReg, KillInputReg,
2521  X86::sub_8bit);
2522  if (!ResultReg)
2523  return false;
2524 
2525  updateValueMap(I, ResultReg);
2526  return true;
2527 }
2528 
2529 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2530  return Len <= (Subtarget->is64Bit() ? 32 : 16);
2531 }
2532 
2533 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2534  X86AddressMode SrcAM, uint64_t Len) {
2535 
2536  // Make sure we don't bloat code by inlining very large memcpy's.
2537  if (!IsMemcpySmall(Len))
2538  return false;
2539 
2540  bool i64Legal = Subtarget->is64Bit();
2541 
2542  // We don't care about alignment here since we just emit integer accesses.
2543  while (Len) {
2544  MVT VT;
2545  if (Len >= 8 && i64Legal)
2546  VT = MVT::i64;
2547  else if (Len >= 4)
2548  VT = MVT::i32;
2549  else if (Len >= 2)
2550  VT = MVT::i16;
2551  else
2552  VT = MVT::i8;
2553 
2554  unsigned Reg;
2555  bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2556  RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2557  assert(RV && "Failed to emit load or store??");
2558 
2559  unsigned Size = VT.getSizeInBits()/8;
2560  Len -= Size;
2561  DestAM.Disp += Size;
2562  SrcAM.Disp += Size;
2563  }
2564 
2565  return true;
2566 }
2567 
2568 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2569  // FIXME: Handle more intrinsics.
2570  switch (II->getIntrinsicID()) {
2571  default: return false;
2572  case Intrinsic::convert_from_fp16:
2573  case Intrinsic::convert_to_fp16: {
2574  if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2575  return false;
2576 
2577  const Value *Op = II->getArgOperand(0);
2578  unsigned InputReg = getRegForValue(Op);
2579  if (InputReg == 0)
2580  return false;
2581 
2582  // F16C only allows converting from float to half and from half to float.
2583  bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2584  if (IsFloatToHalf) {
2585  if (!Op->getType()->isFloatTy())
2586  return false;
2587  } else {
2588  if (!II->getType()->isFloatTy())
2589  return false;
2590  }
2591 
2592  unsigned ResultReg = 0;
2593  const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2594  if (IsFloatToHalf) {
2595  // 'InputReg' is implicitly promoted from register class FR32 to
2596  // register class VR128 by method 'constrainOperandRegClass' which is
2597  // directly called by 'fastEmitInst_ri'.
2598  // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2599  // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2600  // It's consistent with the other FP instructions, which are usually
2601  // controlled by MXCSR.
2602  InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
2603 
2604  // Move the lower 32-bits of ResultReg to another register of class GR32.
2605  ResultReg = createResultReg(&X86::GR32RegClass);
2606  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2607  TII.get(X86::VMOVPDI2DIrr), ResultReg)
2608  .addReg(InputReg, RegState::Kill);
2609 
2610  // The result value is in the lower 16-bits of ResultReg.
2611  unsigned RegIdx = X86::sub_16bit;
2612  ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2613  } else {
2614  assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2615  // Explicitly sign-extend the input to 32-bit.
2616  InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2617  /*Kill=*/false);
2618 
2619  // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2620  InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2621  InputReg, /*Kill=*/true);
2622 
2623  InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2624 
2625  // The result value is in the lower 32-bits of ResultReg.
2626  // Emit an explicit copy from register class VR128 to register class FR32.
2627  ResultReg = createResultReg(&X86::FR32RegClass);
2628  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2629  TII.get(TargetOpcode::COPY), ResultReg)
2630  .addReg(InputReg, RegState::Kill);
2631  }
2632 
2633  updateValueMap(II, ResultReg);
2634  return true;
2635  }
2636  case Intrinsic::frameaddress: {
2637  MachineFunction *MF = FuncInfo.MF;
2638  if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2639  return false;
2640 
2641  Type *RetTy = II->getCalledFunction()->getReturnType();
2642 
2643  MVT VT;
2644  if (!isTypeLegal(RetTy, VT))
2645  return false;
2646 
2647  unsigned Opc;
2648  const TargetRegisterClass *RC = nullptr;
2649 
2650  switch (VT.SimpleTy) {
2651  default: llvm_unreachable("Invalid result type for frameaddress.");
2652  case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2653  case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2654  }
2655 
2656  // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2657  // we get the wrong frame register.
2658  MachineFrameInfo &MFI = MF->getFrameInfo();
2659  MFI.setFrameAddressIsTaken(true);
2660 
2661  const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2662  unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2663  assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2664  (FrameReg == X86::EBP && VT == MVT::i32)) &&
2665  "Invalid Frame Register!");
2666 
2667  // Always make a copy of the frame register to to a vreg first, so that we
2668  // never directly reference the frame register (the TwoAddressInstruction-
2669  // Pass doesn't like that).
2670  unsigned SrcReg = createResultReg(RC);
2671  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2672  TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2673 
2674  // Now recursively load from the frame address.
2675  // movq (%rbp), %rax
2676  // movq (%rax), %rax
2677  // movq (%rax), %rax
2678  // ...
2679  unsigned DestReg;
2680  unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2681  while (Depth--) {
2682  DestReg = createResultReg(RC);
2683  addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2684  TII.get(Opc), DestReg), SrcReg);
2685  SrcReg = DestReg;
2686  }
2687 
2688  updateValueMap(II, SrcReg);
2689  return true;
2690  }
2691  case Intrinsic::memcpy: {
2692  const MemCpyInst *MCI = cast<MemCpyInst>(II);
2693  // Don't handle volatile or variable length memcpys.
2694  if (MCI->isVolatile())
2695  return false;
2696 
2697  if (isa<ConstantInt>(MCI->getLength())) {
2698  // Small memcpy's are common enough that we want to do them
2699  // without a call if possible.
2700  uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2701  if (IsMemcpySmall(Len)) {
2702  X86AddressMode DestAM, SrcAM;
2703  if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2704  !X86SelectAddress(MCI->getRawSource(), SrcAM))
2705  return false;
2706  TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2707  return true;
2708  }
2709  }
2710 
2711  unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2712  if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2713  return false;
2714 
2715  if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2716  return false;
2717 
2718  return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2719  }
2720  case Intrinsic::memset: {
2721  const MemSetInst *MSI = cast<MemSetInst>(II);
2722 
2723  if (MSI->isVolatile())
2724  return false;
2725 
2726  unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2727  if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2728  return false;
2729 
2730  if (MSI->getDestAddressSpace() > 255)
2731  return false;
2732 
2733  return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2734  }
2735  case Intrinsic::stackprotector: {
2736  // Emit code to store the stack guard onto the stack.
2737  EVT PtrTy = TLI.getPointerTy(DL);
2738 
2739  const Value *Op1 = II->getArgOperand(0); // The guard's value.
2740  const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2741 
2742  MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2743 
2744  // Grab the frame index.
2745  X86AddressMode AM;
2746  if (!X86SelectAddress(Slot, AM)) return false;
2747  if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2748  return true;
2749  }
2750  case Intrinsic::dbg_declare: {
2751  const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2752  X86AddressMode AM;
2753  assert(DI->getAddress() && "Null address should be checked earlier!");
2754  if (!X86SelectAddress(DI->getAddress(), AM))
2755  return false;
2756  const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2757  // FIXME may need to add RegState::Debug to any registers produced,
2758  // although ESP/EBP should be the only ones at the moment.
2760  "Expected inlined-at fields to agree");
2761  addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2762  .addImm(0)
2763  .addMetadata(DI->getVariable())
2764  .addMetadata(DI->getExpression());
2765  return true;
2766  }
2767  case Intrinsic::trap: {
2768  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2769  return true;
2770  }
2771  case Intrinsic::sqrt: {
2772  if (!Subtarget->hasSSE1())
2773  return false;
2774 
2775  Type *RetTy = II->getCalledFunction()->getReturnType();
2776 
2777  MVT VT;
2778  if (!isTypeLegal(RetTy, VT))
2779  return false;
2780 
2781  // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2782  // is not generated by FastISel yet.
2783  // FIXME: Update this code once tablegen can handle it.
2784  static const uint16_t SqrtOpc[2][2] = {
2785  {X86::SQRTSSr, X86::VSQRTSSr},
2786  {X86::SQRTSDr, X86::VSQRTSDr}
2787  };
2788  bool HasAVX = Subtarget->hasAVX();
2789  unsigned Opc;
2790  const TargetRegisterClass *RC;
2791  switch (VT.SimpleTy) {
2792  default: return false;
2793  case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2794  case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2795  }
2796 
2797  const Value *SrcVal = II->getArgOperand(0);
2798  unsigned SrcReg = getRegForValue(SrcVal);
2799 
2800  if (SrcReg == 0)
2801  return false;
2802 
2803  unsigned ImplicitDefReg = 0;
2804  if (HasAVX) {
2805  ImplicitDefReg = createResultReg(RC);
2806  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2807  TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2808  }
2809 
2810  unsigned ResultReg = createResultReg(RC);
2811  MachineInstrBuilder MIB;
2812  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2813  ResultReg);
2814 
2815  if (ImplicitDefReg)
2816  MIB.addReg(ImplicitDefReg);
2817 
2818  MIB.addReg(SrcReg);
2819 
2820  updateValueMap(II, ResultReg);
2821  return true;
2822  }
2823  case Intrinsic::sadd_with_overflow:
2824  case Intrinsic::uadd_with_overflow:
2825  case Intrinsic::ssub_with_overflow:
2826  case Intrinsic::usub_with_overflow:
2827  case Intrinsic::smul_with_overflow:
2828  case Intrinsic::umul_with_overflow: {
2829  // This implements the basic lowering of the xalu with overflow intrinsics
2830  // into add/sub/mul followed by either seto or setb.
2831  const Function *Callee = II->getCalledFunction();
2832  auto *Ty = cast<StructType>(Callee->getReturnType());
2833  Type *RetTy = Ty->getTypeAtIndex(0U);
2834  assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2835  Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2836  "Overflow value expected to be an i1");
2837 
2838  MVT VT;
2839  if (!isTypeLegal(RetTy, VT))
2840  return false;
2841 
2842  if (VT < MVT::i8 || VT > MVT::i64)
2843  return false;
2844 
2845  const Value *LHS = II->getArgOperand(0);
2846  const Value *RHS = II->getArgOperand(1);
2847 
2848  // Canonicalize immediate to the RHS.
2849  if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2850  isCommutativeIntrinsic(II))
2851  std::swap(LHS, RHS);
2852 
2853  bool UseIncDec = false;
2854  if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2855  UseIncDec = true;
2856 
2857  unsigned BaseOpc, CondOpc;
2858  switch (II->getIntrinsicID()) {
2859  default: llvm_unreachable("Unexpected intrinsic!");
2860  case Intrinsic::sadd_with_overflow:
2861  BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2862  CondOpc = X86::SETOr;
2863  break;
2864  case Intrinsic::uadd_with_overflow:
2865  BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2866  case Intrinsic::ssub_with_overflow:
2867  BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2868  CondOpc = X86::SETOr;
2869  break;
2870  case Intrinsic::usub_with_overflow:
2871  BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2872  case Intrinsic::smul_with_overflow:
2873  BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2874  case Intrinsic::umul_with_overflow:
2875  BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2876  }
2877 
2878  unsigned LHSReg = getRegForValue(LHS);
2879  if (LHSReg == 0)
2880  return false;
2881  bool LHSIsKill = hasTrivialKill(LHS);
2882 
2883  unsigned ResultReg = 0;
2884  // Check if we have an immediate version.
2885  if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2886  static const uint16_t Opc[2][4] = {
2887  { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2888  { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2889  };
2890 
2891  if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2892  ResultReg = createResultReg(TLI.getRegClassFor(VT));
2893  bool IsDec = BaseOpc == X86ISD::DEC;
2894  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2895  TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2896  .addReg(LHSReg, getKillRegState(LHSIsKill));
2897  } else
2898  ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2899  CI->getZExtValue());
2900  }
2901 
2902  unsigned RHSReg;
2903  bool RHSIsKill;
2904  if (!ResultReg) {
2905  RHSReg = getRegForValue(RHS);
2906  if (RHSReg == 0)
2907  return false;
2908  RHSIsKill = hasTrivialKill(RHS);
2909  ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2910  RHSIsKill);
2911  }
2912 
2913  // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2914  // it manually.
2915  if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2916  static const uint16_t MULOpc[] =
2917  { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2918  static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2919  // First copy the first operand into RAX, which is an implicit input to
2920  // the X86::MUL*r instruction.
2921  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2922  TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2923  .addReg(LHSReg, getKillRegState(LHSIsKill));
2924  ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2925  TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2926  } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2927  static const uint16_t MULOpc[] =
2928  { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2929  if (VT == MVT::i8) {
2930  // Copy the first operand into AL, which is an implicit input to the
2931  // X86::IMUL8r instruction.
2932  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2933  TII.get(TargetOpcode::COPY), X86::AL)
2934  .addReg(LHSReg, getKillRegState(LHSIsKill));
2935  ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2936  RHSIsKill);
2937  } else
2938  ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2939  TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2940  RHSReg, RHSIsKill);
2941  }
2942 
2943  if (!ResultReg)
2944  return false;
2945 
2946  // Assign to a GPR since the overflow return value is lowered to a SETcc.
2947  unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
2948  assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2949  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2950  ResultReg2);
2951 
2952  updateValueMap(II, ResultReg, 2);
2953  return true;
2954  }
2955  case Intrinsic::x86_sse_cvttss2si:
2956  case Intrinsic::x86_sse_cvttss2si64:
2957  case Intrinsic::x86_sse2_cvttsd2si:
2958  case Intrinsic::x86_sse2_cvttsd2si64: {
2959  bool IsInputDouble;
2960  switch (II->getIntrinsicID()) {
2961  default: llvm_unreachable("Unexpected intrinsic.");
2962  case Intrinsic::x86_sse_cvttss2si:
2963  case Intrinsic::x86_sse_cvttss2si64:
2964  if (!Subtarget->hasSSE1())
2965  return false;
2966  IsInputDouble = false;
2967  break;
2968  case Intrinsic::x86_sse2_cvttsd2si:
2969  case Intrinsic::x86_sse2_cvttsd2si64:
2970  if (!Subtarget->hasSSE2())
2971  return false;
2972  IsInputDouble = true;
2973  break;
2974  }
2975 
2976  Type *RetTy = II->getCalledFunction()->getReturnType();
2977  MVT VT;
2978  if (!isTypeLegal(RetTy, VT))
2979  return false;
2980 
2981  static const uint16_t CvtOpc[2][2][2] = {
2982  { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2983  { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2984  { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2985  { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2986  };
2987  bool HasAVX = Subtarget->hasAVX();
2988  unsigned Opc;
2989  switch (VT.SimpleTy) {
2990  default: llvm_unreachable("Unexpected result type.");
2991  case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2992  case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2993  }
2994 
2995  // Check if we can fold insertelement instructions into the convert.
2996  const Value *Op = II->getArgOperand(0);
2997  while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2998  const Value *Index = IE->getOperand(2);
2999  if (!isa<ConstantInt>(Index))
3000  break;
3001  unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
3002 
3003  if (Idx == 0) {
3004  Op = IE->getOperand(1);
3005  break;
3006  }
3007  Op = IE->getOperand(0);
3008  }
3009 
3010  unsigned Reg = getRegForValue(Op);
3011  if (Reg == 0)
3012  return false;
3013 
3014  unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3015  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3016  .addReg(Reg);
3017 
3018  updateValueMap(II, ResultReg);
3019  return true;
3020  }
3021  }
3022 }
3023 
3024 bool X86FastISel::fastLowerArguments() {
3025  if (!FuncInfo.CanLowerReturn)
3026  return false;
3027 
3028  const Function *F = FuncInfo.Fn;
3029  if (F->isVarArg())
3030  return false;
3031 
3032  CallingConv::ID CC = F->getCallingConv();
3033  if (CC != CallingConv::C)
3034  return false;
3035 
3036  if (Subtarget->isCallingConvWin64(CC))
3037  return false;
3038 
3039  if (!Subtarget->is64Bit())
3040  return false;
3041 
3042  if (Subtarget->useSoftFloat())
3043  return false;
3044 
3045  // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3046  unsigned GPRCnt = 0;
3047  unsigned FPRCnt = 0;
3048  for (auto const &Arg : F->args()) {
3049  if (Arg.hasAttribute(Attribute::ByVal) ||
3050  Arg.hasAttribute(Attribute::InReg) ||
3051  Arg.hasAttribute(Attribute::StructRet) ||
3052  Arg.hasAttribute(Attribute::SwiftSelf) ||
3053  Arg.hasAttribute(Attribute::SwiftError) ||
3054  Arg.hasAttribute(Attribute::Nest))
3055  return false;
3056 
3057  Type *ArgTy = Arg.getType();
3058  if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3059  return false;
3060 
3061  EVT ArgVT = TLI.getValueType(DL, ArgTy);
3062  if (!ArgVT.isSimple()) return false;
3063  switch (ArgVT.getSimpleVT().SimpleTy) {
3064  default: return false;
3065  case MVT::i32:
3066  case MVT::i64:
3067  ++GPRCnt;
3068  break;
3069  case MVT::f32:
3070  case MVT::f64:
3071  if (!Subtarget->hasSSE1())
3072  return false;
3073  ++FPRCnt;
3074  break;
3075  }
3076 
3077  if (GPRCnt > 6)
3078  return false;
3079 
3080  if (FPRCnt > 8)
3081  return false;
3082  }
3083 
3084  static const MCPhysReg GPR32ArgRegs[] = {
3085  X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3086  };
3087  static const MCPhysReg GPR64ArgRegs[] = {
3088  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3089  };
3090  static const MCPhysReg XMMArgRegs[] = {
3091  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3092  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3093  };
3094 
3095  unsigned GPRIdx = 0;
3096  unsigned FPRIdx = 0;
3097  for (auto const &Arg : F->args()) {
3098  MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
3099  const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3100  unsigned SrcReg;
3101  switch (VT.SimpleTy) {
3102  default: llvm_unreachable("Unexpected value type.");
3103  case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3104  case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
3105  case MVT::f32: LLVM_FALLTHROUGH;
3106  case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3107  }
3108  unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3109  // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3110  // Without this, EmitLiveInCopies may eliminate the livein if its only
3111  // use is a bitcast (which isn't turned into an instruction).
3112  unsigned ResultReg = createResultReg(RC);
3113  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3114  TII.get(TargetOpcode::COPY), ResultReg)
3115  .addReg(DstReg, getKillRegState(true));
3116  updateValueMap(&Arg, ResultReg);
3117  }
3118  return true;
3119 }
3120 
3121 static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3122  CallingConv::ID CC,
3123  ImmutableCallSite *CS) {
3124  if (Subtarget->is64Bit())
3125  return 0;
3126  if (Subtarget->getTargetTriple().isOSMSVCRT())
3127  return 0;
3128  if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3129  CC == CallingConv::HiPE)
3130  return 0;
3131 
3132  if (CS)
3133  if (CS->arg_empty() || !CS->paramHasAttr(0, Attribute::StructRet) ||
3134  CS->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
3135  return 0;
3136 
3137  return 4;
3138 }
3139 
3140 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3141  auto &OutVals = CLI.OutVals;
3142  auto &OutFlags = CLI.OutFlags;
3143  auto &OutRegs = CLI.OutRegs;
3144  auto &Ins = CLI.Ins;
3145  auto &InRegs = CLI.InRegs;
3146  CallingConv::ID CC = CLI.CallConv;
3147  bool &IsTailCall = CLI.IsTailCall;
3148  bool IsVarArg = CLI.IsVarArg;
3149  const Value *Callee = CLI.Callee;
3150  MCSymbol *Symbol = CLI.Symbol;
3151 
3152  bool Is64Bit = Subtarget->is64Bit();
3153  bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3154 
3155  const CallInst *CI =
3156  CLI.CS ? dyn_cast<CallInst>(CLI.CS->getInstruction()) : nullptr;
3157  const Function *CalledFn = CI ? CI->getCalledFunction() : nullptr;
3158 
3159  // Functions with no_caller_saved_registers that need special handling.
3160  if ((CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3161  (CalledFn && CalledFn->hasFnAttribute("no_caller_saved_registers")))
3162  return false;
3163 
3164  // Handle only C, fastcc, and webkit_js calling conventions for now.
3165  switch (CC) {
3166  default: return false;
3167  case CallingConv::C:
3168  case CallingConv::Fast:
3170  case CallingConv::Swift:
3174  case CallingConv::Win64:
3176  break;
3177  }
3178 
3179  // Allow SelectionDAG isel to handle tail calls.
3180  if (IsTailCall)
3181  return false;
3182 
3183  // fastcc with -tailcallopt is intended to provide a guaranteed
3184  // tail call optimization. Fastisel doesn't know how to do that.
3185  if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3186  return false;
3187 
3188  // Don't know how to handle Win64 varargs yet. Nothing special needed for
3189  // x86-32. Special handling for x86-64 is implemented.
3190  if (IsVarArg && IsWin64)
3191  return false;
3192 
3193  // Don't know about inalloca yet.
3194  if (CLI.CS && CLI.CS->hasInAllocaArgument())
3195  return false;
3196 
3197  for (auto Flag : CLI.OutFlags)
3198  if (Flag.isSwiftError())
3199  return false;
3200 
3201  SmallVector<MVT, 16> OutVTs;
3202  SmallVector<unsigned, 16> ArgRegs;
3203 
3204  // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3205  // instruction. This is safe because it is common to all FastISel supported
3206  // calling conventions on x86.
3207  for (int i = 0, e = OutVals.size(); i != e; ++i) {
3208  Value *&Val = OutVals[i];
3209  ISD::ArgFlagsTy Flags = OutFlags[i];
3210  if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3211  if (CI->getBitWidth() < 32) {
3212  if (Flags.isSExt())
3214  else
3216  }
3217  }
3218 
3219  // Passing bools around ends up doing a trunc to i1 and passing it.
3220  // Codegen this as an argument + "and 1".
3221  MVT VT;
3222  auto *TI = dyn_cast<TruncInst>(Val);
3223  unsigned ResultReg;
3224  if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3225  (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3226  TI->hasOneUse()) {
3227  Value *PrevVal = TI->getOperand(0);
3228  ResultReg = getRegForValue(PrevVal);
3229 
3230  if (!ResultReg)
3231  return false;
3232 
3233  if (!isTypeLegal(PrevVal->getType(), VT))
3234  return false;
3235 
3236  ResultReg =
3237  fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3238  } else {
3239  if (!isTypeLegal(Val->getType(), VT))
3240  return false;
3241  ResultReg = getRegForValue(Val);
3242  }
3243 
3244  if (!ResultReg)
3245  return false;
3246 
3247  ArgRegs.push_back(ResultReg);
3248  OutVTs.push_back(VT);
3249  }
3250 
3251  // Analyze operands of the call, assigning locations to each operand.
3253  CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3254 
3255  // Allocate shadow area for Win64
3256  if (IsWin64)
3257  CCInfo.AllocateStack(32, 8);
3258 
3259  CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3260 
3261  // Get a count of how many bytes are to be pushed on the stack.
3262  unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3263 
3264  // Issue CALLSEQ_START
3265  unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3266  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
3267  .addImm(NumBytes).addImm(0).addImm(0);
3268 
3269  // Walk the register/memloc assignments, inserting copies/loads.
3270  const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3271  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3272  CCValAssign const &VA = ArgLocs[i];
3273  const Value *ArgVal = OutVals[VA.getValNo()];
3274  MVT ArgVT = OutVTs[VA.getValNo()];
3275 
3276  if (ArgVT == MVT::x86mmx)
3277  return false;
3278 
3279  unsigned ArgReg = ArgRegs[VA.getValNo()];
3280 
3281  // Promote the value if needed.
3282  switch (VA.getLocInfo()) {
3283  case CCValAssign::Full: break;
3284  case CCValAssign::SExt: {
3285  assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3286  "Unexpected extend");
3287 
3288  if (ArgVT == MVT::i1)
3289  return false;
3290 
3291  bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3292  ArgVT, ArgReg);
3293  assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3294  ArgVT = VA.getLocVT();
3295  break;
3296  }
3297  case CCValAssign::ZExt: {
3298  assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3299  "Unexpected extend");
3300 
3301  // Handle zero-extension from i1 to i8, which is common.
3302  if (ArgVT == MVT::i1) {
3303  // In case SrcReg is a K register, COPY to a GPR
3304  if (MRI.getRegClass(ArgReg) == &X86::VK1RegClass) {
3305  unsigned KArgReg = ArgReg;
3306  ArgReg = createResultReg(&X86::GR32RegClass);
3307  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3308  TII.get(TargetOpcode::COPY), ArgReg)
3309  .addReg(KArgReg);
3310  ArgReg = fastEmitInst_extractsubreg(MVT::i8, ArgReg, /*Kill=*/true,
3311  X86::sub_8bit);
3312  }
3313  // Set the high bits to zero.
3314  ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3315  ArgVT = MVT::i8;
3316 
3317  if (ArgReg == 0)
3318  return false;
3319  }
3320 
3321  bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3322  ArgVT, ArgReg);
3323  assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3324  ArgVT = VA.getLocVT();
3325  break;
3326  }
3327  case CCValAssign::AExt: {
3328  assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3329  "Unexpected extend");
3330  bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3331  ArgVT, ArgReg);
3332  if (!Emitted)
3333  Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3334  ArgVT, ArgReg);
3335  if (!Emitted)
3336  Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3337  ArgVT, ArgReg);
3338 
3339  assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3340  ArgVT = VA.getLocVT();
3341  break;
3342  }
3343  case CCValAssign::BCvt: {
3344  ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3345  /*TODO: Kill=*/false);
3346  assert(ArgReg && "Failed to emit a bitcast!");
3347  ArgVT = VA.getLocVT();
3348  break;
3349  }
3350  case CCValAssign::VExt:
3351  // VExt has not been implemented, so this should be impossible to reach
3352  // for now. However, fallback to Selection DAG isel once implemented.
3353  return false;
3357  case CCValAssign::FPExt:
3358  llvm_unreachable("Unexpected loc info!");
3359  case CCValAssign::Indirect:
3360  // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3361  // support this.
3362  return false;
3363  }
3364 
3365  if (VA.isRegLoc()) {
3366  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3367  TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3368  OutRegs.push_back(VA.getLocReg());
3369  } else {
3370  assert(VA.isMemLoc());
3371 
3372  // Don't emit stores for undef values.
3373  if (isa<UndefValue>(ArgVal))
3374  continue;
3375 
3376  unsigned LocMemOffset = VA.getLocMemOffset();
3377  X86AddressMode AM;
3378  AM.Base.Reg = RegInfo->getStackRegister();
3379  AM.Disp = LocMemOffset;
3380  ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3381  unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3382  MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3383  MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3384  MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3385  if (Flags.isByVal()) {
3386  X86AddressMode SrcAM;
3387  SrcAM.Base.Reg = ArgReg;
3388  if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3389  return false;
3390  } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3391  // If this is a really simple value, emit this with the Value* version
3392  // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3393  // as it can cause us to reevaluate the argument.
3394  if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3395  return false;
3396  } else {
3397  bool ValIsKill = hasTrivialKill(ArgVal);
3398  if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3399  return false;
3400  }
3401  }
3402  }
3403 
3404  // ELF / PIC requires GOT in the EBX register before function calls via PLT
3405  // GOT pointer.
3406  if (Subtarget->isPICStyleGOT()) {
3407  unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3408  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3409  TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3410  }
3411 
3412  if (Is64Bit && IsVarArg && !IsWin64) {
3413  // From AMD64 ABI document:
3414  // For calls that may call functions that use varargs or stdargs
3415  // (prototype-less calls or calls to functions containing ellipsis (...) in
3416  // the declaration) %al is used as hidden argument to specify the number
3417  // of SSE registers used. The contents of %al do not need to match exactly
3418  // the number of registers, but must be an ubound on the number of SSE
3419  // registers used and is in the range 0 - 8 inclusive.
3420 
3421  // Count the number of XMM registers allocated.
3422  static const MCPhysReg XMMArgRegs[] = {
3423  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3424  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3425  };
3426  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3427  assert((Subtarget->hasSSE1() || !NumXMMRegs)
3428  && "SSE registers cannot be used when SSE is disabled");
3429  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3430  X86::AL).addImm(NumXMMRegs);
3431  }
3432 
3433  // Materialize callee address in a register. FIXME: GV address can be
3434  // handled with a CALLpcrel32 instead.
3435  X86AddressMode CalleeAM;
3436  if (!X86SelectCallAddress(Callee, CalleeAM))
3437  return false;
3438 
3439  unsigned CalleeOp = 0;
3440  const GlobalValue *GV = nullptr;
3441  if (CalleeAM.GV != nullptr) {
3442  GV = CalleeAM.GV;
3443  } else if (CalleeAM.Base.Reg != 0) {
3444  CalleeOp = CalleeAM.Base.Reg;
3445  } else
3446  return false;
3447 
3448  // Issue the call.
3449  MachineInstrBuilder MIB;
3450  if (CalleeOp) {
3451  // Register-indirect call.
3452  unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3453  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3454  .addReg(CalleeOp);
3455  } else {
3456  // Direct call.
3457  assert(GV && "Not a direct call");
3458  unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3459 
3460  // See if we need any target-specific flags on the GV operand.
3461  unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
3462  // Ignore NonLazyBind attribute in FastISel
3463  if (OpFlags == X86II::MO_GOTPCREL)
3464  OpFlags = 0;
3465 
3466  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3467  if (Symbol)
3468  MIB.addSym(Symbol, OpFlags);
3469  else
3470  MIB.addGlobalAddress(GV, 0, OpFlags);
3471  }
3472 
3473  // Add a register mask operand representing the call-preserved registers.
3474  // Proper defs for return values will be added by setPhysRegsDeadExcept().
3475  MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3476 
3477  // Add an implicit use GOT pointer in EBX.
3478  if (Subtarget->isPICStyleGOT())
3479  MIB.addReg(X86::EBX, RegState::Implicit);
3480 
3481  if (Is64Bit && IsVarArg && !IsWin64)
3482  MIB.addReg(X86::AL, RegState::Implicit);
3483 
3484  // Add implicit physical register uses to the call.
3485  for (auto Reg : OutRegs)
3486  MIB.addReg(Reg, RegState::Implicit);
3487 
3488  // Issue CALLSEQ_END
3489  unsigned NumBytesForCalleeToPop =
3490  X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3491  TM.Options.GuaranteedTailCallOpt)
3492  ? NumBytes // Callee pops everything.
3493  : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
3494  unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3495  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3496  .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3497 
3498  // Now handle call return values.
3500  CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3501  CLI.RetTy->getContext());
3502  CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3503 
3504  // Copy all of the result registers out of their specified physreg.
3505  unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3506  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3507  CCValAssign &VA = RVLocs[i];
3508  EVT CopyVT = VA.getValVT();
3509  unsigned CopyReg = ResultReg + i;
3510  unsigned SrcReg = VA.getLocReg();
3511 
3512  // If this is x86-64, and we disabled SSE, we can't return FP values
3513  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3514  ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3515  report_fatal_error("SSE register return with SSE disabled");
3516  }
3517 
3518  // If the return value is an i1 and AVX-512 is enabled, we need
3519  // to do a fixup to make the copy legal.
3520  if (CopyVT == MVT::i1 && SrcReg == X86::AL && Subtarget->hasAVX512()) {
3521  // Need to copy to a GR32 first.
3522  // TODO: MOVZX isn't great here. We don't care about the upper bits.
3523  SrcReg = createResultReg(&X86::GR32RegClass);
3524  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3525  TII.get(X86::MOVZX32rr8), SrcReg).addReg(X86::AL);
3526  }
3527 
3528  // If we prefer to use the value in xmm registers, copy it out as f80 and
3529  // use a truncate to move it from fp stack reg to xmm reg.
3530  if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
3531  isScalarFPTypeInSSEReg(VA.getValVT())) {
3532  CopyVT = MVT::f80;
3533  CopyReg = createResultReg(&X86::RFP80RegClass);
3534  }
3535 
3536  // Copy out the result.
3537  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3538  TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
3539  InRegs.push_back(VA.getLocReg());
3540 
3541  // Round the f80 to the right size, which also moves it to the appropriate
3542  // xmm register. This is accomplished by storing the f80 value in memory
3543  // and then loading it back.
3544  if (CopyVT != VA.getValVT()) {
3545  EVT ResVT = VA.getValVT();
3546  unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3547  unsigned MemSize = ResVT.getSizeInBits()/8;
3548  int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3549  addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3550  TII.get(Opc)), FI)
3551  .addReg(CopyReg);
3552  Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3553  addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3554  TII.get(Opc), ResultReg + i), FI);
3555  }
3556  }
3557 
3558  CLI.ResultReg = ResultReg;
3559  CLI.NumResultRegs = RVLocs.size();
3560  CLI.Call = MIB;
3561 
3562  return true;
3563 }
3564 
3565 bool
3566 X86FastISel::fastSelectInstruction(const Instruction *I) {
3567  switch (I->getOpcode()) {
3568  default: break;
3569  case Instruction::Load:
3570  return X86SelectLoad(I);
3571  case Instruction::Store:
3572  return X86SelectStore(I);
3573  case Instruction::Ret:
3574  return X86SelectRet(I);
3575  case Instruction::ICmp:
3576  case Instruction::FCmp:
3577  return X86SelectCmp(I);
3578  case Instruction::ZExt:
3579  return X86SelectZExt(I);
3580  case Instruction::Br:
3581  return X86SelectBranch(I);
3582  case Instruction::LShr:
3583  case Instruction::AShr:
3584  case Instruction::Shl:
3585  return X86SelectShift(I);
3586  case Instruction::SDiv:
3587  case Instruction::UDiv:
3588  case Instruction::SRem:
3589  case Instruction::URem:
3590  return X86SelectDivRem(I);
3591  case Instruction::Select:
3592  return X86SelectSelect(I);
3593  case Instruction::Trunc:
3594  return X86SelectTrunc(I);
3595  case Instruction::FPExt:
3596  return X86SelectFPExt(I);
3597  case Instruction::FPTrunc:
3598  return X86SelectFPTrunc(I);
3599  case Instruction::SIToFP:
3600  return X86SelectSIToFP(I);
3601  case Instruction::IntToPtr: // Deliberate fall-through.
3602  case Instruction::PtrToInt: {
3603  EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3604  EVT DstVT = TLI.getValueType(DL, I->getType());
3605  if (DstVT.bitsGT(SrcVT))
3606  return X86SelectZExt(I);
3607  if (DstVT.bitsLT(SrcVT))
3608  return X86SelectTrunc(I);
3609  unsigned Reg = getRegForValue(I->getOperand(0));
3610  if (Reg == 0) return false;
3611  updateValueMap(I, Reg);
3612  return true;
3613  }
3614  case Instruction::BitCast: {
3615  // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3616  if (!Subtarget->hasSSE2())
3617  return false;
3618 
3619  EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3620  EVT DstVT = TLI.getValueType(DL, I->getType());
3621 
3622  if (!SrcVT.isSimple() || !DstVT.isSimple())
3623  return false;
3624 
3625  MVT SVT = SrcVT.getSimpleVT();
3626  MVT DVT = DstVT.getSimpleVT();
3627 
3628  if (!SVT.is128BitVector() &&
3629  !(Subtarget->hasAVX() && SVT.is256BitVector()) &&
3630  !(Subtarget->hasAVX512() && SVT.is512BitVector() &&
3631  (Subtarget->hasBWI() || (SVT.getScalarSizeInBits() >= 32 &&
3632  DVT.getScalarSizeInBits() >= 32))))
3633  return false;
3634 
3635  unsigned Reg = getRegForValue(I->getOperand(0));
3636  if (Reg == 0)
3637  return false;
3638 
3639  // No instruction is needed for conversion. Reuse the register used by
3640  // the fist operand.
3641  updateValueMap(I, Reg);
3642  return true;
3643  }
3644  }
3645 
3646  return false;
3647 }
3648 
3649 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3650  if (VT > MVT::i64)
3651  return 0;
3652 
3653  uint64_t Imm = CI->getZExtValue();
3654  if (Imm == 0) {
3655  unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3656  switch (VT.SimpleTy) {
3657  default: llvm_unreachable("Unexpected value type");
3658  case MVT::i1:
3659  case MVT::i8:
3660  return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3661  X86::sub_8bit);
3662  case MVT::i16:
3663  return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3664  X86::sub_16bit);
3665  case MVT::i32:
3666  return SrcReg;
3667  case MVT::i64: {
3668  unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3669  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3670  TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3671  .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3672  return ResultReg;
3673  }
3674  }
3675  }
3676 
3677  unsigned Opc = 0;
3678  switch (VT.SimpleTy) {
3679  default: llvm_unreachable("Unexpected value type");
3680  case MVT::i1:
3681  // TODO: Support this properly.
3682  if (Subtarget->hasAVX512())
3683  return 0;
3684  VT = MVT::i8;
3686  case MVT::i8: Opc = X86::MOV8ri; break;
3687  case MVT::i16: Opc = X86::MOV16ri; break;
3688  case MVT::i32: Opc = X86::MOV32ri; break;
3689  case MVT::i64: {
3690  if (isUInt<32>(Imm))
3691  Opc = X86::MOV32ri;
3692  else if (isInt<32>(Imm))
3693  Opc = X86::MOV64ri32;
3694  else
3695  Opc = X86::MOV64ri;
3696  break;
3697  }
3698  }
3699  if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3700  unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3701  unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3702  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3703  TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3704  .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3705  return ResultReg;
3706  }
3707  return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3708 }
3709 
3710 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3711  if (CFP->isNullValue())
3712  return fastMaterializeFloatZero(CFP);
3713 
3714  // Can't handle alternate code models yet.
3715  CodeModel::Model CM = TM.getCodeModel();
3716  if (CM != CodeModel::Small && CM != CodeModel::Large)
3717  return 0;
3718 
3719  // Get opcode and regclass of the output for the given load instruction.
3720  unsigned Opc = 0;
3721  const TargetRegisterClass *RC = nullptr;
3722  switch (VT.SimpleTy) {
3723  default: return 0;
3724  case MVT::f32:
3725  if (X86ScalarSSEf32) {
3726  Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3727  RC = &X86::FR32RegClass;
3728  } else {
3729  Opc = X86::LD_Fp32m;
3730  RC = &X86::RFP32RegClass;
3731  }
3732  break;
3733  case MVT::f64:
3734  if (X86ScalarSSEf64) {
3735  Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3736  RC = &X86::FR64RegClass;
3737  } else {
3738  Opc = X86::LD_Fp64m;
3739  RC = &X86::RFP64RegClass;
3740  }
3741  break;
3742  case MVT::f80:
3743  // No f80 support yet.
3744  return 0;
3745  }
3746 
3747  // MachineConstantPool wants an explicit alignment.
3748  unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3749  if (Align == 0) {
3750  // Alignment of vector types. FIXME!
3751  Align = DL.getTypeAllocSize(CFP->getType());
3752  }
3753 
3754  // x86-32 PIC requires a PIC base register for constant pools.
3755  unsigned PICBase = 0;
3756  unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3757  if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
3758  PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3759  else if (OpFlag == X86II::MO_GOTOFF)
3760  PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3761  else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
3762  PICBase = X86::RIP;
3763 
3764  // Create the load from the constant pool.
3765  unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3766  unsigned ResultReg = createResultReg(RC);
3767 
3768  if (CM == CodeModel::Large) {
3769  unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3770  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3771  AddrReg)
3772  .addConstantPoolIndex(CPI, 0, OpFlag);
3773  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3774  TII.get(Opc), ResultReg);
3775  addDirectMem(MIB, AddrReg);
3776  MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3779  MIB->addMemOperand(*FuncInfo.MF, MMO);
3780  return ResultReg;
3781  }
3782 
3783  addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3784  TII.get(Opc), ResultReg),
3785  CPI, PICBase, OpFlag);
3786  return ResultReg;
3787 }
3788 
3789 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3790  // Can't handle alternate code models yet.
3791  if (TM.getCodeModel() != CodeModel::Small)
3792  return 0;
3793 
3794  // Materialize addresses with LEA/MOV instructions.
3795  X86AddressMode AM;
3796  if (X86SelectAddress(GV, AM)) {
3797  // If the expression is just a basereg, then we're done, otherwise we need
3798  // to emit an LEA.
3799  if (AM.BaseType == X86AddressMode::RegBase &&
3800  AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3801  return AM.Base.Reg;
3802 
3803  unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3804  if (TM.getRelocationModel() == Reloc::Static &&
3805  TLI.getPointerTy(DL) == MVT::i64) {
3806  // The displacement code could be more than 32 bits away so we need to use
3807  // an instruction with a 64 bit immediate
3808  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3809  ResultReg)
3810  .addGlobalAddress(GV);
3811  } else {
3812  unsigned Opc =
3813  TLI.getPointerTy(DL) == MVT::i32
3814  ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3815  : X86::LEA64r;
3816  addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3817  TII.get(Opc), ResultReg), AM);
3818  }
3819  return ResultReg;
3820  }
3821  return 0;
3822 }
3823 
3824 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3825  EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3826 
3827  // Only handle simple types.
3828  if (!CEVT.isSimple())
3829  return 0;
3830  MVT VT = CEVT.getSimpleVT();
3831 
3832  if (const auto *CI = dyn_cast<ConstantInt>(C))
3833  return X86MaterializeInt(CI, VT);
3834  else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3835  return X86MaterializeFP(CFP, VT);
3836  else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3837  return X86MaterializeGV(GV, VT);
3838 
3839  return 0;
3840 }
3841 
3842 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3843  // Fail on dynamic allocas. At this point, getRegForValue has already
3844  // checked its CSE maps, so if we're here trying to handle a dynamic
3845  // alloca, we're not going to succeed. X86SelectAddress has a
3846  // check for dynamic allocas, because it's called directly from
3847  // various places, but targetMaterializeAlloca also needs a check
3848  // in order to avoid recursion between getRegForValue,
3849  // X86SelectAddrss, and targetMaterializeAlloca.
3850  if (!FuncInfo.StaticAllocaMap.count(C))
3851  return 0;
3852  assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3853 
3854  X86AddressMode AM;
3855  if (!X86SelectAddress(C, AM))
3856  return 0;
3857  unsigned Opc =
3858  TLI.getPointerTy(DL) == MVT::i32
3859  ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3860  : X86::LEA64r;
3861  const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3862  unsigned ResultReg = createResultReg(RC);
3863  addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3864  TII.get(Opc), ResultReg), AM);
3865  return ResultReg;
3866 }
3867 
3868 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3869  MVT VT;
3870  if (!isTypeLegal(CF->getType(), VT))
3871  return 0;
3872 
3873  // Get opcode and regclass for the given zero.
3874  unsigned Opc = 0;
3875  const TargetRegisterClass *RC = nullptr;
3876  switch (VT.SimpleTy) {
3877  default: return 0;
3878  case MVT::f32:
3879  if (X86ScalarSSEf32) {
3880  Opc = X86::FsFLD0SS;
3881  RC = &X86::FR32RegClass;
3882  } else {
3883  Opc = X86::LD_Fp032;
3884  RC = &X86::RFP32RegClass;
3885  }
3886  break;
3887  case MVT::f64:
3888  if (X86ScalarSSEf64) {
3889  Opc = X86::FsFLD0SD;
3890  RC = &X86::FR64RegClass;
3891  } else {
3892  Opc = X86::LD_Fp064;
3893  RC = &X86::RFP64RegClass;
3894  }
3895  break;
3896  case MVT::f80:
3897  // No f80 support yet.
3898  return 0;
3899  }
3900 
3901  unsigned ResultReg = createResultReg(RC);
3902  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3903  return ResultReg;
3904 }
3905 
3906 
3907 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3908  const LoadInst *LI) {
3909  const Value *Ptr = LI->getPointerOperand();
3910  X86AddressMode AM;
3911  if (!X86SelectAddress(Ptr, AM))
3912  return false;
3913 
3914  const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3915 
3916  unsigned Size = DL.getTypeAllocSize(LI->getType());
3917  unsigned Alignment = LI->getAlignment();
3918 
3919  if (Alignment == 0) // Ensure that codegen never sees alignment 0
3920  Alignment = DL.getABITypeAlignment(LI->getType());
3921 
3923  AM.getFullAddress(AddrOps);
3924 
3925  MachineInstr *Result = XII.foldMemoryOperandImpl(
3926  *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3927  /*AllowCommute=*/true);
3928  if (!Result)
3929  return false;
3930 
3931  // The index register could be in the wrong register class. Unfortunately,
3932  // foldMemoryOperandImpl could have commuted the instruction so its not enough
3933  // to just look at OpNo + the offset to the index reg. We actually need to
3934  // scan the instruction to find the index reg and see if its the correct reg
3935  // class.
3936  unsigned OperandNo = 0;
3937  for (MachineInstr::mop_iterator I = Result->operands_begin(),
3938  E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3939  MachineOperand &MO = *I;
3940  if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3941  continue;
3942  // Found the index reg, now try to rewrite it.
3943  unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3944  MO.getReg(), OperandNo);
3945  if (IndexReg == MO.getReg())
3946  continue;
3947  MO.setReg(IndexReg);
3948  }
3949 
3950  Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3951  MI->eraseFromParent();
3952  return true;
3953 }
3954 
3955 unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
3956  const TargetRegisterClass *RC,
3957  unsigned Op0, bool Op0IsKill,
3958  unsigned Op1, bool Op1IsKill,
3959  unsigned Op2, bool Op2IsKill,
3960  unsigned Op3, bool Op3IsKill) {
3961  const MCInstrDesc &II = TII.get(MachineInstOpcode);
3962 
3963  unsigned ResultReg = createResultReg(RC);
3964  Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
3965  Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
3966  Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
3967  Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 3);
3968 
3969  if (II.getNumDefs() >= 1)
3970  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
3971  .addReg(Op0, getKillRegState(Op0IsKill))
3972  .addReg(Op1, getKillRegState(Op1IsKill))
3973  .addReg(Op2, getKillRegState(Op2IsKill))
3974  .addReg(Op3, getKillRegState(Op3IsKill));
3975  else {
3976  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
3977  .addReg(Op0, getKillRegState(Op0IsKill))
3978  .addReg(Op1, getKillRegState(Op1IsKill))
3979  .addReg(Op2, getKillRegState(Op2IsKill))
3980  .addReg(Op3, getKillRegState(Op3IsKill));
3981  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3982  TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
3983  }
3984  return ResultReg;
3985 }
3986 
3987 
3988 namespace llvm {
3990  const TargetLibraryInfo *libInfo) {
3991  return new X86FastISel(funcInfo, libInfo);
3992  }
3993 }
void setFrameAddressIsTaken(bool T)
unsigned GetCondBranchFromCond(CondCode CC)
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:544
constexpr bool isUInt< 32 >(uint64_t x)
Definition: MathExtras.h:341
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Return a value (possibly void), from a function.
Value * getValueOperand()
Definition: Instructions.h:395
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:144
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
mop_iterator operands_end()
Definition: MachineInstr.h:301
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:850
MVT getValVT() const
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
LocInfo getLocInfo() const
static const MachineInstrBuilder & addConstantPoolReference(const MachineInstrBuilder &MIB, unsigned CPI, unsigned GlobalBaseReg, unsigned char OpFlags)
addConstantPoolReference - This function is used to add a reference to the base of a constant value s...
bool isVolatile() const
unsigned constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II, unsigned Reg, unsigned OpIdx)
Try to constrain Reg so that it is usable by argument OpIdx of the provided MCInstrDesc II...
Definition: Utils.cpp:46
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
Definition: MCInstrDesc.h:225
unsigned getNumOperands() const
Definition: User.h:176
unsigned getRegSizeInBits(const TargetRegisterClass &RC) const
Return the size in bits of a register from class RC.
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:690
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
MachineInstrBuilder MachineInstrBuilder &DefMI const MCInstrDesc & Desc
unsigned getScalarSizeInBits() const
DataLayout DL
bool is512BitVector() const
Return true if this is a 512-bit vector type.
This class represents a function call, abstracting a target machine's calling convention.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
Definition: InstrTypes.h:958
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:866
constexpr bool isInt< 8 >(int64_t x)
Definition: MathExtras.h:295
unsigned getSizeInBits() const
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:150
unsigned getByValSize() const
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:876
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:276
This class wraps the llvm.memset intrinsic.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
const GlobalValue * GV
A debug info location.
Definition: DebugLoc.h:34
An instruction for reading from memory.
Definition: Instructions.h:164
MO_GOTPCREL - On a symbol operand this indicates that the immediate is offset to the GOT entry for th...
Definition: X86BaseInfo.h:97
Hexagon Common GEP
X86_ThisCall - Similar to X86_StdCall.
Definition: CallingConv.h:111
bool isCalleePop(CallingConv::ID CallingConv, bool is64Bit, bool IsVarArg, bool GuaranteeTCO)
Determines whether the callee is required to pop its own arguments.
unsigned getValNo() const
op_iterator op_begin()
Definition: User.h:214
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition: ISDOpcodes.h:39
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition: ValueTypes.h:241
bool isRegLoc() const
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:186
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:207
X86MachineFunctionInfo - This class is derived from MachineFunction and contains private X86 target-s...
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:871
Value * getAddress() const
Definition: IntrinsicInst.h:91
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:493
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:870
A description of a memory reference used in the backend.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
const HexagonInstrInfo * TII
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:562
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition: Function.h:150
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
Class to represent struct types.
Definition: DerivedTypes.h:201
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static bool isGlobalStubReference(unsigned char TargetFlag)
isGlobalStubReference - Return true if the specified TargetFlag operand is a reference to a stub for ...
Definition: X86InstrInfo.h:91
unsigned getNumArgOperands() const
Return the number of call arguments.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Reg
All possible values of the reg field in the ModR/M byte.
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:867
SimpleValueType SimpleTy
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1556
const Triple & getTargetTriple() const
Definition: X86Subtarget.h:521
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
union llvm::X86AddressMode::@422 Base
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:282
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:250
static bool isGlobalRelativeToPICBase(unsigned char TargetFlag)
isGlobalRelativeToPICBase - Return true if the specified global value reference is relative to a 32-b...
Definition: X86InstrInfo.h:107
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1570
unsigned getLocReg() const
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition: FastISel.h:67
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:862
#define F(x, y, z)
Definition: MD5.cpp:55
bool is64Bit() const
Is this x86_64? (disregarding specific ABI / programming model)
Definition: X86Subtarget.h:398
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getSuccessor(unsigned i) const
bool isTargetMCU() const
Definition: X86Subtarget.h:540
An instruction for storing to memory.
Definition: Instructions.h:306
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:218
void addMemOperand(MachineFunction &MF, MachineMemOperand *MO)
Add a MachineMemOperand to the machine instruction.
void setStackProtectorIndex(int I)
This class represents a truncation of integer types.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
static MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset)
Stack pointer relative access.
Class to represent pointers.
Definition: DerivedTypes.h:467
unsigned getKillRegState(bool B)
bool hasSSE2() const
Definition: X86Subtarget.h:428
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:121
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:515
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:837
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:142
std::pair< CondCode, bool > getX86ConditionCode(CmpInst::Predicate Predicate)
Return a pair of condition code for the given predicate and whether the instruction operands should b...
enum llvm::X86AddressMode::@421 BaseType
bool isInteger() const
Return true if this is an integer or a vector integer type.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:351
bool arg_empty() const
Definition: CallSite.h:215
unsigned const MachineRegisterInfo * MRI
Machine Value Type.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
DIExpression * getExpression() const
Definition: IntrinsicInst.h:97
Conditional or Unconditional Branch instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:227
MVT getLocVT() const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
This is an important base class in LLVM.
Definition: Constant.h:42
bool isVector() const
Return true if this is a vector value type.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:147
#define A
Definition: LargeTest.cpp:12
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
const MCPhysReg * ImplicitDefs
Definition: MCInstrDesc.h:173
Value * getRawDest() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:280
op_iterator op_end()
Definition: User.h:216
static std::pair< unsigned, bool > getX86SSEConditionCode(CmpInst::Predicate Predicate)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:860
static const unsigned End
TRAP - Trapping instruction.
Definition: ISDOpcodes.h:727
Value * getOperand(unsigned i) const
Definition: User.h:154
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:869
Value * getPointerOperand()
Definition: Instructions.h:270
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:934
X86_FastCall - 'fast' analog of X86_StdCall.
Definition: CallingConv.h:92
void X86SelectAddress(const MachineInstr &I, const MachineRegisterInfo &MRI, X86AddressMode &AM)
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:877
unsigned getSETFromCond(CondCode CC, bool HasMemoryOperand=false)
Return a set opcode for the given condition and whether it has a memory operand.
Extended Value Type.
Definition: ValueTypes.h:34
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:697
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:875
unsigned getStackRegister() const
static const MachineInstrBuilder & addFrameReference(const MachineInstrBuilder &MIB, int FI, int Offset=0, bool mem=true)
addFrameReference - This function is used to add a reference to the base of an abstract object on the...
The memory access writes data.
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition: ValueTypes.h:229
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:700
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:864
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:680
Iterator for intrusive lists based on ilist_node.
CCState - This class holds information needed while lowering arguments and return values...
#define E
Definition: LargeTest.cpp:27
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
constexpr bool isInt< 32 >(int64_t x)
Definition: MathExtras.h:301
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Definition: CallingConv.h:87
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:405
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:130
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:874
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Provides information about what library functions are available for the current target.
CCValAssign - Represent assignment of one arg/retval to a location.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:27
Value * getLength() const
void getFullAddress(SmallVectorImpl< MachineOperand > &MO)
This class wraps the llvm.memcpy intrinsic.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:86
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:35
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
bool is128BitVector() const
Return true if this is a 128-bit vector type.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
virtual const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const
Return a mask of call-preserved registers for the given calling convention on the current function...
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
This file defines the FastISel class.
unsigned getCMovFromCond(CondCode CC, unsigned RegBytes, bool HasMemoryOperand=false)
Return a cmov opcode for the given condition, register size in bytes, and operand type...
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:444
bool isMemLoc() const
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:447
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned char TargetFlags=0) const
bool hasSSE1() const
Definition: X86Subtarget.h:427
The C convention as implemented on Windows/x86-64 and AArch64.
Definition: CallingConv.h:154
llvm_unreachable("Unknown RegBank!")
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:215
The memory access reads data.
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS=nullptr) const override
foldMemoryOperand - If this target supports it, fold a load or store of the specified stack slot into...
Representation of each machine instruction.
Definition: MachineInstr.h:59
MO_GOTOFF - On a symbol operand this indicates that the immediate is the offset to the location of th...
Definition: X86BaseInfo.h:89
static const MachineInstrBuilder & addDirectMem(const MachineInstrBuilder &MIB, unsigned Reg)
addDirectMem - This function is used to add a direct memory reference to the current instruction – th...
Value * getCondition() const
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:361
bool is256BitVector() const
Return true if this is a 256-bit vector type.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the call or the callee has the given attribute.
Definition: CallSite.h:374
#define C
Definition: LargeTest.cpp:25
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:226
Establish a view to a call site for examination.
Definition: CallSite.h:687
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:292
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
bool isOSMSVCRT() const
Is this a "Windows" OS targeting a "MSVCRT.dll" environment.
Definition: Triple.h:545
void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:408
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:868
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:43
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:872
constexpr bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:338
static MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS, const AllocaInst *Alloca=nullptr)
Create a new statically sized stack object, returning a nonnegative identifier to represent it...
Value * getRawSource() const
Return the arguments to the instruction.
unsigned getReg() const
getReg - Returns the register number.
DILocalVariable * getVariable() const
Definition: IntrinsicInst.h:93
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void GetReturnInfo(Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags...
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition: ValueTypes.h:126
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:863
LLVM Value Representation.
Definition: Value.h:73
mop_iterator operands_begin()
Definition: MachineInstr.h:300
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:873
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:121
static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC)
If we have a comparison with RHS as the RHS of the comparison, return an opcode that works for the co...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
unsigned getDestAddressSpace() const
MO_PIC_BASE_OFFSET - On a symbol operand this indicates that the immediate should get the value of th...
Definition: X86BaseInfo.h:75
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this variable.
IRTranslator LLVM IR MI
unsigned getLocMemOffset() const
Conversion operators.
Definition: ISDOpcodes.h:441
int * Ptr
X86AddressMode - This struct holds a generalized full x86 address mode.
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:603
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:157
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:865
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
This represents the llvm.dbg.declare instruction.
Definition: IntrinsicInst.h:89
unsigned getSourceAddressSpace() const
Value * getPointerOperand()
Definition: Instructions.h:398
unsigned AllocateStack(unsigned Size, unsigned Align)
AllocateStack - Allocate a chunk of stack space with the specified size and alignment.
const BasicBlock * getParent() const
Definition: Instruction.h:66
static const MachineInstrBuilder & addFullAddress(const MachineInstrBuilder &MIB, const X86AddressMode &AM)
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition: ISDOpcodes.h:349
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo)
bool hasAVX() const
Definition: X86Subtarget.h:433
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:253
iterator_range< arg_iterator > args()
Definition: Function.h:613
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:862
static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget, CallingConv::ID CC, ImmutableCallSite *CS)
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget)
an instruction to allocate memory on the stack
Definition: Instructions.h:60
gep_type_iterator gep_type_begin(const User *GEP)
unsigned getPtrSizedFrameRegister(const MachineFunction &MF) const
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:568
bool contains(unsigned Reg) const
Return true if the specified register is included in this register class.