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