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