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