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