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