CostModel: initial checkin for code that estimates the cost of special shuffles.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering 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 interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161
162   RegInfo = TM.getRegisterInfo();
163   TD = getDataLayout();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom())
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184   // Bypass i32 with i8 on Atom when compiling with O2
185   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186     addBypassSlowDiv(32, 8);
187
188   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189     // Setup Windows compiler runtime calls.
190     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192     setLibcallName(RTLIB::SREM_I64, "_allrem");
193     setLibcallName(RTLIB::UREM_I64, "_aullrem");
194     setLibcallName(RTLIB::MUL_I64, "_allmul");
195     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201     // The _ftol2 runtime function has an unusual calling conv, which
202     // is modeled by a special pseudo-instruction.
203     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207   }
208
209   if (Subtarget->isTargetDarwin()) {
210     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211     setUseUnderscoreSetJmp(false);
212     setUseUnderscoreLongJmp(false);
213   } else if (Subtarget->isTargetMingw()) {
214     // MS runtime is weird: it exports _setjmp, but longjmp!
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(false);
217   } else {
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(true);
220   }
221
222   // Set up the register classes.
223   addRegisterClass(MVT::i8, &X86::GR8RegClass);
224   addRegisterClass(MVT::i16, &X86::GR16RegClass);
225   addRegisterClass(MVT::i32, &X86::GR32RegClass);
226   if (Subtarget->is64Bit())
227     addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231   // We don't accept any truncstore of integer registers.
232   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239   // SETOEQ and SETUNE require checking two conditions.
240   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248   // operation.
249   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253   if (Subtarget->is64Bit()) {
254     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256   } else if (!TM.Options.UseSoftFloat) {
257     // We have an algorithm for SSE2->double, and we turn this into a
258     // 64-bit FILD followed by conditional FADD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260     // We have an algorithm for SSE2, and we turn this into a 64-bit
261     // FILD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263   }
264
265   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266   // this operation.
267   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270   if (!TM.Options.UseSoftFloat) {
271     // SSE has no i16 to fp conversion, only i32
272     if (X86ScalarSSEf32) {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274       // f32 and f64 cases are Legal, f80 case is not
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     } else {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     }
280   } else {
281     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283   }
284
285   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286   // are Legal, f80 is custom lowered.
287   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291   // this operation.
292   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295   if (X86ScalarSSEf32) {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297     // f32 and f64 cases are Legal, f80 case is not
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   } else {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   }
303
304   // Handle FP_TO_UINT by promoting the destination to a larger signed
305   // conversion.
306   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310   if (Subtarget->is64Bit()) {
311     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313   } else if (!TM.Options.UseSoftFloat) {
314     // Since AVX is a superset of SSE3, only check for SSE here.
315     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316       // Expand FP_TO_UINT into a select.
317       // FIXME: We would like to use a Custom expander here eventually to do
318       // the optimal thing for SSE vs. the default expansion in the legalizer.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320     else
321       // With SSE3 we can use fisttpll to convert to a signed i64; without
322       // SSE, we're stuck with a fistpll.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324   }
325
326   if (isTargetFTOL()) {
327     // Use the _ftol2 runtime function, which has a pseudo-instruction
328     // to handle its weird calling convention.
329     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330   }
331
332   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333   if (!X86ScalarSSEf64) {
334     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336     if (Subtarget->is64Bit()) {
337       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338       // Without SSE, i64->f64 goes through memory.
339       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340     }
341   }
342
343   // Scalar integer divide and remainder are lowered to use operations that
344   // produce two results, to match the available instructions. This exposes
345   // the two-result form to trivial CSE, which is able to combine x/y and x%y
346   // into a single instruction.
347   //
348   // Scalar integer multiply-high is also lowered to use two-result
349   // operations, to match the available instructions. However, plain multiply
350   // (low) operations are left as Legal, as there are single-result
351   // instructions for this in x86. Using the two-result multiply instructions
352   // when both high and low results are needed must be arranged by dagcombine.
353   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354     MVT VT = IntVTs[i];
355     setOperationAction(ISD::MULHS, VT, Expand);
356     setOperationAction(ISD::MULHU, VT, Expand);
357     setOperationAction(ISD::SDIV, VT, Expand);
358     setOperationAction(ISD::UDIV, VT, Expand);
359     setOperationAction(ISD::SREM, VT, Expand);
360     setOperationAction(ISD::UREM, VT, Expand);
361
362     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363     setOperationAction(ISD::ADDC, VT, Custom);
364     setOperationAction(ISD::ADDE, VT, Custom);
365     setOperationAction(ISD::SUBC, VT, Custom);
366     setOperationAction(ISD::SUBE, VT, Custom);
367   }
368
369   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373   if (Subtarget->is64Bit())
374     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384   // Promote the i8 variants and force them on up to i32 which has a shorter
385   // encoding.
386   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390   if (Subtarget->hasBMI()) {
391     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393     if (Subtarget->is64Bit())
394       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395   } else {
396     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasLZCNT()) {
403     // When promoting the i8 variants, force them to i32 for a shorter
404     // encoding.
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411     if (Subtarget->is64Bit())
412       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413   } else {
414     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420     if (Subtarget->is64Bit()) {
421       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423     }
424   }
425
426   if (Subtarget->hasPOPCNT()) {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428   } else {
429     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432     if (Subtarget->is64Bit())
433       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434   }
435
436   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439   // These should be promoted to a larger select which is supported.
440   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441   // X86 wants to expand cmov itself.
442   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454   if (Subtarget->is64Bit()) {
455     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457   }
458   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461   // support continuation, user-level threading, and etc.. As a result, no
462   // other SjLj exception interfaces are implemented and please don't build
463   // your own exception handling based on them.
464   // LLVM/Clang supports zero-cost DWARF exception handling.
465   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468   // Darwin ABI issue.
469   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473   if (Subtarget->is64Bit())
474     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483   }
484   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488   if (Subtarget->is64Bit()) {
489     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasSSE1())
495     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500   // On X86 and X86-64, atomic operations are lowered to locked instructions.
501   // Locked instructions, in turn, have implicit fence semantics (all memory
502   // operations are flushed before issuing the locked instruction, and they
503   // are not buffered), so we can fold away the common pattern of
504   // fence-atomic-fence.
505   setShouldFoldAtomicFences(true);
506
507   // Expand certain atomics
508   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509     MVT VT = IntVTs[i];
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513   }
514
515   if (!Subtarget->is64Bit()) {
516     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528   }
529
530   if (Subtarget->hasCmpxchg16b()) {
531     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532   }
533
534   // FIXME - use subtarget debug flags
535   if (!Subtarget->isTargetDarwin() &&
536       !Subtarget->isTargetELF() &&
537       !Subtarget->isTargetCygMing()) {
538     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539   }
540
541   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545   if (Subtarget->is64Bit()) {
546     setExceptionPointerRegister(X86::RAX);
547     setExceptionSelectorRegister(X86::RDX);
548   } else {
549     setExceptionPointerRegister(X86::EAX);
550     setExceptionSelectorRegister(X86::EDX);
551   }
552   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558   setOperationAction(ISD::TRAP, MVT::Other, Legal);
559   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730     MVT VT = (MVT::SimpleValueType)i;
731     setOperationAction(ISD::ADD , VT, Expand);
732     setOperationAction(ISD::SUB , VT, Expand);
733     setOperationAction(ISD::FADD, VT, Expand);
734     setOperationAction(ISD::FNEG, VT, Expand);
735     setOperationAction(ISD::FSUB, VT, Expand);
736     setOperationAction(ISD::MUL , VT, Expand);
737     setOperationAction(ISD::FMUL, VT, Expand);
738     setOperationAction(ISD::SDIV, VT, Expand);
739     setOperationAction(ISD::UDIV, VT, Expand);
740     setOperationAction(ISD::FDIV, VT, Expand);
741     setOperationAction(ISD::SREM, VT, Expand);
742     setOperationAction(ISD::UREM, VT, Expand);
743     setOperationAction(ISD::LOAD, VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749     setOperationAction(ISD::FABS, VT, Expand);
750     setOperationAction(ISD::FSIN, VT, Expand);
751     setOperationAction(ISD::FCOS, VT, Expand);
752     setOperationAction(ISD::FREM, VT, Expand);
753     setOperationAction(ISD::FMA,  VT, Expand);
754     setOperationAction(ISD::FPOWI, VT, Expand);
755     setOperationAction(ISD::FSQRT, VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757     setOperationAction(ISD::FFLOOR, VT, Expand);
758     setOperationAction(ISD::FCEIL, VT, Expand);
759     setOperationAction(ISD::FTRUNC, VT, Expand);
760     setOperationAction(ISD::FRINT, VT, Expand);
761     setOperationAction(ISD::FNEARBYINT, VT, Expand);
762     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764     setOperationAction(ISD::SDIVREM, VT, Expand);
765     setOperationAction(ISD::UDIVREM, VT, Expand);
766     setOperationAction(ISD::FPOW, VT, Expand);
767     setOperationAction(ISD::CTPOP, VT, Expand);
768     setOperationAction(ISD::CTTZ, VT, Expand);
769     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770     setOperationAction(ISD::CTLZ, VT, Expand);
771     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772     setOperationAction(ISD::SHL, VT, Expand);
773     setOperationAction(ISD::SRA, VT, Expand);
774     setOperationAction(ISD::SRL, VT, Expand);
775     setOperationAction(ISD::ROTL, VT, Expand);
776     setOperationAction(ISD::ROTR, VT, Expand);
777     setOperationAction(ISD::BSWAP, VT, Expand);
778     setOperationAction(ISD::SETCC, VT, Expand);
779     setOperationAction(ISD::FLOG, VT, Expand);
780     setOperationAction(ISD::FLOG2, VT, Expand);
781     setOperationAction(ISD::FLOG10, VT, Expand);
782     setOperationAction(ISD::FEXP, VT, Expand);
783     setOperationAction(ISD::FEXP2, VT, Expand);
784     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789     setOperationAction(ISD::TRUNCATE, VT, Expand);
790     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793     setOperationAction(ISD::VSELECT, VT, Expand);
794     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796       setTruncStoreAction(VT,
797                           (MVT::SimpleValueType)InnerVT, Expand);
798     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
801   }
802
803   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804   // with -msoft-float, disable use of MMX as well.
805   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807     // No operations on x86mmx supported, everything uses intrinsics.
808   }
809
810   // MMX-sized vectors (other than x86mmx) are expected to be expanded
811   // into smaller operations.
812   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
813   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
814   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
815   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
816   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
817   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
818   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
819   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
820   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
821   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
822   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
823   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
824   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
825   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
826   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
827   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
828   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
829   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
830   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
831   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
832   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
833   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
834   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
835   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
836   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
837   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
838   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
839   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
840   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
841
842   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
844
845     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
846     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
847     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
848     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
849     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
850     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
851     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
852     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
853     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
854     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
855     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
857   }
858
859   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
861
862     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863     // registers cannot be used even for integer operations.
864     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
868
869     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
870     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
871     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
872     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
874     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
875     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
876     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
877     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
878     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
879     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
880     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
881     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
882     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
883     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
884     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
885     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
886     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
887
888     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
889     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
890     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
891     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
892
893     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
894     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
895     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
898
899     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901       MVT VT = (MVT::SimpleValueType)i;
902       // Do not attempt to custom lower non-power-of-2 vectors
903       if (!isPowerOf2_32(VT.getVectorNumElements()))
904         continue;
905       // Do not attempt to custom lower non-128-bit vectors
906       if (!VT.is128BitVector())
907         continue;
908       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
909       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911     }
912
913     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
916     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
917     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
919
920     if (Subtarget->is64Bit()) {
921       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
922       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
923     }
924
925     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927       MVT VT = (MVT::SimpleValueType)i;
928
929       // Do not attempt to promote non-128-bit vectors
930       if (!VT.is128BitVector())
931         continue;
932
933       setOperationAction(ISD::AND,    VT, Promote);
934       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
935       setOperationAction(ISD::OR,     VT, Promote);
936       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
937       setOperationAction(ISD::XOR,    VT, Promote);
938       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
939       setOperationAction(ISD::LOAD,   VT, Promote);
940       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
941       setOperationAction(ISD::SELECT, VT, Promote);
942       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
943     }
944
945     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
946
947     // Custom lower v2i64 and v2f64 selects.
948     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
950     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
951     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
952
953     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
954     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
955
956     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
957     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
958     // As there is no 64-bit GPR available, we need build a special custom
959     // sequence to convert from v2i32 to v2f32.
960     if (!Subtarget->is64Bit())
961       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
962
963     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
964     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
965
966     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
967   }
968
969   if (Subtarget->hasSSE41()) {
970     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
971     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
972     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
973     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
974     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
975     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
976     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
977     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
978     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
979     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
980
981     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
982     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
983     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
984     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
985     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
986     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
987     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
988     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
989     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
990     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
991
992     // FIXME: Do we need to handle scalar-to-vector here?
993     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
994
995     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
996     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
997     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
998     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
999     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1000
1001     // i8 and i16 vectors are custom , because the source register and source
1002     // source memory operand types are not the same width.  f32 vectors are
1003     // custom since the immediate controlling the insert encodes additional
1004     // information.
1005     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1009
1010     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014
1015     // FIXME: these should be Legal but thats only for the case where
1016     // the index is constant.  For now custom expand to deal with that.
1017     if (Subtarget->is64Bit()) {
1018       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1019       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020     }
1021   }
1022
1023   if (Subtarget->hasSSE2()) {
1024     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1026
1027     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1028     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1029
1030     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1031     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1032
1033     if (Subtarget->hasInt256()) {
1034       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1035       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1036
1037       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1038       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1039
1040       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1041     } else {
1042       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1043       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1044
1045       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1046       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1047
1048       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1049     }
1050   }
1051
1052   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1053     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1059
1060     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1063
1064     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1076
1077     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1089
1090     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1091     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1092
1093     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1094
1095     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1096     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1097     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1098
1099     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1100     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1101     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1102
1103     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1104
1105     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1106     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1107
1108     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1109     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1110
1111     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1112     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1113
1114     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1115     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1116     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1117     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1118
1119     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1120     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1121     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1122
1123     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1124     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1125     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1126     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1127
1128     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1129     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1130     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1131     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1132     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1133     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1134
1135     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1136       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1137       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1138       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1139       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1140       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1141       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1142     }
1143
1144     if (Subtarget->hasInt256()) {
1145       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1146       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1147       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1148       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1149
1150       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1151       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1152       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1153       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1154
1155       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1156       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1157       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1158       // Don't lower v32i8 because there is no 128-bit byte mul
1159
1160       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1161
1162       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1164
1165       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1166       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1167
1168       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1169     } else {
1170       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1171       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1173       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1174
1175       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1176       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1178       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1179
1180       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1183       // Don't lower v32i8 because there is no 128-bit byte mul
1184
1185       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1187
1188       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1189       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1190
1191       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1192     }
1193
1194     // Custom lower several nodes for 256-bit types.
1195     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1196              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1197       MVT VT = (MVT::SimpleValueType)i;
1198
1199       // Extract subvector is special because the value type
1200       // (result) is 128-bit but the source is 256-bit wide.
1201       if (VT.is128BitVector())
1202         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1203
1204       // Do not attempt to custom lower other non-256-bit vectors
1205       if (!VT.is256BitVector())
1206         continue;
1207
1208       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1209       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1210       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1211       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1213       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1214       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1215     }
1216
1217     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1218     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1219       MVT VT = (MVT::SimpleValueType)i;
1220
1221       // Do not attempt to promote non-256-bit vectors
1222       if (!VT.is256BitVector())
1223         continue;
1224
1225       setOperationAction(ISD::AND,    VT, Promote);
1226       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1227       setOperationAction(ISD::OR,     VT, Promote);
1228       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1229       setOperationAction(ISD::XOR,    VT, Promote);
1230       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1231       setOperationAction(ISD::LOAD,   VT, Promote);
1232       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1233       setOperationAction(ISD::SELECT, VT, Promote);
1234       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1235     }
1236   }
1237
1238   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1239   // of this type with custom code.
1240   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1241            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1242     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1243                        Custom);
1244   }
1245
1246   // We want to custom lower some of our intrinsics.
1247   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1248   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1249
1250   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1251   // handle type legalization for these operations here.
1252   //
1253   // FIXME: We really should do custom legalization for addition and
1254   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1255   // than generic legalization for 64-bit multiplication-with-overflow, though.
1256   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1257     // Add/Sub/Mul with overflow operations are custom lowered.
1258     MVT VT = IntVTs[i];
1259     setOperationAction(ISD::SADDO, VT, Custom);
1260     setOperationAction(ISD::UADDO, VT, Custom);
1261     setOperationAction(ISD::SSUBO, VT, Custom);
1262     setOperationAction(ISD::USUBO, VT, Custom);
1263     setOperationAction(ISD::SMULO, VT, Custom);
1264     setOperationAction(ISD::UMULO, VT, Custom);
1265   }
1266
1267   // There are no 8-bit 3-address imul/mul instructions
1268   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1269   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1270
1271   if (!Subtarget->is64Bit()) {
1272     // These libcalls are not available in 32-bit.
1273     setLibcallName(RTLIB::SHL_I128, 0);
1274     setLibcallName(RTLIB::SRL_I128, 0);
1275     setLibcallName(RTLIB::SRA_I128, 0);
1276   }
1277
1278   // We have target-specific dag combine patterns for the following nodes:
1279   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1280   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1281   setTargetDAGCombine(ISD::VSELECT);
1282   setTargetDAGCombine(ISD::SELECT);
1283   setTargetDAGCombine(ISD::SHL);
1284   setTargetDAGCombine(ISD::SRA);
1285   setTargetDAGCombine(ISD::SRL);
1286   setTargetDAGCombine(ISD::OR);
1287   setTargetDAGCombine(ISD::AND);
1288   setTargetDAGCombine(ISD::ADD);
1289   setTargetDAGCombine(ISD::FADD);
1290   setTargetDAGCombine(ISD::FSUB);
1291   setTargetDAGCombine(ISD::FMA);
1292   setTargetDAGCombine(ISD::SUB);
1293   setTargetDAGCombine(ISD::LOAD);
1294   setTargetDAGCombine(ISD::STORE);
1295   setTargetDAGCombine(ISD::ZERO_EXTEND);
1296   setTargetDAGCombine(ISD::ANY_EXTEND);
1297   setTargetDAGCombine(ISD::SIGN_EXTEND);
1298   setTargetDAGCombine(ISD::TRUNCATE);
1299   setTargetDAGCombine(ISD::SINT_TO_FP);
1300   setTargetDAGCombine(ISD::SETCC);
1301   if (Subtarget->is64Bit())
1302     setTargetDAGCombine(ISD::MUL);
1303   setTargetDAGCombine(ISD::XOR);
1304
1305   computeRegisterProperties();
1306
1307   // On Darwin, -Os means optimize for size without hurting performance,
1308   // do not reduce the limit.
1309   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1310   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1311   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1312   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1313   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1314   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1315   setPrefLoopAlignment(4); // 2^4 bytes.
1316   benefitFromCodePlacementOpt = true;
1317
1318   // Predictable cmov don't hurt on atom because it's in-order.
1319   predictableSelectIsExpensive = !Subtarget->isAtom();
1320
1321   setPrefFunctionAlignment(4); // 2^4 bytes.
1322 }
1323
1324 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1325   if (!VT.isVector()) return MVT::i8;
1326   return VT.changeVectorElementTypeToInteger();
1327 }
1328
1329 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1330 /// the desired ByVal argument alignment.
1331 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1332   if (MaxAlign == 16)
1333     return;
1334   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1335     if (VTy->getBitWidth() == 128)
1336       MaxAlign = 16;
1337   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1338     unsigned EltAlign = 0;
1339     getMaxByValAlign(ATy->getElementType(), EltAlign);
1340     if (EltAlign > MaxAlign)
1341       MaxAlign = EltAlign;
1342   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1343     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1344       unsigned EltAlign = 0;
1345       getMaxByValAlign(STy->getElementType(i), EltAlign);
1346       if (EltAlign > MaxAlign)
1347         MaxAlign = EltAlign;
1348       if (MaxAlign == 16)
1349         break;
1350     }
1351   }
1352 }
1353
1354 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1355 /// function arguments in the caller parameter area. For X86, aggregates
1356 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1357 /// are at 4-byte boundaries.
1358 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1359   if (Subtarget->is64Bit()) {
1360     // Max of 8 and alignment of type.
1361     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1362     if (TyAlign > 8)
1363       return TyAlign;
1364     return 8;
1365   }
1366
1367   unsigned Align = 4;
1368   if (Subtarget->hasSSE1())
1369     getMaxByValAlign(Ty, Align);
1370   return Align;
1371 }
1372
1373 /// getOptimalMemOpType - Returns the target specific optimal type for load
1374 /// and store operations as a result of memset, memcpy, and memmove
1375 /// lowering. If DstAlign is zero that means it's safe to destination
1376 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1377 /// means there isn't a need to check it against alignment requirement,
1378 /// probably because the source does not need to be loaded. If 'IsMemset' is
1379 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1380 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1381 /// source is constant so it does not need to be loaded.
1382 /// It returns EVT::Other if the type should be determined using generic
1383 /// target-independent logic.
1384 EVT
1385 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1386                                        unsigned DstAlign, unsigned SrcAlign,
1387                                        bool IsMemset, bool ZeroMemset,
1388                                        bool MemcpyStrSrc,
1389                                        MachineFunction &MF) const {
1390   const Function *F = MF.getFunction();
1391   if ((!IsMemset || ZeroMemset) &&
1392       !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1393     if (Size >= 16 &&
1394         (Subtarget->isUnalignedMemAccessFast() ||
1395          ((DstAlign == 0 || DstAlign >= 16) &&
1396           (SrcAlign == 0 || SrcAlign >= 16)))) {
1397       if (Size >= 32) {
1398         if (Subtarget->hasInt256())
1399           return MVT::v8i32;
1400         if (Subtarget->hasFp256())
1401           return MVT::v8f32;
1402       }
1403       if (Subtarget->hasSSE2())
1404         return MVT::v4i32;
1405       if (Subtarget->hasSSE1())
1406         return MVT::v4f32;
1407     } else if (!MemcpyStrSrc && Size >= 8 &&
1408                !Subtarget->is64Bit() &&
1409                Subtarget->hasSSE2()) {
1410       // Do not use f64 to lower memcpy if source is string constant. It's
1411       // better to use i32 to avoid the loads.
1412       return MVT::f64;
1413     }
1414   }
1415   if (Subtarget->is64Bit() && Size >= 8)
1416     return MVT::i64;
1417   return MVT::i32;
1418 }
1419
1420 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1421   if (VT == MVT::f32)
1422     return X86ScalarSSEf32;
1423   else if (VT == MVT::f64)
1424     return X86ScalarSSEf64;
1425   return true;
1426 }
1427
1428 bool
1429 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1430   if (Fast)
1431     *Fast = Subtarget->isUnalignedMemAccessFast();
1432   return true;
1433 }
1434
1435 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1436 /// current function.  The returned value is a member of the
1437 /// MachineJumpTableInfo::JTEntryKind enum.
1438 unsigned X86TargetLowering::getJumpTableEncoding() const {
1439   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1440   // symbol.
1441   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1442       Subtarget->isPICStyleGOT())
1443     return MachineJumpTableInfo::EK_Custom32;
1444
1445   // Otherwise, use the normal jump table encoding heuristics.
1446   return TargetLowering::getJumpTableEncoding();
1447 }
1448
1449 const MCExpr *
1450 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1451                                              const MachineBasicBlock *MBB,
1452                                              unsigned uid,MCContext &Ctx) const{
1453   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1454          Subtarget->isPICStyleGOT());
1455   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1456   // entries.
1457   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1458                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1459 }
1460
1461 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1462 /// jumptable.
1463 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1464                                                     SelectionDAG &DAG) const {
1465   if (!Subtarget->is64Bit())
1466     // This doesn't have DebugLoc associated with it, but is not really the
1467     // same as a Register.
1468     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1469   return Table;
1470 }
1471
1472 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1473 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1474 /// MCExpr.
1475 const MCExpr *X86TargetLowering::
1476 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1477                              MCContext &Ctx) const {
1478   // X86-64 uses RIP relative addressing based on the jump table label.
1479   if (Subtarget->isPICStyleRIPRel())
1480     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1481
1482   // Otherwise, the reference is relative to the PIC base.
1483   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1484 }
1485
1486 // FIXME: Why this routine is here? Move to RegInfo!
1487 std::pair<const TargetRegisterClass*, uint8_t>
1488 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1489   const TargetRegisterClass *RRC = 0;
1490   uint8_t Cost = 1;
1491   switch (VT.SimpleTy) {
1492   default:
1493     return TargetLowering::findRepresentativeClass(VT);
1494   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1495     RRC = Subtarget->is64Bit() ?
1496       (const TargetRegisterClass*)&X86::GR64RegClass :
1497       (const TargetRegisterClass*)&X86::GR32RegClass;
1498     break;
1499   case MVT::x86mmx:
1500     RRC = &X86::VR64RegClass;
1501     break;
1502   case MVT::f32: case MVT::f64:
1503   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1504   case MVT::v4f32: case MVT::v2f64:
1505   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1506   case MVT::v4f64:
1507     RRC = &X86::VR128RegClass;
1508     break;
1509   }
1510   return std::make_pair(RRC, Cost);
1511 }
1512
1513 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1514                                                unsigned &Offset) const {
1515   if (!Subtarget->isTargetLinux())
1516     return false;
1517
1518   if (Subtarget->is64Bit()) {
1519     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1520     Offset = 0x28;
1521     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1522       AddressSpace = 256;
1523     else
1524       AddressSpace = 257;
1525   } else {
1526     // %gs:0x14 on i386
1527     Offset = 0x14;
1528     AddressSpace = 256;
1529   }
1530   return true;
1531 }
1532
1533 //===----------------------------------------------------------------------===//
1534 //               Return Value Calling Convention Implementation
1535 //===----------------------------------------------------------------------===//
1536
1537 #include "X86GenCallingConv.inc"
1538
1539 bool
1540 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1541                                   MachineFunction &MF, bool isVarArg,
1542                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1543                         LLVMContext &Context) const {
1544   SmallVector<CCValAssign, 16> RVLocs;
1545   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1546                  RVLocs, Context);
1547   return CCInfo.CheckReturn(Outs, RetCC_X86);
1548 }
1549
1550 SDValue
1551 X86TargetLowering::LowerReturn(SDValue Chain,
1552                                CallingConv::ID CallConv, bool isVarArg,
1553                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1554                                const SmallVectorImpl<SDValue> &OutVals,
1555                                DebugLoc dl, SelectionDAG &DAG) const {
1556   MachineFunction &MF = DAG.getMachineFunction();
1557   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1558
1559   SmallVector<CCValAssign, 16> RVLocs;
1560   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1561                  RVLocs, *DAG.getContext());
1562   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1563
1564   // Add the regs to the liveout set for the function.
1565   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1566   for (unsigned i = 0; i != RVLocs.size(); ++i)
1567     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1568       MRI.addLiveOut(RVLocs[i].getLocReg());
1569
1570   SDValue Flag;
1571
1572   SmallVector<SDValue, 6> RetOps;
1573   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1574   // Operand #1 = Bytes To Pop
1575   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1576                    MVT::i16));
1577
1578   // Copy the result values into the output registers.
1579   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1580     CCValAssign &VA = RVLocs[i];
1581     assert(VA.isRegLoc() && "Can only return in registers!");
1582     SDValue ValToCopy = OutVals[i];
1583     EVT ValVT = ValToCopy.getValueType();
1584
1585     // Promote values to the appropriate types
1586     if (VA.getLocInfo() == CCValAssign::SExt)
1587       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1588     else if (VA.getLocInfo() == CCValAssign::ZExt)
1589       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1590     else if (VA.getLocInfo() == CCValAssign::AExt)
1591       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1592     else if (VA.getLocInfo() == CCValAssign::BCvt)
1593       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1594
1595     // If this is x86-64, and we disabled SSE, we can't return FP values,
1596     // or SSE or MMX vectors.
1597     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1598          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1599           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1600       report_fatal_error("SSE register return with SSE disabled");
1601     }
1602     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1603     // llvm-gcc has never done it right and no one has noticed, so this
1604     // should be OK for now.
1605     if (ValVT == MVT::f64 &&
1606         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1607       report_fatal_error("SSE2 register return with SSE2 disabled");
1608
1609     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1610     // the RET instruction and handled by the FP Stackifier.
1611     if (VA.getLocReg() == X86::ST0 ||
1612         VA.getLocReg() == X86::ST1) {
1613       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1614       // change the value to the FP stack register class.
1615       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1616         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1617       RetOps.push_back(ValToCopy);
1618       // Don't emit a copytoreg.
1619       continue;
1620     }
1621
1622     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1623     // which is returned in RAX / RDX.
1624     if (Subtarget->is64Bit()) {
1625       if (ValVT == MVT::x86mmx) {
1626         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1627           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1628           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1629                                   ValToCopy);
1630           // If we don't have SSE2 available, convert to v4f32 so the generated
1631           // register is legal.
1632           if (!Subtarget->hasSSE2())
1633             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1634         }
1635       }
1636     }
1637
1638     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1639     Flag = Chain.getValue(1);
1640   }
1641
1642   // The x86-64 ABI for returning structs by value requires that we copy
1643   // the sret argument into %rax for the return. We saved the argument into
1644   // a virtual register in the entry block, so now we copy the value out
1645   // and into %rax.
1646   if (Subtarget->is64Bit() &&
1647       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1648     MachineFunction &MF = DAG.getMachineFunction();
1649     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1650     unsigned Reg = FuncInfo->getSRetReturnReg();
1651     assert(Reg &&
1652            "SRetReturnReg should have been set in LowerFormalArguments().");
1653     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1654
1655     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1656     Flag = Chain.getValue(1);
1657
1658     // RAX now acts like a return value.
1659     MRI.addLiveOut(X86::RAX);
1660   }
1661
1662   RetOps[0] = Chain;  // Update chain.
1663
1664   // Add the flag if we have it.
1665   if (Flag.getNode())
1666     RetOps.push_back(Flag);
1667
1668   return DAG.getNode(X86ISD::RET_FLAG, dl,
1669                      MVT::Other, &RetOps[0], RetOps.size());
1670 }
1671
1672 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1673   if (N->getNumValues() != 1)
1674     return false;
1675   if (!N->hasNUsesOfValue(1, 0))
1676     return false;
1677
1678   SDValue TCChain = Chain;
1679   SDNode *Copy = *N->use_begin();
1680   if (Copy->getOpcode() == ISD::CopyToReg) {
1681     // If the copy has a glue operand, we conservatively assume it isn't safe to
1682     // perform a tail call.
1683     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1684       return false;
1685     TCChain = Copy->getOperand(0);
1686   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1687     return false;
1688
1689   bool HasRet = false;
1690   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1691        UI != UE; ++UI) {
1692     if (UI->getOpcode() != X86ISD::RET_FLAG)
1693       return false;
1694     HasRet = true;
1695   }
1696
1697   if (!HasRet)
1698     return false;
1699
1700   Chain = TCChain;
1701   return true;
1702 }
1703
1704 MVT
1705 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1706                                             ISD::NodeType ExtendKind) const {
1707   MVT ReturnMVT;
1708   // TODO: Is this also valid on 32-bit?
1709   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1710     ReturnMVT = MVT::i8;
1711   else
1712     ReturnMVT = MVT::i32;
1713
1714   MVT MinVT = getRegisterType(ReturnMVT);
1715   return VT.bitsLT(MinVT) ? MinVT : VT;
1716 }
1717
1718 /// LowerCallResult - Lower the result values of a call into the
1719 /// appropriate copies out of appropriate physical registers.
1720 ///
1721 SDValue
1722 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1723                                    CallingConv::ID CallConv, bool isVarArg,
1724                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1725                                    DebugLoc dl, SelectionDAG &DAG,
1726                                    SmallVectorImpl<SDValue> &InVals) const {
1727
1728   // Assign locations to each value returned by this call.
1729   SmallVector<CCValAssign, 16> RVLocs;
1730   bool Is64Bit = Subtarget->is64Bit();
1731   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1732                  getTargetMachine(), RVLocs, *DAG.getContext());
1733   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1734
1735   // Copy all of the result registers out of their specified physreg.
1736   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1737     CCValAssign &VA = RVLocs[i];
1738     EVT CopyVT = VA.getValVT();
1739
1740     // If this is x86-64, and we disabled SSE, we can't return FP values
1741     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1742         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1743       report_fatal_error("SSE register return with SSE disabled");
1744     }
1745
1746     SDValue Val;
1747
1748     // If this is a call to a function that returns an fp value on the floating
1749     // point stack, we must guarantee the value is popped from the stack, so
1750     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1751     // if the return value is not used. We use the FpPOP_RETVAL instruction
1752     // instead.
1753     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1754       // If we prefer to use the value in xmm registers, copy it out as f80 and
1755       // use a truncate to move it from fp stack reg to xmm reg.
1756       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1757       SDValue Ops[] = { Chain, InFlag };
1758       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1759                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1760       Val = Chain.getValue(0);
1761
1762       // Round the f80 to the right size, which also moves it to the appropriate
1763       // xmm register.
1764       if (CopyVT != VA.getValVT())
1765         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1766                           // This truncation won't change the value.
1767                           DAG.getIntPtrConstant(1));
1768     } else {
1769       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1770                                  CopyVT, InFlag).getValue(1);
1771       Val = Chain.getValue(0);
1772     }
1773     InFlag = Chain.getValue(2);
1774     InVals.push_back(Val);
1775   }
1776
1777   return Chain;
1778 }
1779
1780 //===----------------------------------------------------------------------===//
1781 //                C & StdCall & Fast Calling Convention implementation
1782 //===----------------------------------------------------------------------===//
1783 //  StdCall calling convention seems to be standard for many Windows' API
1784 //  routines and around. It differs from C calling convention just a little:
1785 //  callee should clean up the stack, not caller. Symbols should be also
1786 //  decorated in some fancy way :) It doesn't support any vector arguments.
1787 //  For info on fast calling convention see Fast Calling Convention (tail call)
1788 //  implementation LowerX86_32FastCCCallTo.
1789
1790 /// CallIsStructReturn - Determines whether a call uses struct return
1791 /// semantics.
1792 enum StructReturnType {
1793   NotStructReturn,
1794   RegStructReturn,
1795   StackStructReturn
1796 };
1797 static StructReturnType
1798 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1799   if (Outs.empty())
1800     return NotStructReturn;
1801
1802   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1803   if (!Flags.isSRet())
1804     return NotStructReturn;
1805   if (Flags.isInReg())
1806     return RegStructReturn;
1807   return StackStructReturn;
1808 }
1809
1810 /// ArgsAreStructReturn - Determines whether a function uses struct
1811 /// return semantics.
1812 static StructReturnType
1813 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1814   if (Ins.empty())
1815     return NotStructReturn;
1816
1817   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1818   if (!Flags.isSRet())
1819     return NotStructReturn;
1820   if (Flags.isInReg())
1821     return RegStructReturn;
1822   return StackStructReturn;
1823 }
1824
1825 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1826 /// by "Src" to address "Dst" with size and alignment information specified by
1827 /// the specific parameter attribute. The copy will be passed as a byval
1828 /// function parameter.
1829 static SDValue
1830 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1831                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1832                           DebugLoc dl) {
1833   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1834
1835   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1836                        /*isVolatile*/false, /*AlwaysInline=*/true,
1837                        MachinePointerInfo(), MachinePointerInfo());
1838 }
1839
1840 /// IsTailCallConvention - Return true if the calling convention is one that
1841 /// supports tail call optimization.
1842 static bool IsTailCallConvention(CallingConv::ID CC) {
1843   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1844           CC == CallingConv::HiPE);
1845 }
1846
1847 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1848   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1849     return false;
1850
1851   CallSite CS(CI);
1852   CallingConv::ID CalleeCC = CS.getCallingConv();
1853   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1854     return false;
1855
1856   return true;
1857 }
1858
1859 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1860 /// a tailcall target by changing its ABI.
1861 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1862                                    bool GuaranteedTailCallOpt) {
1863   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1864 }
1865
1866 SDValue
1867 X86TargetLowering::LowerMemArgument(SDValue Chain,
1868                                     CallingConv::ID CallConv,
1869                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1870                                     DebugLoc dl, SelectionDAG &DAG,
1871                                     const CCValAssign &VA,
1872                                     MachineFrameInfo *MFI,
1873                                     unsigned i) const {
1874   // Create the nodes corresponding to a load from this parameter slot.
1875   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1876   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1877                               getTargetMachine().Options.GuaranteedTailCallOpt);
1878   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1879   EVT ValVT;
1880
1881   // If value is passed by pointer we have address passed instead of the value
1882   // itself.
1883   if (VA.getLocInfo() == CCValAssign::Indirect)
1884     ValVT = VA.getLocVT();
1885   else
1886     ValVT = VA.getValVT();
1887
1888   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1889   // changed with more analysis.
1890   // In case of tail call optimization mark all arguments mutable. Since they
1891   // could be overwritten by lowering of arguments in case of a tail call.
1892   if (Flags.isByVal()) {
1893     unsigned Bytes = Flags.getByValSize();
1894     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1895     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1896     return DAG.getFrameIndex(FI, getPointerTy());
1897   } else {
1898     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1899                                     VA.getLocMemOffset(), isImmutable);
1900     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1901     return DAG.getLoad(ValVT, dl, Chain, FIN,
1902                        MachinePointerInfo::getFixedStack(FI),
1903                        false, false, false, 0);
1904   }
1905 }
1906
1907 SDValue
1908 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1909                                         CallingConv::ID CallConv,
1910                                         bool isVarArg,
1911                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1912                                         DebugLoc dl,
1913                                         SelectionDAG &DAG,
1914                                         SmallVectorImpl<SDValue> &InVals)
1915                                           const {
1916   MachineFunction &MF = DAG.getMachineFunction();
1917   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1918
1919   const Function* Fn = MF.getFunction();
1920   if (Fn->hasExternalLinkage() &&
1921       Subtarget->isTargetCygMing() &&
1922       Fn->getName() == "main")
1923     FuncInfo->setForceFramePointer(true);
1924
1925   MachineFrameInfo *MFI = MF.getFrameInfo();
1926   bool Is64Bit = Subtarget->is64Bit();
1927   bool IsWindows = Subtarget->isTargetWindows();
1928   bool IsWin64 = Subtarget->isTargetWin64();
1929
1930   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1931          "Var args not supported with calling convention fastcc, ghc or hipe");
1932
1933   // Assign locations to all of the incoming arguments.
1934   SmallVector<CCValAssign, 16> ArgLocs;
1935   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1936                  ArgLocs, *DAG.getContext());
1937
1938   // Allocate shadow area for Win64
1939   if (IsWin64) {
1940     CCInfo.AllocateStack(32, 8);
1941   }
1942
1943   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1944
1945   unsigned LastVal = ~0U;
1946   SDValue ArgValue;
1947   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1948     CCValAssign &VA = ArgLocs[i];
1949     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1950     // places.
1951     assert(VA.getValNo() != LastVal &&
1952            "Don't support value assigned to multiple locs yet");
1953     (void)LastVal;
1954     LastVal = VA.getValNo();
1955
1956     if (VA.isRegLoc()) {
1957       EVT RegVT = VA.getLocVT();
1958       const TargetRegisterClass *RC;
1959       if (RegVT == MVT::i32)
1960         RC = &X86::GR32RegClass;
1961       else if (Is64Bit && RegVT == MVT::i64)
1962         RC = &X86::GR64RegClass;
1963       else if (RegVT == MVT::f32)
1964         RC = &X86::FR32RegClass;
1965       else if (RegVT == MVT::f64)
1966         RC = &X86::FR64RegClass;
1967       else if (RegVT.is256BitVector())
1968         RC = &X86::VR256RegClass;
1969       else if (RegVT.is128BitVector())
1970         RC = &X86::VR128RegClass;
1971       else if (RegVT == MVT::x86mmx)
1972         RC = &X86::VR64RegClass;
1973       else
1974         llvm_unreachable("Unknown argument type!");
1975
1976       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1977       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1978
1979       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1980       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1981       // right size.
1982       if (VA.getLocInfo() == CCValAssign::SExt)
1983         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1984                                DAG.getValueType(VA.getValVT()));
1985       else if (VA.getLocInfo() == CCValAssign::ZExt)
1986         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1987                                DAG.getValueType(VA.getValVT()));
1988       else if (VA.getLocInfo() == CCValAssign::BCvt)
1989         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1990
1991       if (VA.isExtInLoc()) {
1992         // Handle MMX values passed in XMM regs.
1993         if (RegVT.isVector()) {
1994           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1995                                  ArgValue);
1996         } else
1997           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1998       }
1999     } else {
2000       assert(VA.isMemLoc());
2001       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2002     }
2003
2004     // If value is passed via pointer - do a load.
2005     if (VA.getLocInfo() == CCValAssign::Indirect)
2006       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2007                              MachinePointerInfo(), false, false, false, 0);
2008
2009     InVals.push_back(ArgValue);
2010   }
2011
2012   // The x86-64 ABI for returning structs by value requires that we copy
2013   // the sret argument into %rax for the return. Save the argument into
2014   // a virtual register so that we can access it from the return points.
2015   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2016     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2017     unsigned Reg = FuncInfo->getSRetReturnReg();
2018     if (!Reg) {
2019       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2020       FuncInfo->setSRetReturnReg(Reg);
2021     }
2022     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2023     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2024   }
2025
2026   unsigned StackSize = CCInfo.getNextStackOffset();
2027   // Align stack specially for tail calls.
2028   if (FuncIsMadeTailCallSafe(CallConv,
2029                              MF.getTarget().Options.GuaranteedTailCallOpt))
2030     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2031
2032   // If the function takes variable number of arguments, make a frame index for
2033   // the start of the first vararg value... for expansion of llvm.va_start.
2034   if (isVarArg) {
2035     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2036                     CallConv != CallingConv::X86_ThisCall)) {
2037       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2038     }
2039     if (Is64Bit) {
2040       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2041
2042       // FIXME: We should really autogenerate these arrays
2043       static const uint16_t GPR64ArgRegsWin64[] = {
2044         X86::RCX, X86::RDX, X86::R8,  X86::R9
2045       };
2046       static const uint16_t GPR64ArgRegs64Bit[] = {
2047         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2048       };
2049       static const uint16_t XMMArgRegs64Bit[] = {
2050         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2051         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2052       };
2053       const uint16_t *GPR64ArgRegs;
2054       unsigned NumXMMRegs = 0;
2055
2056       if (IsWin64) {
2057         // The XMM registers which might contain var arg parameters are shadowed
2058         // in their paired GPR.  So we only need to save the GPR to their home
2059         // slots.
2060         TotalNumIntRegs = 4;
2061         GPR64ArgRegs = GPR64ArgRegsWin64;
2062       } else {
2063         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2064         GPR64ArgRegs = GPR64ArgRegs64Bit;
2065
2066         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2067                                                 TotalNumXMMRegs);
2068       }
2069       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2070                                                        TotalNumIntRegs);
2071
2072       bool NoImplicitFloatOps = Fn->getFnAttributes().
2073         hasAttribute(Attribute::NoImplicitFloat);
2074       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2075              "SSE register cannot be used when SSE is disabled!");
2076       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2077                NoImplicitFloatOps) &&
2078              "SSE register cannot be used when SSE is disabled!");
2079       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2080           !Subtarget->hasSSE1())
2081         // Kernel mode asks for SSE to be disabled, so don't push them
2082         // on the stack.
2083         TotalNumXMMRegs = 0;
2084
2085       if (IsWin64) {
2086         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2087         // Get to the caller-allocated home save location.  Add 8 to account
2088         // for the return address.
2089         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2090         FuncInfo->setRegSaveFrameIndex(
2091           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2092         // Fixup to set vararg frame on shadow area (4 x i64).
2093         if (NumIntRegs < 4)
2094           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2095       } else {
2096         // For X86-64, if there are vararg parameters that are passed via
2097         // registers, then we must store them to their spots on the stack so
2098         // they may be loaded by deferencing the result of va_next.
2099         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2100         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2101         FuncInfo->setRegSaveFrameIndex(
2102           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2103                                false));
2104       }
2105
2106       // Store the integer parameter registers.
2107       SmallVector<SDValue, 8> MemOps;
2108       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2109                                         getPointerTy());
2110       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2111       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2112         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2113                                   DAG.getIntPtrConstant(Offset));
2114         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2115                                      &X86::GR64RegClass);
2116         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2117         SDValue Store =
2118           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2119                        MachinePointerInfo::getFixedStack(
2120                          FuncInfo->getRegSaveFrameIndex(), Offset),
2121                        false, false, 0);
2122         MemOps.push_back(Store);
2123         Offset += 8;
2124       }
2125
2126       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2127         // Now store the XMM (fp + vector) parameter registers.
2128         SmallVector<SDValue, 11> SaveXMMOps;
2129         SaveXMMOps.push_back(Chain);
2130
2131         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2132         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2133         SaveXMMOps.push_back(ALVal);
2134
2135         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2136                                FuncInfo->getRegSaveFrameIndex()));
2137         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2138                                FuncInfo->getVarArgsFPOffset()));
2139
2140         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2141           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2142                                        &X86::VR128RegClass);
2143           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2144           SaveXMMOps.push_back(Val);
2145         }
2146         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2147                                      MVT::Other,
2148                                      &SaveXMMOps[0], SaveXMMOps.size()));
2149       }
2150
2151       if (!MemOps.empty())
2152         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2153                             &MemOps[0], MemOps.size());
2154     }
2155   }
2156
2157   // Some CCs need callee pop.
2158   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2159                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2160     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2161   } else {
2162     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2163     // If this is an sret function, the return should pop the hidden pointer.
2164     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2165         argsAreStructReturn(Ins) == StackStructReturn)
2166       FuncInfo->setBytesToPopOnReturn(4);
2167   }
2168
2169   if (!Is64Bit) {
2170     // RegSaveFrameIndex is X86-64 only.
2171     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2172     if (CallConv == CallingConv::X86_FastCall ||
2173         CallConv == CallingConv::X86_ThisCall)
2174       // fastcc functions can't have varargs.
2175       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2176   }
2177
2178   FuncInfo->setArgumentStackSize(StackSize);
2179
2180   return Chain;
2181 }
2182
2183 SDValue
2184 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2185                                     SDValue StackPtr, SDValue Arg,
2186                                     DebugLoc dl, SelectionDAG &DAG,
2187                                     const CCValAssign &VA,
2188                                     ISD::ArgFlagsTy Flags) const {
2189   unsigned LocMemOffset = VA.getLocMemOffset();
2190   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2191   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2192   if (Flags.isByVal())
2193     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2194
2195   return DAG.getStore(Chain, dl, Arg, PtrOff,
2196                       MachinePointerInfo::getStack(LocMemOffset),
2197                       false, false, 0);
2198 }
2199
2200 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2201 /// optimization is performed and it is required.
2202 SDValue
2203 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2204                                            SDValue &OutRetAddr, SDValue Chain,
2205                                            bool IsTailCall, bool Is64Bit,
2206                                            int FPDiff, DebugLoc dl) const {
2207   // Adjust the Return address stack slot.
2208   EVT VT = getPointerTy();
2209   OutRetAddr = getReturnAddressFrameIndex(DAG);
2210
2211   // Load the "old" Return address.
2212   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2213                            false, false, false, 0);
2214   return SDValue(OutRetAddr.getNode(), 1);
2215 }
2216
2217 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2218 /// optimization is performed and it is required (FPDiff!=0).
2219 static SDValue
2220 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2221                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2222                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2223   // Store the return address to the appropriate stack slot.
2224   if (!FPDiff) return Chain;
2225   // Calculate the new stack slot for the return address.
2226   int NewReturnAddrFI =
2227     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2228   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2229   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2230                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2231                        false, false, 0);
2232   return Chain;
2233 }
2234
2235 SDValue
2236 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2237                              SmallVectorImpl<SDValue> &InVals) const {
2238   SelectionDAG &DAG                     = CLI.DAG;
2239   DebugLoc &dl                          = CLI.DL;
2240   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2241   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2242   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2243   SDValue Chain                         = CLI.Chain;
2244   SDValue Callee                        = CLI.Callee;
2245   CallingConv::ID CallConv              = CLI.CallConv;
2246   bool &isTailCall                      = CLI.IsTailCall;
2247   bool isVarArg                         = CLI.IsVarArg;
2248
2249   MachineFunction &MF = DAG.getMachineFunction();
2250   bool Is64Bit        = Subtarget->is64Bit();
2251   bool IsWin64        = Subtarget->isTargetWin64();
2252   bool IsWindows      = Subtarget->isTargetWindows();
2253   StructReturnType SR = callIsStructReturn(Outs);
2254   bool IsSibcall      = false;
2255
2256   if (MF.getTarget().Options.DisableTailCalls)
2257     isTailCall = false;
2258
2259   if (isTailCall) {
2260     // Check if it's really possible to do a tail call.
2261     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2262                     isVarArg, SR != NotStructReturn,
2263                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2264                     Outs, OutVals, Ins, DAG);
2265
2266     // Sibcalls are automatically detected tailcalls which do not require
2267     // ABI changes.
2268     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2269       IsSibcall = true;
2270
2271     if (isTailCall)
2272       ++NumTailCalls;
2273   }
2274
2275   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2276          "Var args not supported with calling convention fastcc, ghc or hipe");
2277
2278   // Analyze operands of the call, assigning locations to each operand.
2279   SmallVector<CCValAssign, 16> ArgLocs;
2280   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2281                  ArgLocs, *DAG.getContext());
2282
2283   // Allocate shadow area for Win64
2284   if (IsWin64) {
2285     CCInfo.AllocateStack(32, 8);
2286   }
2287
2288   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2289
2290   // Get a count of how many bytes are to be pushed on the stack.
2291   unsigned NumBytes = CCInfo.getNextStackOffset();
2292   if (IsSibcall)
2293     // This is a sibcall. The memory operands are available in caller's
2294     // own caller's stack.
2295     NumBytes = 0;
2296   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2297            IsTailCallConvention(CallConv))
2298     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2299
2300   int FPDiff = 0;
2301   if (isTailCall && !IsSibcall) {
2302     // Lower arguments at fp - stackoffset + fpdiff.
2303     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2304     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2305
2306     FPDiff = NumBytesCallerPushed - NumBytes;
2307
2308     // Set the delta of movement of the returnaddr stackslot.
2309     // But only set if delta is greater than previous delta.
2310     if (FPDiff < X86Info->getTCReturnAddrDelta())
2311       X86Info->setTCReturnAddrDelta(FPDiff);
2312   }
2313
2314   if (!IsSibcall)
2315     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2316
2317   SDValue RetAddrFrIdx;
2318   // Load return address for tail calls.
2319   if (isTailCall && FPDiff)
2320     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2321                                     Is64Bit, FPDiff, dl);
2322
2323   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2324   SmallVector<SDValue, 8> MemOpChains;
2325   SDValue StackPtr;
2326
2327   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2328   // of tail call optimization arguments are handle later.
2329   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2330     CCValAssign &VA = ArgLocs[i];
2331     EVT RegVT = VA.getLocVT();
2332     SDValue Arg = OutVals[i];
2333     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2334     bool isByVal = Flags.isByVal();
2335
2336     // Promote the value if needed.
2337     switch (VA.getLocInfo()) {
2338     default: llvm_unreachable("Unknown loc info!");
2339     case CCValAssign::Full: break;
2340     case CCValAssign::SExt:
2341       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2342       break;
2343     case CCValAssign::ZExt:
2344       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2345       break;
2346     case CCValAssign::AExt:
2347       if (RegVT.is128BitVector()) {
2348         // Special case: passing MMX values in XMM registers.
2349         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2350         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2351         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2352       } else
2353         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2354       break;
2355     case CCValAssign::BCvt:
2356       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2357       break;
2358     case CCValAssign::Indirect: {
2359       // Store the argument.
2360       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2361       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2362       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2363                            MachinePointerInfo::getFixedStack(FI),
2364                            false, false, 0);
2365       Arg = SpillSlot;
2366       break;
2367     }
2368     }
2369
2370     if (VA.isRegLoc()) {
2371       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2372       if (isVarArg && IsWin64) {
2373         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2374         // shadow reg if callee is a varargs function.
2375         unsigned ShadowReg = 0;
2376         switch (VA.getLocReg()) {
2377         case X86::XMM0: ShadowReg = X86::RCX; break;
2378         case X86::XMM1: ShadowReg = X86::RDX; break;
2379         case X86::XMM2: ShadowReg = X86::R8; break;
2380         case X86::XMM3: ShadowReg = X86::R9; break;
2381         }
2382         if (ShadowReg)
2383           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2384       }
2385     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2386       assert(VA.isMemLoc());
2387       if (StackPtr.getNode() == 0)
2388         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2389                                       getPointerTy());
2390       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2391                                              dl, DAG, VA, Flags));
2392     }
2393   }
2394
2395   if (!MemOpChains.empty())
2396     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2397                         &MemOpChains[0], MemOpChains.size());
2398
2399   if (Subtarget->isPICStyleGOT()) {
2400     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2401     // GOT pointer.
2402     if (!isTailCall) {
2403       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2404                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2405     } else {
2406       // If we are tail calling and generating PIC/GOT style code load the
2407       // address of the callee into ECX. The value in ecx is used as target of
2408       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2409       // for tail calls on PIC/GOT architectures. Normally we would just put the
2410       // address of GOT into ebx and then call target@PLT. But for tail calls
2411       // ebx would be restored (since ebx is callee saved) before jumping to the
2412       // target@PLT.
2413
2414       // Note: The actual moving to ECX is done further down.
2415       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2416       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2417           !G->getGlobal()->hasProtectedVisibility())
2418         Callee = LowerGlobalAddress(Callee, DAG);
2419       else if (isa<ExternalSymbolSDNode>(Callee))
2420         Callee = LowerExternalSymbol(Callee, DAG);
2421     }
2422   }
2423
2424   if (Is64Bit && isVarArg && !IsWin64) {
2425     // From AMD64 ABI document:
2426     // For calls that may call functions that use varargs or stdargs
2427     // (prototype-less calls or calls to functions containing ellipsis (...) in
2428     // the declaration) %al is used as hidden argument to specify the number
2429     // of SSE registers used. The contents of %al do not need to match exactly
2430     // the number of registers, but must be an ubound on the number of SSE
2431     // registers used and is in the range 0 - 8 inclusive.
2432
2433     // Count the number of XMM registers allocated.
2434     static const uint16_t XMMArgRegs[] = {
2435       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2437     };
2438     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2439     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2440            && "SSE registers cannot be used when SSE is disabled");
2441
2442     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2443                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2444   }
2445
2446   // For tail calls lower the arguments to the 'real' stack slot.
2447   if (isTailCall) {
2448     // Force all the incoming stack arguments to be loaded from the stack
2449     // before any new outgoing arguments are stored to the stack, because the
2450     // outgoing stack slots may alias the incoming argument stack slots, and
2451     // the alias isn't otherwise explicit. This is slightly more conservative
2452     // than necessary, because it means that each store effectively depends
2453     // on every argument instead of just those arguments it would clobber.
2454     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2455
2456     SmallVector<SDValue, 8> MemOpChains2;
2457     SDValue FIN;
2458     int FI = 0;
2459     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2460       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2461         CCValAssign &VA = ArgLocs[i];
2462         if (VA.isRegLoc())
2463           continue;
2464         assert(VA.isMemLoc());
2465         SDValue Arg = OutVals[i];
2466         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2467         // Create frame index.
2468         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2469         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2470         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2471         FIN = DAG.getFrameIndex(FI, getPointerTy());
2472
2473         if (Flags.isByVal()) {
2474           // Copy relative to framepointer.
2475           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2476           if (StackPtr.getNode() == 0)
2477             StackPtr = DAG.getCopyFromReg(Chain, dl,
2478                                           RegInfo->getStackRegister(),
2479                                           getPointerTy());
2480           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2481
2482           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2483                                                            ArgChain,
2484                                                            Flags, DAG, dl));
2485         } else {
2486           // Store relative to framepointer.
2487           MemOpChains2.push_back(
2488             DAG.getStore(ArgChain, dl, Arg, FIN,
2489                          MachinePointerInfo::getFixedStack(FI),
2490                          false, false, 0));
2491         }
2492       }
2493     }
2494
2495     if (!MemOpChains2.empty())
2496       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2497                           &MemOpChains2[0], MemOpChains2.size());
2498
2499     // Store the return address to the appropriate stack slot.
2500     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2501                                      getPointerTy(), RegInfo->getSlotSize(),
2502                                      FPDiff, dl);
2503   }
2504
2505   // Build a sequence of copy-to-reg nodes chained together with token chain
2506   // and flag operands which copy the outgoing args into registers.
2507   SDValue InFlag;
2508   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2509     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2510                              RegsToPass[i].second, InFlag);
2511     InFlag = Chain.getValue(1);
2512   }
2513
2514   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2515     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2516     // In the 64-bit large code model, we have to make all calls
2517     // through a register, since the call instruction's 32-bit
2518     // pc-relative offset may not be large enough to hold the whole
2519     // address.
2520   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2521     // If the callee is a GlobalAddress node (quite common, every direct call
2522     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2523     // it.
2524
2525     // We should use extra load for direct calls to dllimported functions in
2526     // non-JIT mode.
2527     const GlobalValue *GV = G->getGlobal();
2528     if (!GV->hasDLLImportLinkage()) {
2529       unsigned char OpFlags = 0;
2530       bool ExtraLoad = false;
2531       unsigned WrapperKind = ISD::DELETED_NODE;
2532
2533       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2534       // external symbols most go through the PLT in PIC mode.  If the symbol
2535       // has hidden or protected visibility, or if it is static or local, then
2536       // we don't need to use the PLT - we can directly call it.
2537       if (Subtarget->isTargetELF() &&
2538           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2539           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2540         OpFlags = X86II::MO_PLT;
2541       } else if (Subtarget->isPICStyleStubAny() &&
2542                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2543                  (!Subtarget->getTargetTriple().isMacOSX() ||
2544                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2545         // PC-relative references to external symbols should go through $stub,
2546         // unless we're building with the leopard linker or later, which
2547         // automatically synthesizes these stubs.
2548         OpFlags = X86II::MO_DARWIN_STUB;
2549       } else if (Subtarget->isPICStyleRIPRel() &&
2550                  isa<Function>(GV) &&
2551                  cast<Function>(GV)->getFnAttributes().
2552                    hasAttribute(Attribute::NonLazyBind)) {
2553         // If the function is marked as non-lazy, generate an indirect call
2554         // which loads from the GOT directly. This avoids runtime overhead
2555         // at the cost of eager binding (and one extra byte of encoding).
2556         OpFlags = X86II::MO_GOTPCREL;
2557         WrapperKind = X86ISD::WrapperRIP;
2558         ExtraLoad = true;
2559       }
2560
2561       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2562                                           G->getOffset(), OpFlags);
2563
2564       // Add a wrapper if needed.
2565       if (WrapperKind != ISD::DELETED_NODE)
2566         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2567       // Add extra indirection if needed.
2568       if (ExtraLoad)
2569         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2570                              MachinePointerInfo::getGOT(),
2571                              false, false, false, 0);
2572     }
2573   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2574     unsigned char OpFlags = 0;
2575
2576     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2577     // external symbols should go through the PLT.
2578     if (Subtarget->isTargetELF() &&
2579         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2580       OpFlags = X86II::MO_PLT;
2581     } else if (Subtarget->isPICStyleStubAny() &&
2582                (!Subtarget->getTargetTriple().isMacOSX() ||
2583                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2584       // PC-relative references to external symbols should go through $stub,
2585       // unless we're building with the leopard linker or later, which
2586       // automatically synthesizes these stubs.
2587       OpFlags = X86II::MO_DARWIN_STUB;
2588     }
2589
2590     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2591                                          OpFlags);
2592   }
2593
2594   // Returns a chain & a flag for retval copy to use.
2595   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2596   SmallVector<SDValue, 8> Ops;
2597
2598   if (!IsSibcall && isTailCall) {
2599     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2600                            DAG.getIntPtrConstant(0, true), InFlag);
2601     InFlag = Chain.getValue(1);
2602   }
2603
2604   Ops.push_back(Chain);
2605   Ops.push_back(Callee);
2606
2607   if (isTailCall)
2608     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2609
2610   // Add argument registers to the end of the list so that they are known live
2611   // into the call.
2612   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2613     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2614                                   RegsToPass[i].second.getValueType()));
2615
2616   // Add a register mask operand representing the call-preserved registers.
2617   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2618   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2619   assert(Mask && "Missing call preserved mask for calling convention");
2620   Ops.push_back(DAG.getRegisterMask(Mask));
2621
2622   if (InFlag.getNode())
2623     Ops.push_back(InFlag);
2624
2625   if (isTailCall) {
2626     // We used to do:
2627     //// If this is the first return lowered for this function, add the regs
2628     //// to the liveout set for the function.
2629     // This isn't right, although it's probably harmless on x86; liveouts
2630     // should be computed from returns not tail calls.  Consider a void
2631     // function making a tail call to a function returning int.
2632     return DAG.getNode(X86ISD::TC_RETURN, dl,
2633                        NodeTys, &Ops[0], Ops.size());
2634   }
2635
2636   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2637   InFlag = Chain.getValue(1);
2638
2639   // Create the CALLSEQ_END node.
2640   unsigned NumBytesForCalleeToPush;
2641   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2642                        getTargetMachine().Options.GuaranteedTailCallOpt))
2643     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2644   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2645            SR == StackStructReturn)
2646     // If this is a call to a struct-return function, the callee
2647     // pops the hidden struct pointer, so we have to push it back.
2648     // This is common for Darwin/X86, Linux & Mingw32 targets.
2649     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2650     NumBytesForCalleeToPush = 4;
2651   else
2652     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2653
2654   // Returns a flag for retval copy to use.
2655   if (!IsSibcall) {
2656     Chain = DAG.getCALLSEQ_END(Chain,
2657                                DAG.getIntPtrConstant(NumBytes, true),
2658                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2659                                                      true),
2660                                InFlag);
2661     InFlag = Chain.getValue(1);
2662   }
2663
2664   // Handle result values, copying them out of physregs into vregs that we
2665   // return.
2666   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2667                          Ins, dl, DAG, InVals);
2668 }
2669
2670 //===----------------------------------------------------------------------===//
2671 //                Fast Calling Convention (tail call) implementation
2672 //===----------------------------------------------------------------------===//
2673
2674 //  Like std call, callee cleans arguments, convention except that ECX is
2675 //  reserved for storing the tail called function address. Only 2 registers are
2676 //  free for argument passing (inreg). Tail call optimization is performed
2677 //  provided:
2678 //                * tailcallopt is enabled
2679 //                * caller/callee are fastcc
2680 //  On X86_64 architecture with GOT-style position independent code only local
2681 //  (within module) calls are supported at the moment.
2682 //  To keep the stack aligned according to platform abi the function
2683 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2684 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2685 //  If a tail called function callee has more arguments than the caller the
2686 //  caller needs to make sure that there is room to move the RETADDR to. This is
2687 //  achieved by reserving an area the size of the argument delta right after the
2688 //  original REtADDR, but before the saved framepointer or the spilled registers
2689 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2690 //  stack layout:
2691 //    arg1
2692 //    arg2
2693 //    RETADDR
2694 //    [ new RETADDR
2695 //      move area ]
2696 //    (possible EBP)
2697 //    ESI
2698 //    EDI
2699 //    local1 ..
2700
2701 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2702 /// for a 16 byte align requirement.
2703 unsigned
2704 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2705                                                SelectionDAG& DAG) const {
2706   MachineFunction &MF = DAG.getMachineFunction();
2707   const TargetMachine &TM = MF.getTarget();
2708   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2709   unsigned StackAlignment = TFI.getStackAlignment();
2710   uint64_t AlignMask = StackAlignment - 1;
2711   int64_t Offset = StackSize;
2712   unsigned SlotSize = RegInfo->getSlotSize();
2713   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2714     // Number smaller than 12 so just add the difference.
2715     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2716   } else {
2717     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2718     Offset = ((~AlignMask) & Offset) + StackAlignment +
2719       (StackAlignment-SlotSize);
2720   }
2721   return Offset;
2722 }
2723
2724 /// MatchingStackOffset - Return true if the given stack call argument is
2725 /// already available in the same position (relatively) of the caller's
2726 /// incoming argument stack.
2727 static
2728 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2729                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2730                          const X86InstrInfo *TII) {
2731   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2732   int FI = INT_MAX;
2733   if (Arg.getOpcode() == ISD::CopyFromReg) {
2734     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2735     if (!TargetRegisterInfo::isVirtualRegister(VR))
2736       return false;
2737     MachineInstr *Def = MRI->getVRegDef(VR);
2738     if (!Def)
2739       return false;
2740     if (!Flags.isByVal()) {
2741       if (!TII->isLoadFromStackSlot(Def, FI))
2742         return false;
2743     } else {
2744       unsigned Opcode = Def->getOpcode();
2745       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2746           Def->getOperand(1).isFI()) {
2747         FI = Def->getOperand(1).getIndex();
2748         Bytes = Flags.getByValSize();
2749       } else
2750         return false;
2751     }
2752   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2753     if (Flags.isByVal())
2754       // ByVal argument is passed in as a pointer but it's now being
2755       // dereferenced. e.g.
2756       // define @foo(%struct.X* %A) {
2757       //   tail call @bar(%struct.X* byval %A)
2758       // }
2759       return false;
2760     SDValue Ptr = Ld->getBasePtr();
2761     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2762     if (!FINode)
2763       return false;
2764     FI = FINode->getIndex();
2765   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2766     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2767     FI = FINode->getIndex();
2768     Bytes = Flags.getByValSize();
2769   } else
2770     return false;
2771
2772   assert(FI != INT_MAX);
2773   if (!MFI->isFixedObjectIndex(FI))
2774     return false;
2775   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2776 }
2777
2778 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2779 /// for tail call optimization. Targets which want to do tail call
2780 /// optimization should implement this function.
2781 bool
2782 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2783                                                      CallingConv::ID CalleeCC,
2784                                                      bool isVarArg,
2785                                                      bool isCalleeStructRet,
2786                                                      bool isCallerStructRet,
2787                                                      Type *RetTy,
2788                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2789                                     const SmallVectorImpl<SDValue> &OutVals,
2790                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2791                                                      SelectionDAG& DAG) const {
2792   if (!IsTailCallConvention(CalleeCC) &&
2793       CalleeCC != CallingConv::C)
2794     return false;
2795
2796   // If -tailcallopt is specified, make fastcc functions tail-callable.
2797   const MachineFunction &MF = DAG.getMachineFunction();
2798   const Function *CallerF = DAG.getMachineFunction().getFunction();
2799
2800   // If the function return type is x86_fp80 and the callee return type is not,
2801   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2802   // perform a tailcall optimization here.
2803   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2804     return false;
2805
2806   CallingConv::ID CallerCC = CallerF->getCallingConv();
2807   bool CCMatch = CallerCC == CalleeCC;
2808
2809   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2810     if (IsTailCallConvention(CalleeCC) && CCMatch)
2811       return true;
2812     return false;
2813   }
2814
2815   // Look for obvious safe cases to perform tail call optimization that do not
2816   // require ABI changes. This is what gcc calls sibcall.
2817
2818   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2819   // emit a special epilogue.
2820   if (RegInfo->needsStackRealignment(MF))
2821     return false;
2822
2823   // Also avoid sibcall optimization if either caller or callee uses struct
2824   // return semantics.
2825   if (isCalleeStructRet || isCallerStructRet)
2826     return false;
2827
2828   // An stdcall caller is expected to clean up its arguments; the callee
2829   // isn't going to do that.
2830   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2831     return false;
2832
2833   // Do not sibcall optimize vararg calls unless all arguments are passed via
2834   // registers.
2835   if (isVarArg && !Outs.empty()) {
2836
2837     // Optimizing for varargs on Win64 is unlikely to be safe without
2838     // additional testing.
2839     if (Subtarget->isTargetWin64())
2840       return false;
2841
2842     SmallVector<CCValAssign, 16> ArgLocs;
2843     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2844                    getTargetMachine(), ArgLocs, *DAG.getContext());
2845
2846     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2847     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2848       if (!ArgLocs[i].isRegLoc())
2849         return false;
2850   }
2851
2852   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2853   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2854   // this into a sibcall.
2855   bool Unused = false;
2856   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2857     if (!Ins[i].Used) {
2858       Unused = true;
2859       break;
2860     }
2861   }
2862   if (Unused) {
2863     SmallVector<CCValAssign, 16> RVLocs;
2864     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2865                    getTargetMachine(), RVLocs, *DAG.getContext());
2866     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2867     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2868       CCValAssign &VA = RVLocs[i];
2869       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2870         return false;
2871     }
2872   }
2873
2874   // If the calling conventions do not match, then we'd better make sure the
2875   // results are returned in the same way as what the caller expects.
2876   if (!CCMatch) {
2877     SmallVector<CCValAssign, 16> RVLocs1;
2878     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2879                     getTargetMachine(), RVLocs1, *DAG.getContext());
2880     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2881
2882     SmallVector<CCValAssign, 16> RVLocs2;
2883     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2884                     getTargetMachine(), RVLocs2, *DAG.getContext());
2885     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2886
2887     if (RVLocs1.size() != RVLocs2.size())
2888       return false;
2889     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2890       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2891         return false;
2892       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2893         return false;
2894       if (RVLocs1[i].isRegLoc()) {
2895         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2896           return false;
2897       } else {
2898         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2899           return false;
2900       }
2901     }
2902   }
2903
2904   // If the callee takes no arguments then go on to check the results of the
2905   // call.
2906   if (!Outs.empty()) {
2907     // Check if stack adjustment is needed. For now, do not do this if any
2908     // argument is passed on the stack.
2909     SmallVector<CCValAssign, 16> ArgLocs;
2910     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2911                    getTargetMachine(), ArgLocs, *DAG.getContext());
2912
2913     // Allocate shadow area for Win64
2914     if (Subtarget->isTargetWin64()) {
2915       CCInfo.AllocateStack(32, 8);
2916     }
2917
2918     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2919     if (CCInfo.getNextStackOffset()) {
2920       MachineFunction &MF = DAG.getMachineFunction();
2921       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2922         return false;
2923
2924       // Check if the arguments are already laid out in the right way as
2925       // the caller's fixed stack objects.
2926       MachineFrameInfo *MFI = MF.getFrameInfo();
2927       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2928       const X86InstrInfo *TII =
2929         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2930       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2931         CCValAssign &VA = ArgLocs[i];
2932         SDValue Arg = OutVals[i];
2933         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2934         if (VA.getLocInfo() == CCValAssign::Indirect)
2935           return false;
2936         if (!VA.isRegLoc()) {
2937           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2938                                    MFI, MRI, TII))
2939             return false;
2940         }
2941       }
2942     }
2943
2944     // If the tailcall address may be in a register, then make sure it's
2945     // possible to register allocate for it. In 32-bit, the call address can
2946     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2947     // callee-saved registers are restored. These happen to be the same
2948     // registers used to pass 'inreg' arguments so watch out for those.
2949     if (!Subtarget->is64Bit() &&
2950         !isa<GlobalAddressSDNode>(Callee) &&
2951         !isa<ExternalSymbolSDNode>(Callee)) {
2952       unsigned NumInRegs = 0;
2953       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2954         CCValAssign &VA = ArgLocs[i];
2955         if (!VA.isRegLoc())
2956           continue;
2957         unsigned Reg = VA.getLocReg();
2958         switch (Reg) {
2959         default: break;
2960         case X86::EAX: case X86::EDX: case X86::ECX:
2961           if (++NumInRegs == 3)
2962             return false;
2963           break;
2964         }
2965       }
2966     }
2967   }
2968
2969   return true;
2970 }
2971
2972 FastISel *
2973 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2974                                   const TargetLibraryInfo *libInfo) const {
2975   return X86::createFastISel(funcInfo, libInfo);
2976 }
2977
2978 //===----------------------------------------------------------------------===//
2979 //                           Other Lowering Hooks
2980 //===----------------------------------------------------------------------===//
2981
2982 static bool MayFoldLoad(SDValue Op) {
2983   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2984 }
2985
2986 static bool MayFoldIntoStore(SDValue Op) {
2987   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2988 }
2989
2990 static bool isTargetShuffle(unsigned Opcode) {
2991   switch(Opcode) {
2992   default: return false;
2993   case X86ISD::PSHUFD:
2994   case X86ISD::PSHUFHW:
2995   case X86ISD::PSHUFLW:
2996   case X86ISD::SHUFP:
2997   case X86ISD::PALIGN:
2998   case X86ISD::MOVLHPS:
2999   case X86ISD::MOVLHPD:
3000   case X86ISD::MOVHLPS:
3001   case X86ISD::MOVLPS:
3002   case X86ISD::MOVLPD:
3003   case X86ISD::MOVSHDUP:
3004   case X86ISD::MOVSLDUP:
3005   case X86ISD::MOVDDUP:
3006   case X86ISD::MOVSS:
3007   case X86ISD::MOVSD:
3008   case X86ISD::UNPCKL:
3009   case X86ISD::UNPCKH:
3010   case X86ISD::VPERMILP:
3011   case X86ISD::VPERM2X128:
3012   case X86ISD::VPERMI:
3013     return true;
3014   }
3015 }
3016
3017 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3018                                     SDValue V1, SelectionDAG &DAG) {
3019   switch(Opc) {
3020   default: llvm_unreachable("Unknown x86 shuffle node");
3021   case X86ISD::MOVSHDUP:
3022   case X86ISD::MOVSLDUP:
3023   case X86ISD::MOVDDUP:
3024     return DAG.getNode(Opc, dl, VT, V1);
3025   }
3026 }
3027
3028 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3029                                     SDValue V1, unsigned TargetMask,
3030                                     SelectionDAG &DAG) {
3031   switch(Opc) {
3032   default: llvm_unreachable("Unknown x86 shuffle node");
3033   case X86ISD::PSHUFD:
3034   case X86ISD::PSHUFHW:
3035   case X86ISD::PSHUFLW:
3036   case X86ISD::VPERMILP:
3037   case X86ISD::VPERMI:
3038     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3039   }
3040 }
3041
3042 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3043                                     SDValue V1, SDValue V2, unsigned TargetMask,
3044                                     SelectionDAG &DAG) {
3045   switch(Opc) {
3046   default: llvm_unreachable("Unknown x86 shuffle node");
3047   case X86ISD::PALIGN:
3048   case X86ISD::SHUFP:
3049   case X86ISD::VPERM2X128:
3050     return DAG.getNode(Opc, dl, VT, V1, V2,
3051                        DAG.getConstant(TargetMask, MVT::i8));
3052   }
3053 }
3054
3055 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3056                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3057   switch(Opc) {
3058   default: llvm_unreachable("Unknown x86 shuffle node");
3059   case X86ISD::MOVLHPS:
3060   case X86ISD::MOVLHPD:
3061   case X86ISD::MOVHLPS:
3062   case X86ISD::MOVLPS:
3063   case X86ISD::MOVLPD:
3064   case X86ISD::MOVSS:
3065   case X86ISD::MOVSD:
3066   case X86ISD::UNPCKL:
3067   case X86ISD::UNPCKH:
3068     return DAG.getNode(Opc, dl, VT, V1, V2);
3069   }
3070 }
3071
3072 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3073   MachineFunction &MF = DAG.getMachineFunction();
3074   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3075   int ReturnAddrIndex = FuncInfo->getRAIndex();
3076
3077   if (ReturnAddrIndex == 0) {
3078     // Set up a frame object for the return address.
3079     unsigned SlotSize = RegInfo->getSlotSize();
3080     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3081                                                            false);
3082     FuncInfo->setRAIndex(ReturnAddrIndex);
3083   }
3084
3085   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3086 }
3087
3088 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3089                                        bool hasSymbolicDisplacement) {
3090   // Offset should fit into 32 bit immediate field.
3091   if (!isInt<32>(Offset))
3092     return false;
3093
3094   // If we don't have a symbolic displacement - we don't have any extra
3095   // restrictions.
3096   if (!hasSymbolicDisplacement)
3097     return true;
3098
3099   // FIXME: Some tweaks might be needed for medium code model.
3100   if (M != CodeModel::Small && M != CodeModel::Kernel)
3101     return false;
3102
3103   // For small code model we assume that latest object is 16MB before end of 31
3104   // bits boundary. We may also accept pretty large negative constants knowing
3105   // that all objects are in the positive half of address space.
3106   if (M == CodeModel::Small && Offset < 16*1024*1024)
3107     return true;
3108
3109   // For kernel code model we know that all object resist in the negative half
3110   // of 32bits address space. We may not accept negative offsets, since they may
3111   // be just off and we may accept pretty large positive ones.
3112   if (M == CodeModel::Kernel && Offset > 0)
3113     return true;
3114
3115   return false;
3116 }
3117
3118 /// isCalleePop - Determines whether the callee is required to pop its
3119 /// own arguments. Callee pop is necessary to support tail calls.
3120 bool X86::isCalleePop(CallingConv::ID CallingConv,
3121                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3122   if (IsVarArg)
3123     return false;
3124
3125   switch (CallingConv) {
3126   default:
3127     return false;
3128   case CallingConv::X86_StdCall:
3129     return !is64Bit;
3130   case CallingConv::X86_FastCall:
3131     return !is64Bit;
3132   case CallingConv::X86_ThisCall:
3133     return !is64Bit;
3134   case CallingConv::Fast:
3135     return TailCallOpt;
3136   case CallingConv::GHC:
3137     return TailCallOpt;
3138   case CallingConv::HiPE:
3139     return TailCallOpt;
3140   }
3141 }
3142
3143 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3144 /// specific condition code, returning the condition code and the LHS/RHS of the
3145 /// comparison to make.
3146 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3147                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3148   if (!isFP) {
3149     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3150       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3151         // X > -1   -> X == 0, jump !sign.
3152         RHS = DAG.getConstant(0, RHS.getValueType());
3153         return X86::COND_NS;
3154       }
3155       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3156         // X < 0   -> X == 0, jump on sign.
3157         return X86::COND_S;
3158       }
3159       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3160         // X < 1   -> X <= 0
3161         RHS = DAG.getConstant(0, RHS.getValueType());
3162         return X86::COND_LE;
3163       }
3164     }
3165
3166     switch (SetCCOpcode) {
3167     default: llvm_unreachable("Invalid integer condition!");
3168     case ISD::SETEQ:  return X86::COND_E;
3169     case ISD::SETGT:  return X86::COND_G;
3170     case ISD::SETGE:  return X86::COND_GE;
3171     case ISD::SETLT:  return X86::COND_L;
3172     case ISD::SETLE:  return X86::COND_LE;
3173     case ISD::SETNE:  return X86::COND_NE;
3174     case ISD::SETULT: return X86::COND_B;
3175     case ISD::SETUGT: return X86::COND_A;
3176     case ISD::SETULE: return X86::COND_BE;
3177     case ISD::SETUGE: return X86::COND_AE;
3178     }
3179   }
3180
3181   // First determine if it is required or is profitable to flip the operands.
3182
3183   // If LHS is a foldable load, but RHS is not, flip the condition.
3184   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3185       !ISD::isNON_EXTLoad(RHS.getNode())) {
3186     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3187     std::swap(LHS, RHS);
3188   }
3189
3190   switch (SetCCOpcode) {
3191   default: break;
3192   case ISD::SETOLT:
3193   case ISD::SETOLE:
3194   case ISD::SETUGT:
3195   case ISD::SETUGE:
3196     std::swap(LHS, RHS);
3197     break;
3198   }
3199
3200   // On a floating point condition, the flags are set as follows:
3201   // ZF  PF  CF   op
3202   //  0 | 0 | 0 | X > Y
3203   //  0 | 0 | 1 | X < Y
3204   //  1 | 0 | 0 | X == Y
3205   //  1 | 1 | 1 | unordered
3206   switch (SetCCOpcode) {
3207   default: llvm_unreachable("Condcode should be pre-legalized away");
3208   case ISD::SETUEQ:
3209   case ISD::SETEQ:   return X86::COND_E;
3210   case ISD::SETOLT:              // flipped
3211   case ISD::SETOGT:
3212   case ISD::SETGT:   return X86::COND_A;
3213   case ISD::SETOLE:              // flipped
3214   case ISD::SETOGE:
3215   case ISD::SETGE:   return X86::COND_AE;
3216   case ISD::SETUGT:              // flipped
3217   case ISD::SETULT:
3218   case ISD::SETLT:   return X86::COND_B;
3219   case ISD::SETUGE:              // flipped
3220   case ISD::SETULE:
3221   case ISD::SETLE:   return X86::COND_BE;
3222   case ISD::SETONE:
3223   case ISD::SETNE:   return X86::COND_NE;
3224   case ISD::SETUO:   return X86::COND_P;
3225   case ISD::SETO:    return X86::COND_NP;
3226   case ISD::SETOEQ:
3227   case ISD::SETUNE:  return X86::COND_INVALID;
3228   }
3229 }
3230
3231 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3232 /// code. Current x86 isa includes the following FP cmov instructions:
3233 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3234 static bool hasFPCMov(unsigned X86CC) {
3235   switch (X86CC) {
3236   default:
3237     return false;
3238   case X86::COND_B:
3239   case X86::COND_BE:
3240   case X86::COND_E:
3241   case X86::COND_P:
3242   case X86::COND_A:
3243   case X86::COND_AE:
3244   case X86::COND_NE:
3245   case X86::COND_NP:
3246     return true;
3247   }
3248 }
3249
3250 /// isFPImmLegal - Returns true if the target can instruction select the
3251 /// specified FP immediate natively. If false, the legalizer will
3252 /// materialize the FP immediate as a load from a constant pool.
3253 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3254   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3255     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3256       return true;
3257   }
3258   return false;
3259 }
3260
3261 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3262 /// the specified range (L, H].
3263 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3264   return (Val < 0) || (Val >= Low && Val < Hi);
3265 }
3266
3267 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3268 /// specified value.
3269 static bool isUndefOrEqual(int Val, int CmpVal) {
3270   return (Val < 0 || Val == CmpVal);
3271 }
3272
3273 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3274 /// from position Pos and ending in Pos+Size, falls within the specified
3275 /// sequential range (L, L+Pos]. or is undef.
3276 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3277                                        unsigned Pos, unsigned Size, int Low) {
3278   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3279     if (!isUndefOrEqual(Mask[i], Low))
3280       return false;
3281   return true;
3282 }
3283
3284 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3285 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3286 /// the second operand.
3287 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3288   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3289     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3290   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3291     return (Mask[0] < 2 && Mask[1] < 2);
3292   return false;
3293 }
3294
3295 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3296 /// is suitable for input to PSHUFHW.
3297 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3298   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3299     return false;
3300
3301   // Lower quadword copied in order or undef.
3302   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3303     return false;
3304
3305   // Upper quadword shuffled.
3306   for (unsigned i = 4; i != 8; ++i)
3307     if (!isUndefOrInRange(Mask[i], 4, 8))
3308       return false;
3309
3310   if (VT == MVT::v16i16) {
3311     // Lower quadword copied in order or undef.
3312     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3313       return false;
3314
3315     // Upper quadword shuffled.
3316     for (unsigned i = 12; i != 16; ++i)
3317       if (!isUndefOrInRange(Mask[i], 12, 16))
3318         return false;
3319   }
3320
3321   return true;
3322 }
3323
3324 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3325 /// is suitable for input to PSHUFLW.
3326 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3327   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3328     return false;
3329
3330   // Upper quadword copied in order.
3331   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3332     return false;
3333
3334   // Lower quadword shuffled.
3335   for (unsigned i = 0; i != 4; ++i)
3336     if (!isUndefOrInRange(Mask[i], 0, 4))
3337       return false;
3338
3339   if (VT == MVT::v16i16) {
3340     // Upper quadword copied in order.
3341     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3342       return false;
3343
3344     // Lower quadword shuffled.
3345     for (unsigned i = 8; i != 12; ++i)
3346       if (!isUndefOrInRange(Mask[i], 8, 12))
3347         return false;
3348   }
3349
3350   return true;
3351 }
3352
3353 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3354 /// is suitable for input to PALIGNR.
3355 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3356                           const X86Subtarget *Subtarget) {
3357   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3358       (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3359     return false;
3360
3361   unsigned NumElts = VT.getVectorNumElements();
3362   unsigned NumLanes = VT.getSizeInBits()/128;
3363   unsigned NumLaneElts = NumElts/NumLanes;
3364
3365   // Do not handle 64-bit element shuffles with palignr.
3366   if (NumLaneElts == 2)
3367     return false;
3368
3369   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3370     unsigned i;
3371     for (i = 0; i != NumLaneElts; ++i) {
3372       if (Mask[i+l] >= 0)
3373         break;
3374     }
3375
3376     // Lane is all undef, go to next lane
3377     if (i == NumLaneElts)
3378       continue;
3379
3380     int Start = Mask[i+l];
3381
3382     // Make sure its in this lane in one of the sources
3383     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3384         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3385       return false;
3386
3387     // If not lane 0, then we must match lane 0
3388     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3389       return false;
3390
3391     // Correct second source to be contiguous with first source
3392     if (Start >= (int)NumElts)
3393       Start -= NumElts - NumLaneElts;
3394
3395     // Make sure we're shifting in the right direction.
3396     if (Start <= (int)(i+l))
3397       return false;
3398
3399     Start -= i;
3400
3401     // Check the rest of the elements to see if they are consecutive.
3402     for (++i; i != NumLaneElts; ++i) {
3403       int Idx = Mask[i+l];
3404
3405       // Make sure its in this lane
3406       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3407           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3408         return false;
3409
3410       // If not lane 0, then we must match lane 0
3411       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3412         return false;
3413
3414       if (Idx >= (int)NumElts)
3415         Idx -= NumElts - NumLaneElts;
3416
3417       if (!isUndefOrEqual(Idx, Start+i))
3418         return false;
3419
3420     }
3421   }
3422
3423   return true;
3424 }
3425
3426 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3427 /// the two vector operands have swapped position.
3428 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3429                                      unsigned NumElems) {
3430   for (unsigned i = 0; i != NumElems; ++i) {
3431     int idx = Mask[i];
3432     if (idx < 0)
3433       continue;
3434     else if (idx < (int)NumElems)
3435       Mask[i] = idx + NumElems;
3436     else
3437       Mask[i] = idx - NumElems;
3438   }
3439 }
3440
3441 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3442 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3443 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3444 /// reverse of what x86 shuffles want.
3445 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3446                         bool Commuted = false) {
3447   if (!HasFp256 && VT.getSizeInBits() == 256)
3448     return false;
3449
3450   unsigned NumElems = VT.getVectorNumElements();
3451   unsigned NumLanes = VT.getSizeInBits()/128;
3452   unsigned NumLaneElems = NumElems/NumLanes;
3453
3454   if (NumLaneElems != 2 && NumLaneElems != 4)
3455     return false;
3456
3457   // VSHUFPSY divides the resulting vector into 4 chunks.
3458   // The sources are also splitted into 4 chunks, and each destination
3459   // chunk must come from a different source chunk.
3460   //
3461   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3462   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3463   //
3464   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3465   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3466   //
3467   // VSHUFPDY divides the resulting vector into 4 chunks.
3468   // The sources are also splitted into 4 chunks, and each destination
3469   // chunk must come from a different source chunk.
3470   //
3471   //  SRC1 =>      X3       X2       X1       X0
3472   //  SRC2 =>      Y3       Y2       Y1       Y0
3473   //
3474   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3475   //
3476   unsigned HalfLaneElems = NumLaneElems/2;
3477   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3478     for (unsigned i = 0; i != NumLaneElems; ++i) {
3479       int Idx = Mask[i+l];
3480       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3481       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3482         return false;
3483       // For VSHUFPSY, the mask of the second half must be the same as the
3484       // first but with the appropriate offsets. This works in the same way as
3485       // VPERMILPS works with masks.
3486       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3487         continue;
3488       if (!isUndefOrEqual(Idx, Mask[i]+l))
3489         return false;
3490     }
3491   }
3492
3493   return true;
3494 }
3495
3496 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3498 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3499   if (!VT.is128BitVector())
3500     return false;
3501
3502   unsigned NumElems = VT.getVectorNumElements();
3503
3504   if (NumElems != 4)
3505     return false;
3506
3507   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3508   return isUndefOrEqual(Mask[0], 6) &&
3509          isUndefOrEqual(Mask[1], 7) &&
3510          isUndefOrEqual(Mask[2], 2) &&
3511          isUndefOrEqual(Mask[3], 3);
3512 }
3513
3514 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3515 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3516 /// <2, 3, 2, 3>
3517 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3518   if (!VT.is128BitVector())
3519     return false;
3520
3521   unsigned NumElems = VT.getVectorNumElements();
3522
3523   if (NumElems != 4)
3524     return false;
3525
3526   return isUndefOrEqual(Mask[0], 2) &&
3527          isUndefOrEqual(Mask[1], 3) &&
3528          isUndefOrEqual(Mask[2], 2) &&
3529          isUndefOrEqual(Mask[3], 3);
3530 }
3531
3532 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3533 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3534 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3535   if (!VT.is128BitVector())
3536     return false;
3537
3538   unsigned NumElems = VT.getVectorNumElements();
3539
3540   if (NumElems != 2 && NumElems != 4)
3541     return false;
3542
3543   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3544     if (!isUndefOrEqual(Mask[i], i + NumElems))
3545       return false;
3546
3547   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3548     if (!isUndefOrEqual(Mask[i], i))
3549       return false;
3550
3551   return true;
3552 }
3553
3554 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3555 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3556 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3557   if (!VT.is128BitVector())
3558     return false;
3559
3560   unsigned NumElems = VT.getVectorNumElements();
3561
3562   if (NumElems != 2 && NumElems != 4)
3563     return false;
3564
3565   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3566     if (!isUndefOrEqual(Mask[i], i))
3567       return false;
3568
3569   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3570     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3571       return false;
3572
3573   return true;
3574 }
3575
3576 //
3577 // Some special combinations that can be optimized.
3578 //
3579 static
3580 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3581                                SelectionDAG &DAG) {
3582   EVT VT = SVOp->getValueType(0);
3583   DebugLoc dl = SVOp->getDebugLoc();
3584
3585   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3586     return SDValue();
3587
3588   ArrayRef<int> Mask = SVOp->getMask();
3589
3590   // These are the special masks that may be optimized.
3591   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3592   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3593   bool MatchEvenMask = true;
3594   bool MatchOddMask  = true;
3595   for (int i=0; i<8; ++i) {
3596     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3597       MatchEvenMask = false;
3598     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3599       MatchOddMask = false;
3600   }
3601
3602   if (!MatchEvenMask && !MatchOddMask)
3603     return SDValue();
3604
3605   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3606
3607   SDValue Op0 = SVOp->getOperand(0);
3608   SDValue Op1 = SVOp->getOperand(1);
3609
3610   if (MatchEvenMask) {
3611     // Shift the second operand right to 32 bits.
3612     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3613     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3614   } else {
3615     // Shift the first operand left to 32 bits.
3616     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3617     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3618   }
3619   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3620   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3621 }
3622
3623 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3624 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3625 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3626                          bool HasInt256, bool V2IsSplat = false) {
3627   unsigned NumElts = VT.getVectorNumElements();
3628
3629   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3630          "Unsupported vector type for unpckh");
3631
3632   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3633       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3634     return false;
3635
3636   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3637   // independently on 128-bit lanes.
3638   unsigned NumLanes = VT.getSizeInBits()/128;
3639   unsigned NumLaneElts = NumElts/NumLanes;
3640
3641   for (unsigned l = 0; l != NumLanes; ++l) {
3642     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3643          i != (l+1)*NumLaneElts;
3644          i += 2, ++j) {
3645       int BitI  = Mask[i];
3646       int BitI1 = Mask[i+1];
3647       if (!isUndefOrEqual(BitI, j))
3648         return false;
3649       if (V2IsSplat) {
3650         if (!isUndefOrEqual(BitI1, NumElts))
3651           return false;
3652       } else {
3653         if (!isUndefOrEqual(BitI1, j + NumElts))
3654           return false;
3655       }
3656     }
3657   }
3658
3659   return true;
3660 }
3661
3662 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3663 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3664 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3665                          bool HasInt256, bool V2IsSplat = false) {
3666   unsigned NumElts = VT.getVectorNumElements();
3667
3668   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3669          "Unsupported vector type for unpckh");
3670
3671   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3672       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3673     return false;
3674
3675   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3676   // independently on 128-bit lanes.
3677   unsigned NumLanes = VT.getSizeInBits()/128;
3678   unsigned NumLaneElts = NumElts/NumLanes;
3679
3680   for (unsigned l = 0; l != NumLanes; ++l) {
3681     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3682          i != (l+1)*NumLaneElts; i += 2, ++j) {
3683       int BitI  = Mask[i];
3684       int BitI1 = Mask[i+1];
3685       if (!isUndefOrEqual(BitI, j))
3686         return false;
3687       if (V2IsSplat) {
3688         if (isUndefOrEqual(BitI1, NumElts))
3689           return false;
3690       } else {
3691         if (!isUndefOrEqual(BitI1, j+NumElts))
3692           return false;
3693       }
3694     }
3695   }
3696   return true;
3697 }
3698
3699 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3700 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3701 /// <0, 0, 1, 1>
3702 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3703                                   bool HasInt256) {
3704   unsigned NumElts = VT.getVectorNumElements();
3705
3706   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3707          "Unsupported vector type for unpckh");
3708
3709   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3710       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3711     return false;
3712
3713   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3714   // FIXME: Need a better way to get rid of this, there's no latency difference
3715   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3716   // the former later. We should also remove the "_undef" special mask.
3717   if (NumElts == 4 && VT.getSizeInBits() == 256)
3718     return false;
3719
3720   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3721   // independently on 128-bit lanes.
3722   unsigned NumLanes = VT.getSizeInBits()/128;
3723   unsigned NumLaneElts = NumElts/NumLanes;
3724
3725   for (unsigned l = 0; l != NumLanes; ++l) {
3726     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3727          i != (l+1)*NumLaneElts;
3728          i += 2, ++j) {
3729       int BitI  = Mask[i];
3730       int BitI1 = Mask[i+1];
3731
3732       if (!isUndefOrEqual(BitI, j))
3733         return false;
3734       if (!isUndefOrEqual(BitI1, j))
3735         return false;
3736     }
3737   }
3738
3739   return true;
3740 }
3741
3742 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3743 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3744 /// <2, 2, 3, 3>
3745 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3746   unsigned NumElts = VT.getVectorNumElements();
3747
3748   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3749          "Unsupported vector type for unpckh");
3750
3751   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3752       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3753     return false;
3754
3755   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3756   // independently on 128-bit lanes.
3757   unsigned NumLanes = VT.getSizeInBits()/128;
3758   unsigned NumLaneElts = NumElts/NumLanes;
3759
3760   for (unsigned l = 0; l != NumLanes; ++l) {
3761     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3762          i != (l+1)*NumLaneElts; i += 2, ++j) {
3763       int BitI  = Mask[i];
3764       int BitI1 = Mask[i+1];
3765       if (!isUndefOrEqual(BitI, j))
3766         return false;
3767       if (!isUndefOrEqual(BitI1, j))
3768         return false;
3769     }
3770   }
3771   return true;
3772 }
3773
3774 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3775 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3776 /// MOVSD, and MOVD, i.e. setting the lowest element.
3777 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3778   if (VT.getVectorElementType().getSizeInBits() < 32)
3779     return false;
3780   if (!VT.is128BitVector())
3781     return false;
3782
3783   unsigned NumElts = VT.getVectorNumElements();
3784
3785   if (!isUndefOrEqual(Mask[0], NumElts))
3786     return false;
3787
3788   for (unsigned i = 1; i != NumElts; ++i)
3789     if (!isUndefOrEqual(Mask[i], i))
3790       return false;
3791
3792   return true;
3793 }
3794
3795 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3796 /// as permutations between 128-bit chunks or halves. As an example: this
3797 /// shuffle bellow:
3798 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3799 /// The first half comes from the second half of V1 and the second half from the
3800 /// the second half of V2.
3801 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3802   if (!HasFp256 || !VT.is256BitVector())
3803     return false;
3804
3805   // The shuffle result is divided into half A and half B. In total the two
3806   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3807   // B must come from C, D, E or F.
3808   unsigned HalfSize = VT.getVectorNumElements()/2;
3809   bool MatchA = false, MatchB = false;
3810
3811   // Check if A comes from one of C, D, E, F.
3812   for (unsigned Half = 0; Half != 4; ++Half) {
3813     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3814       MatchA = true;
3815       break;
3816     }
3817   }
3818
3819   // Check if B comes from one of C, D, E, F.
3820   for (unsigned Half = 0; Half != 4; ++Half) {
3821     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3822       MatchB = true;
3823       break;
3824     }
3825   }
3826
3827   return MatchA && MatchB;
3828 }
3829
3830 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3831 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3832 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3833   EVT VT = SVOp->getValueType(0);
3834
3835   unsigned HalfSize = VT.getVectorNumElements()/2;
3836
3837   unsigned FstHalf = 0, SndHalf = 0;
3838   for (unsigned i = 0; i < HalfSize; ++i) {
3839     if (SVOp->getMaskElt(i) > 0) {
3840       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3841       break;
3842     }
3843   }
3844   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3845     if (SVOp->getMaskElt(i) > 0) {
3846       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3847       break;
3848     }
3849   }
3850
3851   return (FstHalf | (SndHalf << 4));
3852 }
3853
3854 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3856 /// Note that VPERMIL mask matching is different depending whether theunderlying
3857 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3858 /// to the same elements of the low, but to the higher half of the source.
3859 /// In VPERMILPD the two lanes could be shuffled independently of each other
3860 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3861 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3862   if (!HasFp256)
3863     return false;
3864
3865   unsigned NumElts = VT.getVectorNumElements();
3866   // Only match 256-bit with 32/64-bit types
3867   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3868     return false;
3869
3870   unsigned NumLanes = VT.getSizeInBits()/128;
3871   unsigned LaneSize = NumElts/NumLanes;
3872   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3873     for (unsigned i = 0; i != LaneSize; ++i) {
3874       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3875         return false;
3876       if (NumElts != 8 || l == 0)
3877         continue;
3878       // VPERMILPS handling
3879       if (Mask[i] < 0)
3880         continue;
3881       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3882         return false;
3883     }
3884   }
3885
3886   return true;
3887 }
3888
3889 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3890 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3891 /// element of vector 2 and the other elements to come from vector 1 in order.
3892 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3893                                bool V2IsSplat = false, bool V2IsUndef = false) {
3894   if (!VT.is128BitVector())
3895     return false;
3896
3897   unsigned NumOps = VT.getVectorNumElements();
3898   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3899     return false;
3900
3901   if (!isUndefOrEqual(Mask[0], 0))
3902     return false;
3903
3904   for (unsigned i = 1; i != NumOps; ++i)
3905     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3906           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3907           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3908       return false;
3909
3910   return true;
3911 }
3912
3913 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3915 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3916 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3917                            const X86Subtarget *Subtarget) {
3918   if (!Subtarget->hasSSE3())
3919     return false;
3920
3921   unsigned NumElems = VT.getVectorNumElements();
3922
3923   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3924       (VT.getSizeInBits() == 256 && NumElems != 8))
3925     return false;
3926
3927   // "i+1" is the value the indexed mask element must have
3928   for (unsigned i = 0; i != NumElems; i += 2)
3929     if (!isUndefOrEqual(Mask[i], i+1) ||
3930         !isUndefOrEqual(Mask[i+1], i+1))
3931       return false;
3932
3933   return true;
3934 }
3935
3936 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3938 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3939 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3940                            const X86Subtarget *Subtarget) {
3941   if (!Subtarget->hasSSE3())
3942     return false;
3943
3944   unsigned NumElems = VT.getVectorNumElements();
3945
3946   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3947       (VT.getSizeInBits() == 256 && NumElems != 8))
3948     return false;
3949
3950   // "i" is the value the indexed mask element must have
3951   for (unsigned i = 0; i != NumElems; i += 2)
3952     if (!isUndefOrEqual(Mask[i], i) ||
3953         !isUndefOrEqual(Mask[i+1], i))
3954       return false;
3955
3956   return true;
3957 }
3958
3959 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to 256-bit
3961 /// version of MOVDDUP.
3962 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3963   if (!HasFp256 || !VT.is256BitVector())
3964     return false;
3965
3966   unsigned NumElts = VT.getVectorNumElements();
3967   if (NumElts != 4)
3968     return false;
3969
3970   for (unsigned i = 0; i != NumElts/2; ++i)
3971     if (!isUndefOrEqual(Mask[i], 0))
3972       return false;
3973   for (unsigned i = NumElts/2; i != NumElts; ++i)
3974     if (!isUndefOrEqual(Mask[i], NumElts/2))
3975       return false;
3976   return true;
3977 }
3978
3979 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3980 /// specifies a shuffle of elements that is suitable for input to 128-bit
3981 /// version of MOVDDUP.
3982 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3983   if (!VT.is128BitVector())
3984     return false;
3985
3986   unsigned e = VT.getVectorNumElements() / 2;
3987   for (unsigned i = 0; i != e; ++i)
3988     if (!isUndefOrEqual(Mask[i], i))
3989       return false;
3990   for (unsigned i = 0; i != e; ++i)
3991     if (!isUndefOrEqual(Mask[e+i], i))
3992       return false;
3993   return true;
3994 }
3995
3996 /// isVEXTRACTF128Index - Return true if the specified
3997 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3998 /// suitable for input to VEXTRACTF128.
3999 bool X86::isVEXTRACTF128Index(SDNode *N) {
4000   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4001     return false;
4002
4003   // The index should be aligned on a 128-bit boundary.
4004   uint64_t Index =
4005     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4006
4007   unsigned VL = N->getValueType(0).getVectorNumElements();
4008   unsigned VBits = N->getValueType(0).getSizeInBits();
4009   unsigned ElSize = VBits / VL;
4010   bool Result = (Index * ElSize) % 128 == 0;
4011
4012   return Result;
4013 }
4014
4015 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4016 /// operand specifies a subvector insert that is suitable for input to
4017 /// VINSERTF128.
4018 bool X86::isVINSERTF128Index(SDNode *N) {
4019   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4020     return false;
4021
4022   // The index should be aligned on a 128-bit boundary.
4023   uint64_t Index =
4024     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4025
4026   unsigned VL = N->getValueType(0).getVectorNumElements();
4027   unsigned VBits = N->getValueType(0).getSizeInBits();
4028   unsigned ElSize = VBits / VL;
4029   bool Result = (Index * ElSize) % 128 == 0;
4030
4031   return Result;
4032 }
4033
4034 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4035 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4036 /// Handles 128-bit and 256-bit.
4037 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4038   EVT VT = N->getValueType(0);
4039
4040   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4041          "Unsupported vector type for PSHUF/SHUFP");
4042
4043   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4044   // independently on 128-bit lanes.
4045   unsigned NumElts = VT.getVectorNumElements();
4046   unsigned NumLanes = VT.getSizeInBits()/128;
4047   unsigned NumLaneElts = NumElts/NumLanes;
4048
4049   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4050          "Only supports 2 or 4 elements per lane");
4051
4052   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4053   unsigned Mask = 0;
4054   for (unsigned i = 0; i != NumElts; ++i) {
4055     int Elt = N->getMaskElt(i);
4056     if (Elt < 0) continue;
4057     Elt &= NumLaneElts - 1;
4058     unsigned ShAmt = (i << Shift) % 8;
4059     Mask |= Elt << ShAmt;
4060   }
4061
4062   return Mask;
4063 }
4064
4065 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4067 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4068   EVT VT = N->getValueType(0);
4069
4070   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4071          "Unsupported vector type for PSHUFHW");
4072
4073   unsigned NumElts = VT.getVectorNumElements();
4074
4075   unsigned Mask = 0;
4076   for (unsigned l = 0; l != NumElts; l += 8) {
4077     // 8 nodes per lane, but we only care about the last 4.
4078     for (unsigned i = 0; i < 4; ++i) {
4079       int Elt = N->getMaskElt(l+i+4);
4080       if (Elt < 0) continue;
4081       Elt &= 0x3; // only 2-bits.
4082       Mask |= Elt << (i * 2);
4083     }
4084   }
4085
4086   return Mask;
4087 }
4088
4089 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4090 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4091 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4092   EVT VT = N->getValueType(0);
4093
4094   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4095          "Unsupported vector type for PSHUFHW");
4096
4097   unsigned NumElts = VT.getVectorNumElements();
4098
4099   unsigned Mask = 0;
4100   for (unsigned l = 0; l != NumElts; l += 8) {
4101     // 8 nodes per lane, but we only care about the first 4.
4102     for (unsigned i = 0; i < 4; ++i) {
4103       int Elt = N->getMaskElt(l+i);
4104       if (Elt < 0) continue;
4105       Elt &= 0x3; // only 2-bits
4106       Mask |= Elt << (i * 2);
4107     }
4108   }
4109
4110   return Mask;
4111 }
4112
4113 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4115 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4116   EVT VT = SVOp->getValueType(0);
4117   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4118
4119   unsigned NumElts = VT.getVectorNumElements();
4120   unsigned NumLanes = VT.getSizeInBits()/128;
4121   unsigned NumLaneElts = NumElts/NumLanes;
4122
4123   int Val = 0;
4124   unsigned i;
4125   for (i = 0; i != NumElts; ++i) {
4126     Val = SVOp->getMaskElt(i);
4127     if (Val >= 0)
4128       break;
4129   }
4130   if (Val >= (int)NumElts)
4131     Val -= NumElts - NumLaneElts;
4132
4133   assert(Val - i > 0 && "PALIGNR imm should be positive");
4134   return (Val - i) * EltSize;
4135 }
4136
4137 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4138 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4139 /// instructions.
4140 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4141   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4142     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4143
4144   uint64_t Index =
4145     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4146
4147   EVT VecVT = N->getOperand(0).getValueType();
4148   EVT ElVT = VecVT.getVectorElementType();
4149
4150   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4151   return Index / NumElemsPerChunk;
4152 }
4153
4154 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4155 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4156 /// instructions.
4157 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4158   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4159     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4160
4161   uint64_t Index =
4162     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4163
4164   EVT VecVT = N->getValueType(0);
4165   EVT ElVT = VecVT.getVectorElementType();
4166
4167   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4168   return Index / NumElemsPerChunk;
4169 }
4170
4171 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4172 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4173 /// Handles 256-bit.
4174 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4175   EVT VT = N->getValueType(0);
4176
4177   unsigned NumElts = VT.getVectorNumElements();
4178
4179   assert((VT.is256BitVector() && NumElts == 4) &&
4180          "Unsupported vector type for VPERMQ/VPERMPD");
4181
4182   unsigned Mask = 0;
4183   for (unsigned i = 0; i != NumElts; ++i) {
4184     int Elt = N->getMaskElt(i);
4185     if (Elt < 0)
4186       continue;
4187     Mask |= Elt << (i*2);
4188   }
4189
4190   return Mask;
4191 }
4192 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4193 /// constant +0.0.
4194 bool X86::isZeroNode(SDValue Elt) {
4195   return ((isa<ConstantSDNode>(Elt) &&
4196            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4197           (isa<ConstantFPSDNode>(Elt) &&
4198            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4199 }
4200
4201 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4202 /// their permute mask.
4203 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4204                                     SelectionDAG &DAG) {
4205   EVT VT = SVOp->getValueType(0);
4206   unsigned NumElems = VT.getVectorNumElements();
4207   SmallVector<int, 8> MaskVec;
4208
4209   for (unsigned i = 0; i != NumElems; ++i) {
4210     int Idx = SVOp->getMaskElt(i);
4211     if (Idx >= 0) {
4212       if (Idx < (int)NumElems)
4213         Idx += NumElems;
4214       else
4215         Idx -= NumElems;
4216     }
4217     MaskVec.push_back(Idx);
4218   }
4219   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4220                               SVOp->getOperand(0), &MaskVec[0]);
4221 }
4222
4223 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4224 /// match movhlps. The lower half elements should come from upper half of
4225 /// V1 (and in order), and the upper half elements should come from the upper
4226 /// half of V2 (and in order).
4227 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4228   if (!VT.is128BitVector())
4229     return false;
4230   if (VT.getVectorNumElements() != 4)
4231     return false;
4232   for (unsigned i = 0, e = 2; i != e; ++i)
4233     if (!isUndefOrEqual(Mask[i], i+2))
4234       return false;
4235   for (unsigned i = 2; i != 4; ++i)
4236     if (!isUndefOrEqual(Mask[i], i+4))
4237       return false;
4238   return true;
4239 }
4240
4241 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4242 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4243 /// required.
4244 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4245   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4246     return false;
4247   N = N->getOperand(0).getNode();
4248   if (!ISD::isNON_EXTLoad(N))
4249     return false;
4250   if (LD)
4251     *LD = cast<LoadSDNode>(N);
4252   return true;
4253 }
4254
4255 // Test whether the given value is a vector value which will be legalized
4256 // into a load.
4257 static bool WillBeConstantPoolLoad(SDNode *N) {
4258   if (N->getOpcode() != ISD::BUILD_VECTOR)
4259     return false;
4260
4261   // Check for any non-constant elements.
4262   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4263     switch (N->getOperand(i).getNode()->getOpcode()) {
4264     case ISD::UNDEF:
4265     case ISD::ConstantFP:
4266     case ISD::Constant:
4267       break;
4268     default:
4269       return false;
4270     }
4271
4272   // Vectors of all-zeros and all-ones are materialized with special
4273   // instructions rather than being loaded.
4274   return !ISD::isBuildVectorAllZeros(N) &&
4275          !ISD::isBuildVectorAllOnes(N);
4276 }
4277
4278 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4279 /// match movlp{s|d}. The lower half elements should come from lower half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order). And since V1 will become the source of the
4282 /// MOVLP, it must be either a vector load or a scalar load to vector.
4283 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4284                                ArrayRef<int> Mask, EVT VT) {
4285   if (!VT.is128BitVector())
4286     return false;
4287
4288   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4289     return false;
4290   // Is V2 is a vector load, don't do this transformation. We will try to use
4291   // load folding shufps op.
4292   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4293     return false;
4294
4295   unsigned NumElems = VT.getVectorNumElements();
4296
4297   if (NumElems != 2 && NumElems != 4)
4298     return false;
4299   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4300     if (!isUndefOrEqual(Mask[i], i))
4301       return false;
4302   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4303     if (!isUndefOrEqual(Mask[i], i+NumElems))
4304       return false;
4305   return true;
4306 }
4307
4308 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4309 /// all the same.
4310 static bool isSplatVector(SDNode *N) {
4311   if (N->getOpcode() != ISD::BUILD_VECTOR)
4312     return false;
4313
4314   SDValue SplatValue = N->getOperand(0);
4315   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4316     if (N->getOperand(i) != SplatValue)
4317       return false;
4318   return true;
4319 }
4320
4321 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4322 /// to an zero vector.
4323 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4324 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4325   SDValue V1 = N->getOperand(0);
4326   SDValue V2 = N->getOperand(1);
4327   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4328   for (unsigned i = 0; i != NumElems; ++i) {
4329     int Idx = N->getMaskElt(i);
4330     if (Idx >= (int)NumElems) {
4331       unsigned Opc = V2.getOpcode();
4332       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4333         continue;
4334       if (Opc != ISD::BUILD_VECTOR ||
4335           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4336         return false;
4337     } else if (Idx >= 0) {
4338       unsigned Opc = V1.getOpcode();
4339       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4340         continue;
4341       if (Opc != ISD::BUILD_VECTOR ||
4342           !X86::isZeroNode(V1.getOperand(Idx)))
4343         return false;
4344     }
4345   }
4346   return true;
4347 }
4348
4349 /// getZeroVector - Returns a vector of specified type with all zero elements.
4350 ///
4351 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4352                              SelectionDAG &DAG, DebugLoc dl) {
4353   assert(VT.isVector() && "Expected a vector type");
4354   unsigned Size = VT.getSizeInBits();
4355
4356   // Always build SSE zero vectors as <4 x i32> bitcasted
4357   // to their dest type. This ensures they get CSE'd.
4358   SDValue Vec;
4359   if (Size == 128) {  // SSE
4360     if (Subtarget->hasSSE2()) {  // SSE2
4361       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4363     } else { // SSE1
4364       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4365       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4366     }
4367   } else if (Size == 256) { // AVX
4368     if (Subtarget->hasInt256()) { // AVX2
4369       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4370       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4371       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4372     } else {
4373       // 256-bit logic and arithmetic instructions in AVX are all
4374       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4375       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4376       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4377       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4378     }
4379   } else
4380     llvm_unreachable("Unexpected vector type");
4381
4382   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4383 }
4384
4385 /// getOnesVector - Returns a vector of specified type with all bits set.
4386 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4387 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4388 /// Then bitcast to their original type, ensuring they get CSE'd.
4389 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4390                              DebugLoc dl) {
4391   assert(VT.isVector() && "Expected a vector type");
4392   unsigned Size = VT.getSizeInBits();
4393
4394   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4395   SDValue Vec;
4396   if (Size == 256) {
4397     if (HasInt256) { // AVX2
4398       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4399       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4400     } else { // AVX
4401       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4403     }
4404   } else if (Size == 128) {
4405     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4406   } else
4407     llvm_unreachable("Unexpected vector type");
4408
4409   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4410 }
4411
4412 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4413 /// that point to V2 points to its first element.
4414 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4415   for (unsigned i = 0; i != NumElems; ++i) {
4416     if (Mask[i] > (int)NumElems) {
4417       Mask[i] = NumElems;
4418     }
4419   }
4420 }
4421
4422 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4423 /// operation of specified width.
4424 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4425                        SDValue V2) {
4426   unsigned NumElems = VT.getVectorNumElements();
4427   SmallVector<int, 8> Mask;
4428   Mask.push_back(NumElems);
4429   for (unsigned i = 1; i != NumElems; ++i)
4430     Mask.push_back(i);
4431   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4432 }
4433
4434 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4435 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4436                           SDValue V2) {
4437   unsigned NumElems = VT.getVectorNumElements();
4438   SmallVector<int, 8> Mask;
4439   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4440     Mask.push_back(i);
4441     Mask.push_back(i + NumElems);
4442   }
4443   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4444 }
4445
4446 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4447 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4448                           SDValue V2) {
4449   unsigned NumElems = VT.getVectorNumElements();
4450   SmallVector<int, 8> Mask;
4451   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4452     Mask.push_back(i + Half);
4453     Mask.push_back(i + NumElems + Half);
4454   }
4455   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4456 }
4457
4458 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4459 // a generic shuffle instruction because the target has no such instructions.
4460 // Generate shuffles which repeat i16 and i8 several times until they can be
4461 // represented by v4f32 and then be manipulated by target suported shuffles.
4462 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4463   EVT VT = V.getValueType();
4464   int NumElems = VT.getVectorNumElements();
4465   DebugLoc dl = V.getDebugLoc();
4466
4467   while (NumElems > 4) {
4468     if (EltNo < NumElems/2) {
4469       V = getUnpackl(DAG, dl, VT, V, V);
4470     } else {
4471       V = getUnpackh(DAG, dl, VT, V, V);
4472       EltNo -= NumElems/2;
4473     }
4474     NumElems >>= 1;
4475   }
4476   return V;
4477 }
4478
4479 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4480 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4481   EVT VT = V.getValueType();
4482   DebugLoc dl = V.getDebugLoc();
4483   unsigned Size = VT.getSizeInBits();
4484
4485   if (Size == 128) {
4486     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4487     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4488     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4489                              &SplatMask[0]);
4490   } else if (Size == 256) {
4491     // To use VPERMILPS to splat scalars, the second half of indicies must
4492     // refer to the higher part, which is a duplication of the lower one,
4493     // because VPERMILPS can only handle in-lane permutations.
4494     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4495                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4496
4497     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4498     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4499                              &SplatMask[0]);
4500   } else
4501     llvm_unreachable("Vector size not supported");
4502
4503   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4504 }
4505
4506 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4507 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4508   EVT SrcVT = SV->getValueType(0);
4509   SDValue V1 = SV->getOperand(0);
4510   DebugLoc dl = SV->getDebugLoc();
4511
4512   int EltNo = SV->getSplatIndex();
4513   int NumElems = SrcVT.getVectorNumElements();
4514   unsigned Size = SrcVT.getSizeInBits();
4515
4516   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4517           "Unknown how to promote splat for type");
4518
4519   // Extract the 128-bit part containing the splat element and update
4520   // the splat element index when it refers to the higher register.
4521   if (Size == 256) {
4522     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4523     if (EltNo >= NumElems/2)
4524       EltNo -= NumElems/2;
4525   }
4526
4527   // All i16 and i8 vector types can't be used directly by a generic shuffle
4528   // instruction because the target has no such instruction. Generate shuffles
4529   // which repeat i16 and i8 several times until they fit in i32, and then can
4530   // be manipulated by target suported shuffles.
4531   EVT EltVT = SrcVT.getVectorElementType();
4532   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4533     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4534
4535   // Recreate the 256-bit vector and place the same 128-bit vector
4536   // into the low and high part. This is necessary because we want
4537   // to use VPERM* to shuffle the vectors
4538   if (Size == 256) {
4539     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4540   }
4541
4542   return getLegalSplat(DAG, V1, EltNo);
4543 }
4544
4545 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4546 /// vector of zero or undef vector.  This produces a shuffle where the low
4547 /// element of V2 is swizzled into the zero/undef vector, landing at element
4548 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4549 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4550                                            bool IsZero,
4551                                            const X86Subtarget *Subtarget,
4552                                            SelectionDAG &DAG) {
4553   EVT VT = V2.getValueType();
4554   SDValue V1 = IsZero
4555     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4556   unsigned NumElems = VT.getVectorNumElements();
4557   SmallVector<int, 16> MaskVec;
4558   for (unsigned i = 0; i != NumElems; ++i)
4559     // If this is the insertion idx, put the low elt of V2 here.
4560     MaskVec.push_back(i == Idx ? NumElems : i);
4561   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4562 }
4563
4564 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4565 /// target specific opcode. Returns true if the Mask could be calculated.
4566 /// Sets IsUnary to true if only uses one source.
4567 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4568                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4569   unsigned NumElems = VT.getVectorNumElements();
4570   SDValue ImmN;
4571
4572   IsUnary = false;
4573   switch(N->getOpcode()) {
4574   case X86ISD::SHUFP:
4575     ImmN = N->getOperand(N->getNumOperands()-1);
4576     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577     break;
4578   case X86ISD::UNPCKH:
4579     DecodeUNPCKHMask(VT, Mask);
4580     break;
4581   case X86ISD::UNPCKL:
4582     DecodeUNPCKLMask(VT, Mask);
4583     break;
4584   case X86ISD::MOVHLPS:
4585     DecodeMOVHLPSMask(NumElems, Mask);
4586     break;
4587   case X86ISD::MOVLHPS:
4588     DecodeMOVLHPSMask(NumElems, Mask);
4589     break;
4590   case X86ISD::PSHUFD:
4591   case X86ISD::VPERMILP:
4592     ImmN = N->getOperand(N->getNumOperands()-1);
4593     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4594     IsUnary = true;
4595     break;
4596   case X86ISD::PSHUFHW:
4597     ImmN = N->getOperand(N->getNumOperands()-1);
4598     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4599     IsUnary = true;
4600     break;
4601   case X86ISD::PSHUFLW:
4602     ImmN = N->getOperand(N->getNumOperands()-1);
4603     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4604     IsUnary = true;
4605     break;
4606   case X86ISD::VPERMI:
4607     ImmN = N->getOperand(N->getNumOperands()-1);
4608     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4609     IsUnary = true;
4610     break;
4611   case X86ISD::MOVSS:
4612   case X86ISD::MOVSD: {
4613     // The index 0 always comes from the first element of the second source,
4614     // this is why MOVSS and MOVSD are used in the first place. The other
4615     // elements come from the other positions of the first source vector
4616     Mask.push_back(NumElems);
4617     for (unsigned i = 1; i != NumElems; ++i) {
4618       Mask.push_back(i);
4619     }
4620     break;
4621   }
4622   case X86ISD::VPERM2X128:
4623     ImmN = N->getOperand(N->getNumOperands()-1);
4624     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4625     if (Mask.empty()) return false;
4626     break;
4627   case X86ISD::MOVDDUP:
4628   case X86ISD::MOVLHPD:
4629   case X86ISD::MOVLPD:
4630   case X86ISD::MOVLPS:
4631   case X86ISD::MOVSHDUP:
4632   case X86ISD::MOVSLDUP:
4633   case X86ISD::PALIGN:
4634     // Not yet implemented
4635     return false;
4636   default: llvm_unreachable("unknown target shuffle node");
4637   }
4638
4639   return true;
4640 }
4641
4642 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4643 /// element of the result of the vector shuffle.
4644 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4645                                    unsigned Depth) {
4646   if (Depth == 6)
4647     return SDValue();  // Limit search depth.
4648
4649   SDValue V = SDValue(N, 0);
4650   EVT VT = V.getValueType();
4651   unsigned Opcode = V.getOpcode();
4652
4653   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4654   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4655     int Elt = SV->getMaskElt(Index);
4656
4657     if (Elt < 0)
4658       return DAG.getUNDEF(VT.getVectorElementType());
4659
4660     unsigned NumElems = VT.getVectorNumElements();
4661     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4662                                          : SV->getOperand(1);
4663     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4664   }
4665
4666   // Recurse into target specific vector shuffles to find scalars.
4667   if (isTargetShuffle(Opcode)) {
4668     MVT ShufVT = V.getValueType().getSimpleVT();
4669     unsigned NumElems = ShufVT.getVectorNumElements();
4670     SmallVector<int, 16> ShuffleMask;
4671     bool IsUnary;
4672
4673     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4674       return SDValue();
4675
4676     int Elt = ShuffleMask[Index];
4677     if (Elt < 0)
4678       return DAG.getUNDEF(ShufVT.getVectorElementType());
4679
4680     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4681                                          : N->getOperand(1);
4682     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4683                                Depth+1);
4684   }
4685
4686   // Actual nodes that may contain scalar elements
4687   if (Opcode == ISD::BITCAST) {
4688     V = V.getOperand(0);
4689     EVT SrcVT = V.getValueType();
4690     unsigned NumElems = VT.getVectorNumElements();
4691
4692     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4693       return SDValue();
4694   }
4695
4696   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4697     return (Index == 0) ? V.getOperand(0)
4698                         : DAG.getUNDEF(VT.getVectorElementType());
4699
4700   if (V.getOpcode() == ISD::BUILD_VECTOR)
4701     return V.getOperand(Index);
4702
4703   return SDValue();
4704 }
4705
4706 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4707 /// shuffle operation which come from a consecutively from a zero. The
4708 /// search can start in two different directions, from left or right.
4709 static
4710 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4711                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4712   unsigned i;
4713   for (i = 0; i != NumElems; ++i) {
4714     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4715     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4716     if (!(Elt.getNode() &&
4717          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4718       break;
4719   }
4720
4721   return i;
4722 }
4723
4724 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4725 /// correspond consecutively to elements from one of the vector operands,
4726 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4727 static
4728 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4729                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4730                               unsigned NumElems, unsigned &OpNum) {
4731   bool SeenV1 = false;
4732   bool SeenV2 = false;
4733
4734   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4735     int Idx = SVOp->getMaskElt(i);
4736     // Ignore undef indicies
4737     if (Idx < 0)
4738       continue;
4739
4740     if (Idx < (int)NumElems)
4741       SeenV1 = true;
4742     else
4743       SeenV2 = true;
4744
4745     // Only accept consecutive elements from the same vector
4746     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4747       return false;
4748   }
4749
4750   OpNum = SeenV1 ? 0 : 1;
4751   return true;
4752 }
4753
4754 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4755 /// logical left shift of a vector.
4756 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4757                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4758   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4759   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4760               false /* check zeros from right */, DAG);
4761   unsigned OpSrc;
4762
4763   if (!NumZeros)
4764     return false;
4765
4766   // Considering the elements in the mask that are not consecutive zeros,
4767   // check if they consecutively come from only one of the source vectors.
4768   //
4769   //               V1 = {X, A, B, C}     0
4770   //                         \  \  \    /
4771   //   vector_shuffle V1, V2 <1, 2, 3, X>
4772   //
4773   if (!isShuffleMaskConsecutive(SVOp,
4774             0,                   // Mask Start Index
4775             NumElems-NumZeros,   // Mask End Index(exclusive)
4776             NumZeros,            // Where to start looking in the src vector
4777             NumElems,            // Number of elements in vector
4778             OpSrc))              // Which source operand ?
4779     return false;
4780
4781   isLeft = false;
4782   ShAmt = NumZeros;
4783   ShVal = SVOp->getOperand(OpSrc);
4784   return true;
4785 }
4786
4787 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4788 /// logical left shift of a vector.
4789 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4790                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4791   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4792   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4793               true /* check zeros from left */, DAG);
4794   unsigned OpSrc;
4795
4796   if (!NumZeros)
4797     return false;
4798
4799   // Considering the elements in the mask that are not consecutive zeros,
4800   // check if they consecutively come from only one of the source vectors.
4801   //
4802   //                           0    { A, B, X, X } = V2
4803   //                          / \    /  /
4804   //   vector_shuffle V1, V2 <X, X, 4, 5>
4805   //
4806   if (!isShuffleMaskConsecutive(SVOp,
4807             NumZeros,     // Mask Start Index
4808             NumElems,     // Mask End Index(exclusive)
4809             0,            // Where to start looking in the src vector
4810             NumElems,     // Number of elements in vector
4811             OpSrc))       // Which source operand ?
4812     return false;
4813
4814   isLeft = true;
4815   ShAmt = NumZeros;
4816   ShVal = SVOp->getOperand(OpSrc);
4817   return true;
4818 }
4819
4820 /// isVectorShift - Returns true if the shuffle can be implemented as a
4821 /// logical left or right shift of a vector.
4822 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4823                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4824   // Although the logic below support any bitwidth size, there are no
4825   // shift instructions which handle more than 128-bit vectors.
4826   if (!SVOp->getValueType(0).is128BitVector())
4827     return false;
4828
4829   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4830       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4831     return true;
4832
4833   return false;
4834 }
4835
4836 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4837 ///
4838 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4839                                        unsigned NumNonZero, unsigned NumZero,
4840                                        SelectionDAG &DAG,
4841                                        const X86Subtarget* Subtarget,
4842                                        const TargetLowering &TLI) {
4843   if (NumNonZero > 8)
4844     return SDValue();
4845
4846   DebugLoc dl = Op.getDebugLoc();
4847   SDValue V(0, 0);
4848   bool First = true;
4849   for (unsigned i = 0; i < 16; ++i) {
4850     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4851     if (ThisIsNonZero && First) {
4852       if (NumZero)
4853         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4854       else
4855         V = DAG.getUNDEF(MVT::v8i16);
4856       First = false;
4857     }
4858
4859     if ((i & 1) != 0) {
4860       SDValue ThisElt(0, 0), LastElt(0, 0);
4861       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4862       if (LastIsNonZero) {
4863         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4864                               MVT::i16, Op.getOperand(i-1));
4865       }
4866       if (ThisIsNonZero) {
4867         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4868         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4869                               ThisElt, DAG.getConstant(8, MVT::i8));
4870         if (LastIsNonZero)
4871           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4872       } else
4873         ThisElt = LastElt;
4874
4875       if (ThisElt.getNode())
4876         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4877                         DAG.getIntPtrConstant(i/2));
4878     }
4879   }
4880
4881   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4882 }
4883
4884 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4885 ///
4886 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4887                                      unsigned NumNonZero, unsigned NumZero,
4888                                      SelectionDAG &DAG,
4889                                      const X86Subtarget* Subtarget,
4890                                      const TargetLowering &TLI) {
4891   if (NumNonZero > 4)
4892     return SDValue();
4893
4894   DebugLoc dl = Op.getDebugLoc();
4895   SDValue V(0, 0);
4896   bool First = true;
4897   for (unsigned i = 0; i < 8; ++i) {
4898     bool isNonZero = (NonZeros & (1 << i)) != 0;
4899     if (isNonZero) {
4900       if (First) {
4901         if (NumZero)
4902           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4903         else
4904           V = DAG.getUNDEF(MVT::v8i16);
4905         First = false;
4906       }
4907       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4908                       MVT::v8i16, V, Op.getOperand(i),
4909                       DAG.getIntPtrConstant(i));
4910     }
4911   }
4912
4913   return V;
4914 }
4915
4916 /// getVShift - Return a vector logical shift node.
4917 ///
4918 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4919                          unsigned NumBits, SelectionDAG &DAG,
4920                          const TargetLowering &TLI, DebugLoc dl) {
4921   assert(VT.is128BitVector() && "Unknown type for VShift");
4922   EVT ShVT = MVT::v2i64;
4923   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4924   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4925   return DAG.getNode(ISD::BITCAST, dl, VT,
4926                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4927                              DAG.getConstant(NumBits,
4928                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4929 }
4930
4931 SDValue
4932 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4933                                           SelectionDAG &DAG) const {
4934
4935   // Check if the scalar load can be widened into a vector load. And if
4936   // the address is "base + cst" see if the cst can be "absorbed" into
4937   // the shuffle mask.
4938   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4939     SDValue Ptr = LD->getBasePtr();
4940     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4941       return SDValue();
4942     EVT PVT = LD->getValueType(0);
4943     if (PVT != MVT::i32 && PVT != MVT::f32)
4944       return SDValue();
4945
4946     int FI = -1;
4947     int64_t Offset = 0;
4948     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4949       FI = FINode->getIndex();
4950       Offset = 0;
4951     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4952                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4953       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4954       Offset = Ptr.getConstantOperandVal(1);
4955       Ptr = Ptr.getOperand(0);
4956     } else {
4957       return SDValue();
4958     }
4959
4960     // FIXME: 256-bit vector instructions don't require a strict alignment,
4961     // improve this code to support it better.
4962     unsigned RequiredAlign = VT.getSizeInBits()/8;
4963     SDValue Chain = LD->getChain();
4964     // Make sure the stack object alignment is at least 16 or 32.
4965     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4966     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4967       if (MFI->isFixedObjectIndex(FI)) {
4968         // Can't change the alignment. FIXME: It's possible to compute
4969         // the exact stack offset and reference FI + adjust offset instead.
4970         // If someone *really* cares about this. That's the way to implement it.
4971         return SDValue();
4972       } else {
4973         MFI->setObjectAlignment(FI, RequiredAlign);
4974       }
4975     }
4976
4977     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4978     // Ptr + (Offset & ~15).
4979     if (Offset < 0)
4980       return SDValue();
4981     if ((Offset % RequiredAlign) & 3)
4982       return SDValue();
4983     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4984     if (StartOffset)
4985       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4986                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4987
4988     int EltNo = (Offset - StartOffset) >> 2;
4989     unsigned NumElems = VT.getVectorNumElements();
4990
4991     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4992     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4993                              LD->getPointerInfo().getWithOffset(StartOffset),
4994                              false, false, false, 0);
4995
4996     SmallVector<int, 8> Mask;
4997     for (unsigned i = 0; i != NumElems; ++i)
4998       Mask.push_back(EltNo);
4999
5000     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5001   }
5002
5003   return SDValue();
5004 }
5005
5006 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5007 /// vector of type 'VT', see if the elements can be replaced by a single large
5008 /// load which has the same value as a build_vector whose operands are 'elts'.
5009 ///
5010 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5011 ///
5012 /// FIXME: we'd also like to handle the case where the last elements are zero
5013 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5014 /// There's even a handy isZeroNode for that purpose.
5015 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5016                                         DebugLoc &DL, SelectionDAG &DAG) {
5017   EVT EltVT = VT.getVectorElementType();
5018   unsigned NumElems = Elts.size();
5019
5020   LoadSDNode *LDBase = NULL;
5021   unsigned LastLoadedElt = -1U;
5022
5023   // For each element in the initializer, see if we've found a load or an undef.
5024   // If we don't find an initial load element, or later load elements are
5025   // non-consecutive, bail out.
5026   for (unsigned i = 0; i < NumElems; ++i) {
5027     SDValue Elt = Elts[i];
5028
5029     if (!Elt.getNode() ||
5030         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5031       return SDValue();
5032     if (!LDBase) {
5033       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5034         return SDValue();
5035       LDBase = cast<LoadSDNode>(Elt.getNode());
5036       LastLoadedElt = i;
5037       continue;
5038     }
5039     if (Elt.getOpcode() == ISD::UNDEF)
5040       continue;
5041
5042     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5043     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5044       return SDValue();
5045     LastLoadedElt = i;
5046   }
5047
5048   // If we have found an entire vector of loads and undefs, then return a large
5049   // load of the entire vector width starting at the base pointer.  If we found
5050   // consecutive loads for the low half, generate a vzext_load node.
5051   if (LastLoadedElt == NumElems - 1) {
5052     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5053       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5054                          LDBase->getPointerInfo(),
5055                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5056                          LDBase->isInvariant(), 0);
5057     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5058                        LDBase->getPointerInfo(),
5059                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5060                        LDBase->isInvariant(), LDBase->getAlignment());
5061   }
5062   if (NumElems == 4 && LastLoadedElt == 1 &&
5063       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5064     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5065     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5066     SDValue ResNode =
5067         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5068                                 LDBase->getPointerInfo(),
5069                                 LDBase->getAlignment(),
5070                                 false/*isVolatile*/, true/*ReadMem*/,
5071                                 false/*WriteMem*/);
5072
5073     // Make sure the newly-created LOAD is in the same position as LDBase in
5074     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5075     // update uses of LDBase's output chain to use the TokenFactor.
5076     if (LDBase->hasAnyUseOfValue(1)) {
5077       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5078                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5079       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5080       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5081                              SDValue(ResNode.getNode(), 1));
5082     }
5083
5084     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5085   }
5086   return SDValue();
5087 }
5088
5089 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5090 /// to generate a splat value for the following cases:
5091 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5092 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5093 /// a scalar load, or a constant.
5094 /// The VBROADCAST node is returned when a pattern is found,
5095 /// or SDValue() otherwise.
5096 SDValue
5097 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5098   if (!Subtarget->hasFp256())
5099     return SDValue();
5100
5101   EVT VT = Op.getValueType();
5102   DebugLoc dl = Op.getDebugLoc();
5103
5104   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5105          "Unsupported vector type for broadcast.");
5106
5107   SDValue Ld;
5108   bool ConstSplatVal;
5109
5110   switch (Op.getOpcode()) {
5111     default:
5112       // Unknown pattern found.
5113       return SDValue();
5114
5115     case ISD::BUILD_VECTOR: {
5116       // The BUILD_VECTOR node must be a splat.
5117       if (!isSplatVector(Op.getNode()))
5118         return SDValue();
5119
5120       Ld = Op.getOperand(0);
5121       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5122                      Ld.getOpcode() == ISD::ConstantFP);
5123
5124       // The suspected load node has several users. Make sure that all
5125       // of its users are from the BUILD_VECTOR node.
5126       // Constants may have multiple users.
5127       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5128         return SDValue();
5129       break;
5130     }
5131
5132     case ISD::VECTOR_SHUFFLE: {
5133       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5134
5135       // Shuffles must have a splat mask where the first element is
5136       // broadcasted.
5137       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5138         return SDValue();
5139
5140       SDValue Sc = Op.getOperand(0);
5141       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5142           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5143
5144         if (!Subtarget->hasInt256())
5145           return SDValue();
5146
5147         // Use the register form of the broadcast instruction available on AVX2.
5148         if (VT.is256BitVector())
5149           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5150         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5151       }
5152
5153       Ld = Sc.getOperand(0);
5154       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5155                        Ld.getOpcode() == ISD::ConstantFP);
5156
5157       // The scalar_to_vector node and the suspected
5158       // load node must have exactly one user.
5159       // Constants may have multiple users.
5160       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5161         return SDValue();
5162       break;
5163     }
5164   }
5165
5166   bool Is256 = VT.is256BitVector();
5167
5168   // Handle the broadcasting a single constant scalar from the constant pool
5169   // into a vector. On Sandybridge it is still better to load a constant vector
5170   // from the constant pool and not to broadcast it from a scalar.
5171   if (ConstSplatVal && Subtarget->hasInt256()) {
5172     EVT CVT = Ld.getValueType();
5173     assert(!CVT.isVector() && "Must not broadcast a vector type");
5174     unsigned ScalarSize = CVT.getSizeInBits();
5175
5176     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5177       const Constant *C = 0;
5178       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5179         C = CI->getConstantIntValue();
5180       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5181         C = CF->getConstantFPValue();
5182
5183       assert(C && "Invalid constant type");
5184
5185       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5186       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5187       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5188                        MachinePointerInfo::getConstantPool(),
5189                        false, false, false, Alignment);
5190
5191       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5192     }
5193   }
5194
5195   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5196   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5197
5198   // Handle AVX2 in-register broadcasts.
5199   if (!IsLoad && Subtarget->hasInt256() &&
5200       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5201     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5202
5203   // The scalar source must be a normal load.
5204   if (!IsLoad)
5205     return SDValue();
5206
5207   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5208     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5209
5210   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5211   // double since there is no vbroadcastsd xmm
5212   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5213     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5214       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5215   }
5216
5217   // Unsupported broadcast.
5218   return SDValue();
5219 }
5220
5221 SDValue
5222 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5223   EVT VT = Op.getValueType();
5224
5225   // Skip if insert_vec_elt is not supported.
5226   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5227     return SDValue();
5228
5229   DebugLoc DL = Op.getDebugLoc();
5230   unsigned NumElems = Op.getNumOperands();
5231
5232   SDValue VecIn1;
5233   SDValue VecIn2;
5234   SmallVector<unsigned, 4> InsertIndices;
5235   SmallVector<int, 8> Mask(NumElems, -1);
5236
5237   for (unsigned i = 0; i != NumElems; ++i) {
5238     unsigned Opc = Op.getOperand(i).getOpcode();
5239
5240     if (Opc == ISD::UNDEF)
5241       continue;
5242
5243     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5244       // Quit if more than 1 elements need inserting.
5245       if (InsertIndices.size() > 1)
5246         return SDValue();
5247
5248       InsertIndices.push_back(i);
5249       continue;
5250     }
5251
5252     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5253     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5254
5255     // Quit if extracted from vector of different type.
5256     if (ExtractedFromVec.getValueType() != VT)
5257       return SDValue();
5258
5259     // Quit if non-constant index.
5260     if (!isa<ConstantSDNode>(ExtIdx))
5261       return SDValue();
5262
5263     if (VecIn1.getNode() == 0)
5264       VecIn1 = ExtractedFromVec;
5265     else if (VecIn1 != ExtractedFromVec) {
5266       if (VecIn2.getNode() == 0)
5267         VecIn2 = ExtractedFromVec;
5268       else if (VecIn2 != ExtractedFromVec)
5269         // Quit if more than 2 vectors to shuffle
5270         return SDValue();
5271     }
5272
5273     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5274
5275     if (ExtractedFromVec == VecIn1)
5276       Mask[i] = Idx;
5277     else if (ExtractedFromVec == VecIn2)
5278       Mask[i] = Idx + NumElems;
5279   }
5280
5281   if (VecIn1.getNode() == 0)
5282     return SDValue();
5283
5284   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5285   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5286   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5287     unsigned Idx = InsertIndices[i];
5288     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5289                      DAG.getIntPtrConstant(Idx));
5290   }
5291
5292   return NV;
5293 }
5294
5295 SDValue
5296 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5297   DebugLoc dl = Op.getDebugLoc();
5298
5299   EVT VT = Op.getValueType();
5300   EVT ExtVT = VT.getVectorElementType();
5301   unsigned NumElems = Op.getNumOperands();
5302
5303   // Vectors containing all zeros can be matched by pxor and xorps later
5304   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5305     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5306     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5307     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5308       return Op;
5309
5310     return getZeroVector(VT, Subtarget, DAG, dl);
5311   }
5312
5313   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5314   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5315   // vpcmpeqd on 256-bit vectors.
5316   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5317     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5318       return Op;
5319
5320     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5321   }
5322
5323   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5324   if (Broadcast.getNode())
5325     return Broadcast;
5326
5327   unsigned EVTBits = ExtVT.getSizeInBits();
5328
5329   unsigned NumZero  = 0;
5330   unsigned NumNonZero = 0;
5331   unsigned NonZeros = 0;
5332   bool IsAllConstants = true;
5333   SmallSet<SDValue, 8> Values;
5334   for (unsigned i = 0; i < NumElems; ++i) {
5335     SDValue Elt = Op.getOperand(i);
5336     if (Elt.getOpcode() == ISD::UNDEF)
5337       continue;
5338     Values.insert(Elt);
5339     if (Elt.getOpcode() != ISD::Constant &&
5340         Elt.getOpcode() != ISD::ConstantFP)
5341       IsAllConstants = false;
5342     if (X86::isZeroNode(Elt))
5343       NumZero++;
5344     else {
5345       NonZeros |= (1 << i);
5346       NumNonZero++;
5347     }
5348   }
5349
5350   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5351   if (NumNonZero == 0)
5352     return DAG.getUNDEF(VT);
5353
5354   // Special case for single non-zero, non-undef, element.
5355   if (NumNonZero == 1) {
5356     unsigned Idx = CountTrailingZeros_32(NonZeros);
5357     SDValue Item = Op.getOperand(Idx);
5358
5359     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5360     // the value are obviously zero, truncate the value to i32 and do the
5361     // insertion that way.  Only do this if the value is non-constant or if the
5362     // value is a constant being inserted into element 0.  It is cheaper to do
5363     // a constant pool load than it is to do a movd + shuffle.
5364     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5365         (!IsAllConstants || Idx == 0)) {
5366       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5367         // Handle SSE only.
5368         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5369         EVT VecVT = MVT::v4i32;
5370         unsigned VecElts = 4;
5371
5372         // Truncate the value (which may itself be a constant) to i32, and
5373         // convert it to a vector with movd (S2V+shuffle to zero extend).
5374         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5375         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5376         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5377
5378         // Now we have our 32-bit value zero extended in the low element of
5379         // a vector.  If Idx != 0, swizzle it into place.
5380         if (Idx != 0) {
5381           SmallVector<int, 4> Mask;
5382           Mask.push_back(Idx);
5383           for (unsigned i = 1; i != VecElts; ++i)
5384             Mask.push_back(i);
5385           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5386                                       &Mask[0]);
5387         }
5388         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5389       }
5390     }
5391
5392     // If we have a constant or non-constant insertion into the low element of
5393     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5394     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5395     // depending on what the source datatype is.
5396     if (Idx == 0) {
5397       if (NumZero == 0)
5398         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5399
5400       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5401           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5402         if (VT.is256BitVector()) {
5403           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5404           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5405                              Item, DAG.getIntPtrConstant(0));
5406         }
5407         assert(VT.is128BitVector() && "Expected an SSE value type!");
5408         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5409         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5410         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5411       }
5412
5413       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5414         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5415         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5416         if (VT.is256BitVector()) {
5417           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5418           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5419         } else {
5420           assert(VT.is128BitVector() && "Expected an SSE value type!");
5421           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5422         }
5423         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5424       }
5425     }
5426
5427     // Is it a vector logical left shift?
5428     if (NumElems == 2 && Idx == 1 &&
5429         X86::isZeroNode(Op.getOperand(0)) &&
5430         !X86::isZeroNode(Op.getOperand(1))) {
5431       unsigned NumBits = VT.getSizeInBits();
5432       return getVShift(true, VT,
5433                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5434                                    VT, Op.getOperand(1)),
5435                        NumBits/2, DAG, *this, dl);
5436     }
5437
5438     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5439       return SDValue();
5440
5441     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5442     // is a non-constant being inserted into an element other than the low one,
5443     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5444     // movd/movss) to move this into the low element, then shuffle it into
5445     // place.
5446     if (EVTBits == 32) {
5447       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5448
5449       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5450       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5451       SmallVector<int, 8> MaskVec;
5452       for (unsigned i = 0; i != NumElems; ++i)
5453         MaskVec.push_back(i == Idx ? 0 : 1);
5454       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5455     }
5456   }
5457
5458   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5459   if (Values.size() == 1) {
5460     if (EVTBits == 32) {
5461       // Instead of a shuffle like this:
5462       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5463       // Check if it's possible to issue this instead.
5464       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5465       unsigned Idx = CountTrailingZeros_32(NonZeros);
5466       SDValue Item = Op.getOperand(Idx);
5467       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5468         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5469     }
5470     return SDValue();
5471   }
5472
5473   // A vector full of immediates; various special cases are already
5474   // handled, so this is best done with a single constant-pool load.
5475   if (IsAllConstants)
5476     return SDValue();
5477
5478   // For AVX-length vectors, build the individual 128-bit pieces and use
5479   // shuffles to put them in place.
5480   if (VT.is256BitVector()) {
5481     SmallVector<SDValue, 32> V;
5482     for (unsigned i = 0; i != NumElems; ++i)
5483       V.push_back(Op.getOperand(i));
5484
5485     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5486
5487     // Build both the lower and upper subvector.
5488     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5489     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5490                                 NumElems/2);
5491
5492     // Recreate the wider vector with the lower and upper part.
5493     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5494   }
5495
5496   // Let legalizer expand 2-wide build_vectors.
5497   if (EVTBits == 64) {
5498     if (NumNonZero == 1) {
5499       // One half is zero or undef.
5500       unsigned Idx = CountTrailingZeros_32(NonZeros);
5501       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5502                                  Op.getOperand(Idx));
5503       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5504     }
5505     return SDValue();
5506   }
5507
5508   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5509   if (EVTBits == 8 && NumElems == 16) {
5510     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5511                                         Subtarget, *this);
5512     if (V.getNode()) return V;
5513   }
5514
5515   if (EVTBits == 16 && NumElems == 8) {
5516     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5517                                       Subtarget, *this);
5518     if (V.getNode()) return V;
5519   }
5520
5521   // If element VT is == 32 bits, turn it into a number of shuffles.
5522   SmallVector<SDValue, 8> V(NumElems);
5523   if (NumElems == 4 && NumZero > 0) {
5524     for (unsigned i = 0; i < 4; ++i) {
5525       bool isZero = !(NonZeros & (1 << i));
5526       if (isZero)
5527         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5528       else
5529         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5530     }
5531
5532     for (unsigned i = 0; i < 2; ++i) {
5533       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5534         default: break;
5535         case 0:
5536           V[i] = V[i*2];  // Must be a zero vector.
5537           break;
5538         case 1:
5539           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5540           break;
5541         case 2:
5542           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5543           break;
5544         case 3:
5545           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5546           break;
5547       }
5548     }
5549
5550     bool Reverse1 = (NonZeros & 0x3) == 2;
5551     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5552     int MaskVec[] = {
5553       Reverse1 ? 1 : 0,
5554       Reverse1 ? 0 : 1,
5555       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5556       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5557     };
5558     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5559   }
5560
5561   if (Values.size() > 1 && VT.is128BitVector()) {
5562     // Check for a build vector of consecutive loads.
5563     for (unsigned i = 0; i < NumElems; ++i)
5564       V[i] = Op.getOperand(i);
5565
5566     // Check for elements which are consecutive loads.
5567     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5568     if (LD.getNode())
5569       return LD;
5570
5571     // Check for a build vector from mostly shuffle plus few inserting.
5572     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5573     if (Sh.getNode())
5574       return Sh;
5575
5576     // For SSE 4.1, use insertps to put the high elements into the low element.
5577     if (getSubtarget()->hasSSE41()) {
5578       SDValue Result;
5579       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5580         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5581       else
5582         Result = DAG.getUNDEF(VT);
5583
5584       for (unsigned i = 1; i < NumElems; ++i) {
5585         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5586         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5587                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5588       }
5589       return Result;
5590     }
5591
5592     // Otherwise, expand into a number of unpckl*, start by extending each of
5593     // our (non-undef) elements to the full vector width with the element in the
5594     // bottom slot of the vector (which generates no code for SSE).
5595     for (unsigned i = 0; i < NumElems; ++i) {
5596       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5597         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5598       else
5599         V[i] = DAG.getUNDEF(VT);
5600     }
5601
5602     // Next, we iteratively mix elements, e.g. for v4f32:
5603     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5604     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5605     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5606     unsigned EltStride = NumElems >> 1;
5607     while (EltStride != 0) {
5608       for (unsigned i = 0; i < EltStride; ++i) {
5609         // If V[i+EltStride] is undef and this is the first round of mixing,
5610         // then it is safe to just drop this shuffle: V[i] is already in the
5611         // right place, the one element (since it's the first round) being
5612         // inserted as undef can be dropped.  This isn't safe for successive
5613         // rounds because they will permute elements within both vectors.
5614         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5615             EltStride == NumElems/2)
5616           continue;
5617
5618         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5619       }
5620       EltStride >>= 1;
5621     }
5622     return V[0];
5623   }
5624   return SDValue();
5625 }
5626
5627 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5628 // to create 256-bit vectors from two other 128-bit ones.
5629 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5630   DebugLoc dl = Op.getDebugLoc();
5631   EVT ResVT = Op.getValueType();
5632
5633   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5634
5635   SDValue V1 = Op.getOperand(0);
5636   SDValue V2 = Op.getOperand(1);
5637   unsigned NumElems = ResVT.getVectorNumElements();
5638
5639   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5640 }
5641
5642 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5643   assert(Op.getNumOperands() == 2);
5644
5645   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5646   // from two other 128-bit ones.
5647   return LowerAVXCONCAT_VECTORS(Op, DAG);
5648 }
5649
5650 // Try to lower a shuffle node into a simple blend instruction.
5651 static SDValue
5652 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5653                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5654   SDValue V1 = SVOp->getOperand(0);
5655   SDValue V2 = SVOp->getOperand(1);
5656   DebugLoc dl = SVOp->getDebugLoc();
5657   EVT VT = SVOp->getValueType(0);
5658   EVT EltVT = VT.getVectorElementType();
5659   unsigned NumElems = VT.getVectorNumElements();
5660
5661   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5662     return SDValue();
5663   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5664     return SDValue();
5665
5666   // Check the mask for BLEND and build the value.
5667   unsigned MaskValue = 0;
5668   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5669   unsigned NumLanes = (NumElems-1)/8 + 1; 
5670   unsigned NumElemsInLane = NumElems / NumLanes;
5671
5672   // Blend for v16i16 should be symetric for the both lanes.
5673   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5674
5675     int SndLaneEltIdx = (NumLanes == 2) ? 
5676       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5677     int EltIdx = SVOp->getMaskElt(i);
5678
5679     if ((EltIdx == -1 || EltIdx == (int)i) && 
5680         (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5681       continue;
5682
5683     if (((unsigned)EltIdx == (i + NumElems)) && 
5684         (SndLaneEltIdx == -1 || 
5685          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5686       MaskValue |= (1<<i);
5687     else 
5688       return SDValue();
5689   }
5690
5691   // Convert i32 vectors to floating point if it is not AVX2.
5692   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5693   EVT BlendVT = VT;
5694   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5695     BlendVT = EVT::getVectorVT(*DAG.getContext(), 
5696                               EVT::getFloatingPointVT(EltVT.getSizeInBits()), 
5697                               NumElems);
5698     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5699     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5700   }
5701   
5702   SDValue Ret =  DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5703                              DAG.getConstant(MaskValue, MVT::i32));
5704   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5705 }
5706
5707 // v8i16 shuffles - Prefer shuffles in the following order:
5708 // 1. [all]   pshuflw, pshufhw, optional move
5709 // 2. [ssse3] 1 x pshufb
5710 // 3. [ssse3] 2 x pshufb + 1 x por
5711 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5712 static SDValue
5713 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5714                          SelectionDAG &DAG) {
5715   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5716   SDValue V1 = SVOp->getOperand(0);
5717   SDValue V2 = SVOp->getOperand(1);
5718   DebugLoc dl = SVOp->getDebugLoc();
5719   SmallVector<int, 8> MaskVals;
5720
5721   // Determine if more than 1 of the words in each of the low and high quadwords
5722   // of the result come from the same quadword of one of the two inputs.  Undef
5723   // mask values count as coming from any quadword, for better codegen.
5724   unsigned LoQuad[] = { 0, 0, 0, 0 };
5725   unsigned HiQuad[] = { 0, 0, 0, 0 };
5726   std::bitset<4> InputQuads;
5727   for (unsigned i = 0; i < 8; ++i) {
5728     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5729     int EltIdx = SVOp->getMaskElt(i);
5730     MaskVals.push_back(EltIdx);
5731     if (EltIdx < 0) {
5732       ++Quad[0];
5733       ++Quad[1];
5734       ++Quad[2];
5735       ++Quad[3];
5736       continue;
5737     }
5738     ++Quad[EltIdx / 4];
5739     InputQuads.set(EltIdx / 4);
5740   }
5741
5742   int BestLoQuad = -1;
5743   unsigned MaxQuad = 1;
5744   for (unsigned i = 0; i < 4; ++i) {
5745     if (LoQuad[i] > MaxQuad) {
5746       BestLoQuad = i;
5747       MaxQuad = LoQuad[i];
5748     }
5749   }
5750
5751   int BestHiQuad = -1;
5752   MaxQuad = 1;
5753   for (unsigned i = 0; i < 4; ++i) {
5754     if (HiQuad[i] > MaxQuad) {
5755       BestHiQuad = i;
5756       MaxQuad = HiQuad[i];
5757     }
5758   }
5759
5760   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5761   // of the two input vectors, shuffle them into one input vector so only a
5762   // single pshufb instruction is necessary. If There are more than 2 input
5763   // quads, disable the next transformation since it does not help SSSE3.
5764   bool V1Used = InputQuads[0] || InputQuads[1];
5765   bool V2Used = InputQuads[2] || InputQuads[3];
5766   if (Subtarget->hasSSSE3()) {
5767     if (InputQuads.count() == 2 && V1Used && V2Used) {
5768       BestLoQuad = InputQuads[0] ? 0 : 1;
5769       BestHiQuad = InputQuads[2] ? 2 : 3;
5770     }
5771     if (InputQuads.count() > 2) {
5772       BestLoQuad = -1;
5773       BestHiQuad = -1;
5774     }
5775   }
5776
5777   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5778   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5779   // words from all 4 input quadwords.
5780   SDValue NewV;
5781   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5782     int MaskV[] = {
5783       BestLoQuad < 0 ? 0 : BestLoQuad,
5784       BestHiQuad < 0 ? 1 : BestHiQuad
5785     };
5786     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5787                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5788                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5789     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5790
5791     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5792     // source words for the shuffle, to aid later transformations.
5793     bool AllWordsInNewV = true;
5794     bool InOrder[2] = { true, true };
5795     for (unsigned i = 0; i != 8; ++i) {
5796       int idx = MaskVals[i];
5797       if (idx != (int)i)
5798         InOrder[i/4] = false;
5799       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5800         continue;
5801       AllWordsInNewV = false;
5802       break;
5803     }
5804
5805     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5806     if (AllWordsInNewV) {
5807       for (int i = 0; i != 8; ++i) {
5808         int idx = MaskVals[i];
5809         if (idx < 0)
5810           continue;
5811         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5812         if ((idx != i) && idx < 4)
5813           pshufhw = false;
5814         if ((idx != i) && idx > 3)
5815           pshuflw = false;
5816       }
5817       V1 = NewV;
5818       V2Used = false;
5819       BestLoQuad = 0;
5820       BestHiQuad = 1;
5821     }
5822
5823     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5824     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5825     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5826       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5827       unsigned TargetMask = 0;
5828       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5829                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5830       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5831       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5832                              getShufflePSHUFLWImmediate(SVOp);
5833       V1 = NewV.getOperand(0);
5834       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5835     }
5836   }
5837
5838   // If we have SSSE3, and all words of the result are from 1 input vector,
5839   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5840   // is present, fall back to case 4.
5841   if (Subtarget->hasSSSE3()) {
5842     SmallVector<SDValue,16> pshufbMask;
5843
5844     // If we have elements from both input vectors, set the high bit of the
5845     // shuffle mask element to zero out elements that come from V2 in the V1
5846     // mask, and elements that come from V1 in the V2 mask, so that the two
5847     // results can be OR'd together.
5848     bool TwoInputs = V1Used && V2Used;
5849     for (unsigned i = 0; i != 8; ++i) {
5850       int EltIdx = MaskVals[i] * 2;
5851       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5852       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5853       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5854       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5855     }
5856     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5857     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5858                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5859                                  MVT::v16i8, &pshufbMask[0], 16));
5860     if (!TwoInputs)
5861       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5862
5863     // Calculate the shuffle mask for the second input, shuffle it, and
5864     // OR it with the first shuffled input.
5865     pshufbMask.clear();
5866     for (unsigned i = 0; i != 8; ++i) {
5867       int EltIdx = MaskVals[i] * 2;
5868       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5869       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5870       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5871       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5872     }
5873     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5874     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5875                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5876                                  MVT::v16i8, &pshufbMask[0], 16));
5877     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5878     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5879   }
5880
5881   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5882   // and update MaskVals with new element order.
5883   std::bitset<8> InOrder;
5884   if (BestLoQuad >= 0) {
5885     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5886     for (int i = 0; i != 4; ++i) {
5887       int idx = MaskVals[i];
5888       if (idx < 0) {
5889         InOrder.set(i);
5890       } else if ((idx / 4) == BestLoQuad) {
5891         MaskV[i] = idx & 3;
5892         InOrder.set(i);
5893       }
5894     }
5895     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5896                                 &MaskV[0]);
5897
5898     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5899       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5900       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5901                                   NewV.getOperand(0),
5902                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5903     }
5904   }
5905
5906   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5907   // and update MaskVals with the new element order.
5908   if (BestHiQuad >= 0) {
5909     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5910     for (unsigned i = 4; i != 8; ++i) {
5911       int idx = MaskVals[i];
5912       if (idx < 0) {
5913         InOrder.set(i);
5914       } else if ((idx / 4) == BestHiQuad) {
5915         MaskV[i] = (idx & 3) + 4;
5916         InOrder.set(i);
5917       }
5918     }
5919     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5920                                 &MaskV[0]);
5921
5922     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5923       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5924       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5925                                   NewV.getOperand(0),
5926                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5927     }
5928   }
5929
5930   // In case BestHi & BestLo were both -1, which means each quadword has a word
5931   // from each of the four input quadwords, calculate the InOrder bitvector now
5932   // before falling through to the insert/extract cleanup.
5933   if (BestLoQuad == -1 && BestHiQuad == -1) {
5934     NewV = V1;
5935     for (int i = 0; i != 8; ++i)
5936       if (MaskVals[i] < 0 || MaskVals[i] == i)
5937         InOrder.set(i);
5938   }
5939
5940   // The other elements are put in the right place using pextrw and pinsrw.
5941   for (unsigned i = 0; i != 8; ++i) {
5942     if (InOrder[i])
5943       continue;
5944     int EltIdx = MaskVals[i];
5945     if (EltIdx < 0)
5946       continue;
5947     SDValue ExtOp = (EltIdx < 8) ?
5948       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5949                   DAG.getIntPtrConstant(EltIdx)) :
5950       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5951                   DAG.getIntPtrConstant(EltIdx - 8));
5952     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5953                        DAG.getIntPtrConstant(i));
5954   }
5955   return NewV;
5956 }
5957
5958 // v16i8 shuffles - Prefer shuffles in the following order:
5959 // 1. [ssse3] 1 x pshufb
5960 // 2. [ssse3] 2 x pshufb + 1 x por
5961 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5962 static
5963 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5964                                  SelectionDAG &DAG,
5965                                  const X86TargetLowering &TLI) {
5966   SDValue V1 = SVOp->getOperand(0);
5967   SDValue V2 = SVOp->getOperand(1);
5968   DebugLoc dl = SVOp->getDebugLoc();
5969   ArrayRef<int> MaskVals = SVOp->getMask();
5970
5971   // If we have SSSE3, case 1 is generated when all result bytes come from
5972   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5973   // present, fall back to case 3.
5974
5975   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5976   if (TLI.getSubtarget()->hasSSSE3()) {
5977     SmallVector<SDValue,16> pshufbMask;
5978
5979     // If all result elements are from one input vector, then only translate
5980     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5981     //
5982     // Otherwise, we have elements from both input vectors, and must zero out
5983     // elements that come from V2 in the first mask, and V1 in the second mask
5984     // so that we can OR them together.
5985     for (unsigned i = 0; i != 16; ++i) {
5986       int EltIdx = MaskVals[i];
5987       if (EltIdx < 0 || EltIdx >= 16)
5988         EltIdx = 0x80;
5989       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5990     }
5991     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5992                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5993                                  MVT::v16i8, &pshufbMask[0], 16));
5994
5995     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5996     // the 2nd operand if it's undefined or zero.
5997     if (V2.getOpcode() == ISD::UNDEF ||
5998         ISD::isBuildVectorAllZeros(V2.getNode()))
5999       return V1;
6000
6001     // Calculate the shuffle mask for the second input, shuffle it, and
6002     // OR it with the first shuffled input.
6003     pshufbMask.clear();
6004     for (unsigned i = 0; i != 16; ++i) {
6005       int EltIdx = MaskVals[i];
6006       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6007       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6008     }
6009     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6010                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6011                                  MVT::v16i8, &pshufbMask[0], 16));
6012     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6013   }
6014
6015   // No SSSE3 - Calculate in place words and then fix all out of place words
6016   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6017   // the 16 different words that comprise the two doublequadword input vectors.
6018   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6019   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6020   SDValue NewV = V1;
6021   for (int i = 0; i != 8; ++i) {
6022     int Elt0 = MaskVals[i*2];
6023     int Elt1 = MaskVals[i*2+1];
6024
6025     // This word of the result is all undef, skip it.
6026     if (Elt0 < 0 && Elt1 < 0)
6027       continue;
6028
6029     // This word of the result is already in the correct place, skip it.
6030     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6031       continue;
6032
6033     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6034     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6035     SDValue InsElt;
6036
6037     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6038     // using a single extract together, load it and store it.
6039     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6040       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6041                            DAG.getIntPtrConstant(Elt1 / 2));
6042       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6043                         DAG.getIntPtrConstant(i));
6044       continue;
6045     }
6046
6047     // If Elt1 is defined, extract it from the appropriate source.  If the
6048     // source byte is not also odd, shift the extracted word left 8 bits
6049     // otherwise clear the bottom 8 bits if we need to do an or.
6050     if (Elt1 >= 0) {
6051       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6052                            DAG.getIntPtrConstant(Elt1 / 2));
6053       if ((Elt1 & 1) == 0)
6054         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6055                              DAG.getConstant(8,
6056                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6057       else if (Elt0 >= 0)
6058         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6059                              DAG.getConstant(0xFF00, MVT::i16));
6060     }
6061     // If Elt0 is defined, extract it from the appropriate source.  If the
6062     // source byte is not also even, shift the extracted word right 8 bits. If
6063     // Elt1 was also defined, OR the extracted values together before
6064     // inserting them in the result.
6065     if (Elt0 >= 0) {
6066       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6067                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6068       if ((Elt0 & 1) != 0)
6069         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6070                               DAG.getConstant(8,
6071                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6072       else if (Elt1 >= 0)
6073         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6074                              DAG.getConstant(0x00FF, MVT::i16));
6075       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6076                          : InsElt0;
6077     }
6078     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6079                        DAG.getIntPtrConstant(i));
6080   }
6081   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6082 }
6083
6084 // v32i8 shuffles - Translate to VPSHUFB if possible.
6085 static
6086 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6087                                  const X86Subtarget *Subtarget,
6088                                  SelectionDAG &DAG) {
6089   EVT VT = SVOp->getValueType(0);
6090   SDValue V1 = SVOp->getOperand(0);
6091   SDValue V2 = SVOp->getOperand(1);
6092   DebugLoc dl = SVOp->getDebugLoc();
6093   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6094
6095   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6096   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6097   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6098
6099   // VPSHUFB may be generated if
6100   // (1) one of input vector is undefined or zeroinitializer.
6101   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6102   // And (2) the mask indexes don't cross the 128-bit lane.
6103   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6104       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6105     return SDValue();
6106
6107   if (V1IsAllZero && !V2IsAllZero) {
6108     CommuteVectorShuffleMask(MaskVals, 32);
6109     V1 = V2;
6110   }
6111   SmallVector<SDValue, 32> pshufbMask;
6112   for (unsigned i = 0; i != 32; i++) {
6113     int EltIdx = MaskVals[i];
6114     if (EltIdx < 0 || EltIdx >= 32)
6115       EltIdx = 0x80;
6116     else {
6117       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6118         // Cross lane is not allowed.
6119         return SDValue();
6120       EltIdx &= 0xf;
6121     }
6122     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6123   }
6124   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6125                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6126                                   MVT::v32i8, &pshufbMask[0], 32));
6127 }
6128
6129 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6130 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6131 /// done when every pair / quad of shuffle mask elements point to elements in
6132 /// the right sequence. e.g.
6133 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6134 static
6135 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6136                                  SelectionDAG &DAG, DebugLoc dl) {
6137   MVT VT = SVOp->getValueType(0).getSimpleVT();
6138   unsigned NumElems = VT.getVectorNumElements();
6139   MVT NewVT;
6140   unsigned Scale;
6141   switch (VT.SimpleTy) {
6142   default: llvm_unreachable("Unexpected!");
6143   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6144   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6145   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6146   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6147   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6148   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6149   }
6150
6151   SmallVector<int, 8> MaskVec;
6152   for (unsigned i = 0; i != NumElems; i += Scale) {
6153     int StartIdx = -1;
6154     for (unsigned j = 0; j != Scale; ++j) {
6155       int EltIdx = SVOp->getMaskElt(i+j);
6156       if (EltIdx < 0)
6157         continue;
6158       if (StartIdx < 0)
6159         StartIdx = (EltIdx / Scale);
6160       if (EltIdx != (int)(StartIdx*Scale + j))
6161         return SDValue();
6162     }
6163     MaskVec.push_back(StartIdx);
6164   }
6165
6166   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6167   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6168   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6169 }
6170
6171 /// getVZextMovL - Return a zero-extending vector move low node.
6172 ///
6173 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6174                             SDValue SrcOp, SelectionDAG &DAG,
6175                             const X86Subtarget *Subtarget, DebugLoc dl) {
6176   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6177     LoadSDNode *LD = NULL;
6178     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6179       LD = dyn_cast<LoadSDNode>(SrcOp);
6180     if (!LD) {
6181       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6182       // instead.
6183       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6184       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6185           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6186           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6187           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6188         // PR2108
6189         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6190         return DAG.getNode(ISD::BITCAST, dl, VT,
6191                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6192                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6193                                                    OpVT,
6194                                                    SrcOp.getOperand(0)
6195                                                           .getOperand(0))));
6196       }
6197     }
6198   }
6199
6200   return DAG.getNode(ISD::BITCAST, dl, VT,
6201                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6202                                  DAG.getNode(ISD::BITCAST, dl,
6203                                              OpVT, SrcOp)));
6204 }
6205
6206 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6207 /// which could not be matched by any known target speficic shuffle
6208 static SDValue
6209 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6210
6211   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6212   if (NewOp.getNode())
6213     return NewOp;
6214
6215   EVT VT = SVOp->getValueType(0);
6216
6217   unsigned NumElems = VT.getVectorNumElements();
6218   unsigned NumLaneElems = NumElems / 2;
6219
6220   DebugLoc dl = SVOp->getDebugLoc();
6221   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6222   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6223   SDValue Output[2];
6224
6225   SmallVector<int, 16> Mask;
6226   for (unsigned l = 0; l < 2; ++l) {
6227     // Build a shuffle mask for the output, discovering on the fly which
6228     // input vectors to use as shuffle operands (recorded in InputUsed).
6229     // If building a suitable shuffle vector proves too hard, then bail
6230     // out with UseBuildVector set.
6231     bool UseBuildVector = false;
6232     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6233     unsigned LaneStart = l * NumLaneElems;
6234     for (unsigned i = 0; i != NumLaneElems; ++i) {
6235       // The mask element.  This indexes into the input.
6236       int Idx = SVOp->getMaskElt(i+LaneStart);
6237       if (Idx < 0) {
6238         // the mask element does not index into any input vector.
6239         Mask.push_back(-1);
6240         continue;
6241       }
6242
6243       // The input vector this mask element indexes into.
6244       int Input = Idx / NumLaneElems;
6245
6246       // Turn the index into an offset from the start of the input vector.
6247       Idx -= Input * NumLaneElems;
6248
6249       // Find or create a shuffle vector operand to hold this input.
6250       unsigned OpNo;
6251       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6252         if (InputUsed[OpNo] == Input)
6253           // This input vector is already an operand.
6254           break;
6255         if (InputUsed[OpNo] < 0) {
6256           // Create a new operand for this input vector.
6257           InputUsed[OpNo] = Input;
6258           break;
6259         }
6260       }
6261
6262       if (OpNo >= array_lengthof(InputUsed)) {
6263         // More than two input vectors used!  Give up on trying to create a
6264         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6265         UseBuildVector = true;
6266         break;
6267       }
6268
6269       // Add the mask index for the new shuffle vector.
6270       Mask.push_back(Idx + OpNo * NumLaneElems);
6271     }
6272
6273     if (UseBuildVector) {
6274       SmallVector<SDValue, 16> SVOps;
6275       for (unsigned i = 0; i != NumLaneElems; ++i) {
6276         // The mask element.  This indexes into the input.
6277         int Idx = SVOp->getMaskElt(i+LaneStart);
6278         if (Idx < 0) {
6279           SVOps.push_back(DAG.getUNDEF(EltVT));
6280           continue;
6281         }
6282
6283         // The input vector this mask element indexes into.
6284         int Input = Idx / NumElems;
6285
6286         // Turn the index into an offset from the start of the input vector.
6287         Idx -= Input * NumElems;
6288
6289         // Extract the vector element by hand.
6290         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6291                                     SVOp->getOperand(Input),
6292                                     DAG.getIntPtrConstant(Idx)));
6293       }
6294
6295       // Construct the output using a BUILD_VECTOR.
6296       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6297                               SVOps.size());
6298     } else if (InputUsed[0] < 0) {
6299       // No input vectors were used! The result is undefined.
6300       Output[l] = DAG.getUNDEF(NVT);
6301     } else {
6302       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6303                                         (InputUsed[0] % 2) * NumLaneElems,
6304                                         DAG, dl);
6305       // If only one input was used, use an undefined vector for the other.
6306       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6307         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6308                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6309       // At least one input vector was used. Create a new shuffle vector.
6310       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6311     }
6312
6313     Mask.clear();
6314   }
6315
6316   // Concatenate the result back
6317   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6318 }
6319
6320 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6321 /// 4 elements, and match them with several different shuffle types.
6322 static SDValue
6323 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6324   SDValue V1 = SVOp->getOperand(0);
6325   SDValue V2 = SVOp->getOperand(1);
6326   DebugLoc dl = SVOp->getDebugLoc();
6327   EVT VT = SVOp->getValueType(0);
6328
6329   assert(VT.is128BitVector() && "Unsupported vector size");
6330
6331   std::pair<int, int> Locs[4];
6332   int Mask1[] = { -1, -1, -1, -1 };
6333   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6334
6335   unsigned NumHi = 0;
6336   unsigned NumLo = 0;
6337   for (unsigned i = 0; i != 4; ++i) {
6338     int Idx = PermMask[i];
6339     if (Idx < 0) {
6340       Locs[i] = std::make_pair(-1, -1);
6341     } else {
6342       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6343       if (Idx < 4) {
6344         Locs[i] = std::make_pair(0, NumLo);
6345         Mask1[NumLo] = Idx;
6346         NumLo++;
6347       } else {
6348         Locs[i] = std::make_pair(1, NumHi);
6349         if (2+NumHi < 4)
6350           Mask1[2+NumHi] = Idx;
6351         NumHi++;
6352       }
6353     }
6354   }
6355
6356   if (NumLo <= 2 && NumHi <= 2) {
6357     // If no more than two elements come from either vector. This can be
6358     // implemented with two shuffles. First shuffle gather the elements.
6359     // The second shuffle, which takes the first shuffle as both of its
6360     // vector operands, put the elements into the right order.
6361     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6362
6363     int Mask2[] = { -1, -1, -1, -1 };
6364
6365     for (unsigned i = 0; i != 4; ++i)
6366       if (Locs[i].first != -1) {
6367         unsigned Idx = (i < 2) ? 0 : 4;
6368         Idx += Locs[i].first * 2 + Locs[i].second;
6369         Mask2[i] = Idx;
6370       }
6371
6372     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6373   }
6374
6375   if (NumLo == 3 || NumHi == 3) {
6376     // Otherwise, we must have three elements from one vector, call it X, and
6377     // one element from the other, call it Y.  First, use a shufps to build an
6378     // intermediate vector with the one element from Y and the element from X
6379     // that will be in the same half in the final destination (the indexes don't
6380     // matter). Then, use a shufps to build the final vector, taking the half
6381     // containing the element from Y from the intermediate, and the other half
6382     // from X.
6383     if (NumHi == 3) {
6384       // Normalize it so the 3 elements come from V1.
6385       CommuteVectorShuffleMask(PermMask, 4);
6386       std::swap(V1, V2);
6387     }
6388
6389     // Find the element from V2.
6390     unsigned HiIndex;
6391     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6392       int Val = PermMask[HiIndex];
6393       if (Val < 0)
6394         continue;
6395       if (Val >= 4)
6396         break;
6397     }
6398
6399     Mask1[0] = PermMask[HiIndex];
6400     Mask1[1] = -1;
6401     Mask1[2] = PermMask[HiIndex^1];
6402     Mask1[3] = -1;
6403     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6404
6405     if (HiIndex >= 2) {
6406       Mask1[0] = PermMask[0];
6407       Mask1[1] = PermMask[1];
6408       Mask1[2] = HiIndex & 1 ? 6 : 4;
6409       Mask1[3] = HiIndex & 1 ? 4 : 6;
6410       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6411     }
6412
6413     Mask1[0] = HiIndex & 1 ? 2 : 0;
6414     Mask1[1] = HiIndex & 1 ? 0 : 2;
6415     Mask1[2] = PermMask[2];
6416     Mask1[3] = PermMask[3];
6417     if (Mask1[2] >= 0)
6418       Mask1[2] += 4;
6419     if (Mask1[3] >= 0)
6420       Mask1[3] += 4;
6421     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6422   }
6423
6424   // Break it into (shuffle shuffle_hi, shuffle_lo).
6425   int LoMask[] = { -1, -1, -1, -1 };
6426   int HiMask[] = { -1, -1, -1, -1 };
6427
6428   int *MaskPtr = LoMask;
6429   unsigned MaskIdx = 0;
6430   unsigned LoIdx = 0;
6431   unsigned HiIdx = 2;
6432   for (unsigned i = 0; i != 4; ++i) {
6433     if (i == 2) {
6434       MaskPtr = HiMask;
6435       MaskIdx = 1;
6436       LoIdx = 0;
6437       HiIdx = 2;
6438     }
6439     int Idx = PermMask[i];
6440     if (Idx < 0) {
6441       Locs[i] = std::make_pair(-1, -1);
6442     } else if (Idx < 4) {
6443       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6444       MaskPtr[LoIdx] = Idx;
6445       LoIdx++;
6446     } else {
6447       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6448       MaskPtr[HiIdx] = Idx;
6449       HiIdx++;
6450     }
6451   }
6452
6453   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6454   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6455   int MaskOps[] = { -1, -1, -1, -1 };
6456   for (unsigned i = 0; i != 4; ++i)
6457     if (Locs[i].first != -1)
6458       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6459   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6460 }
6461
6462 static bool MayFoldVectorLoad(SDValue V) {
6463   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6464     V = V.getOperand(0);
6465
6466   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6467     V = V.getOperand(0);
6468   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6469       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6470     // BUILD_VECTOR (load), undef
6471     V = V.getOperand(0);
6472
6473   return MayFoldLoad(V);
6474 }
6475
6476 static
6477 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6478   EVT VT = Op.getValueType();
6479
6480   // Canonizalize to v2f64.
6481   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6482   return DAG.getNode(ISD::BITCAST, dl, VT,
6483                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6484                                           V1, DAG));
6485 }
6486
6487 static
6488 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6489                         bool HasSSE2) {
6490   SDValue V1 = Op.getOperand(0);
6491   SDValue V2 = Op.getOperand(1);
6492   EVT VT = Op.getValueType();
6493
6494   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6495
6496   if (HasSSE2 && VT == MVT::v2f64)
6497     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6498
6499   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6500   return DAG.getNode(ISD::BITCAST, dl, VT,
6501                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6502                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6503                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6504 }
6505
6506 static
6507 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6508   SDValue V1 = Op.getOperand(0);
6509   SDValue V2 = Op.getOperand(1);
6510   EVT VT = Op.getValueType();
6511
6512   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6513          "unsupported shuffle type");
6514
6515   if (V2.getOpcode() == ISD::UNDEF)
6516     V2 = V1;
6517
6518   // v4i32 or v4f32
6519   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6520 }
6521
6522 static
6523 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6524   SDValue V1 = Op.getOperand(0);
6525   SDValue V2 = Op.getOperand(1);
6526   EVT VT = Op.getValueType();
6527   unsigned NumElems = VT.getVectorNumElements();
6528
6529   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6530   // operand of these instructions is only memory, so check if there's a
6531   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6532   // same masks.
6533   bool CanFoldLoad = false;
6534
6535   // Trivial case, when V2 comes from a load.
6536   if (MayFoldVectorLoad(V2))
6537     CanFoldLoad = true;
6538
6539   // When V1 is a load, it can be folded later into a store in isel, example:
6540   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6541   //    turns into:
6542   //  (MOVLPSmr addr:$src1, VR128:$src2)
6543   // So, recognize this potential and also use MOVLPS or MOVLPD
6544   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6545     CanFoldLoad = true;
6546
6547   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6548   if (CanFoldLoad) {
6549     if (HasSSE2 && NumElems == 2)
6550       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6551
6552     if (NumElems == 4)
6553       // If we don't care about the second element, proceed to use movss.
6554       if (SVOp->getMaskElt(1) != -1)
6555         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6556   }
6557
6558   // movl and movlp will both match v2i64, but v2i64 is never matched by
6559   // movl earlier because we make it strict to avoid messing with the movlp load
6560   // folding logic (see the code above getMOVLP call). Match it here then,
6561   // this is horrible, but will stay like this until we move all shuffle
6562   // matching to x86 specific nodes. Note that for the 1st condition all
6563   // types are matched with movsd.
6564   if (HasSSE2) {
6565     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6566     // as to remove this logic from here, as much as possible
6567     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6568       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6569     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6570   }
6571
6572   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6573
6574   // Invert the operand order and use SHUFPS to match it.
6575   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6576                               getShuffleSHUFImmediate(SVOp), DAG);
6577 }
6578
6579 // Reduce a vector shuffle to zext.
6580 SDValue
6581 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6582   // PMOVZX is only available from SSE41.
6583   if (!Subtarget->hasSSE41())
6584     return SDValue();
6585
6586   EVT VT = Op.getValueType();
6587
6588   // Only AVX2 support 256-bit vector integer extending.
6589   if (!Subtarget->hasInt256() && VT.is256BitVector())
6590     return SDValue();
6591
6592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6593   DebugLoc DL = Op.getDebugLoc();
6594   SDValue V1 = Op.getOperand(0);
6595   SDValue V2 = Op.getOperand(1);
6596   unsigned NumElems = VT.getVectorNumElements();
6597
6598   // Extending is an unary operation and the element type of the source vector
6599   // won't be equal to or larger than i64.
6600   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6601       VT.getVectorElementType() == MVT::i64)
6602     return SDValue();
6603
6604   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6605   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6606   while ((1U << Shift) < NumElems) {
6607     if (SVOp->getMaskElt(1U << Shift) == 1)
6608       break;
6609     Shift += 1;
6610     // The maximal ratio is 8, i.e. from i8 to i64.
6611     if (Shift > 3)
6612       return SDValue();
6613   }
6614
6615   // Check the shuffle mask.
6616   unsigned Mask = (1U << Shift) - 1;
6617   for (unsigned i = 0; i != NumElems; ++i) {
6618     int EltIdx = SVOp->getMaskElt(i);
6619     if ((i & Mask) != 0 && EltIdx != -1)
6620       return SDValue();
6621     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6622       return SDValue();
6623   }
6624
6625   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6626   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6627   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6628
6629   if (!isTypeLegal(NVT))
6630     return SDValue();
6631
6632   // Simplify the operand as it's prepared to be fed into shuffle.
6633   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6634   if (V1.getOpcode() == ISD::BITCAST &&
6635       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6636       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6637       V1.getOperand(0)
6638         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6639     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6640     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6641     ConstantSDNode *CIdx =
6642       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6643     // If it's foldable, i.e. normal load with single use, we will let code
6644     // selection to fold it. Otherwise, we will short the conversion sequence.
6645     if (CIdx && CIdx->getZExtValue() == 0 &&
6646         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6647       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6648   }
6649
6650   return DAG.getNode(ISD::BITCAST, DL, VT,
6651                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6652 }
6653
6654 SDValue
6655 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6656   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6657   EVT VT = Op.getValueType();
6658   DebugLoc dl = Op.getDebugLoc();
6659   SDValue V1 = Op.getOperand(0);
6660   SDValue V2 = Op.getOperand(1);
6661
6662   if (isZeroShuffle(SVOp))
6663     return getZeroVector(VT, Subtarget, DAG, dl);
6664
6665   // Handle splat operations
6666   if (SVOp->isSplat()) {
6667     unsigned NumElem = VT.getVectorNumElements();
6668     int Size = VT.getSizeInBits();
6669
6670     // Use vbroadcast whenever the splat comes from a foldable load
6671     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6672     if (Broadcast.getNode())
6673       return Broadcast;
6674
6675     // Handle splats by matching through known shuffle masks
6676     if ((Size == 128 && NumElem <= 4) ||
6677         (Size == 256 && NumElem <= 8))
6678       return SDValue();
6679
6680     // All remaning splats are promoted to target supported vector shuffles.
6681     return PromoteSplat(SVOp, DAG);
6682   }
6683
6684   // Check integer expanding shuffles.
6685   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6686   if (NewOp.getNode())
6687     return NewOp;
6688
6689   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6690   // do it!
6691   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6692       VT == MVT::v16i16 || VT == MVT::v32i8) {
6693     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694     if (NewOp.getNode())
6695       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6696   } else if ((VT == MVT::v4i32 ||
6697              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6698     // FIXME: Figure out a cleaner way to do this.
6699     // Try to make use of movq to zero out the top part.
6700     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6701       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6702       if (NewOp.getNode()) {
6703         EVT NewVT = NewOp.getValueType();
6704         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6705                                NewVT, true, false))
6706           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6707                               DAG, Subtarget, dl);
6708       }
6709     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6710       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6711       if (NewOp.getNode()) {
6712         EVT NewVT = NewOp.getValueType();
6713         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6714           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6715                               DAG, Subtarget, dl);
6716       }
6717     }
6718   }
6719   return SDValue();
6720 }
6721
6722 SDValue
6723 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6724   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6725   SDValue V1 = Op.getOperand(0);
6726   SDValue V2 = Op.getOperand(1);
6727   EVT VT = Op.getValueType();
6728   DebugLoc dl = Op.getDebugLoc();
6729   unsigned NumElems = VT.getVectorNumElements();
6730   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6731   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6732   bool V1IsSplat = false;
6733   bool V2IsSplat = false;
6734   bool HasSSE2 = Subtarget->hasSSE2();
6735   bool HasFp256    = Subtarget->hasFp256();
6736   bool HasInt256   = Subtarget->hasInt256();
6737   MachineFunction &MF = DAG.getMachineFunction();
6738   bool OptForSize = MF.getFunction()->getFnAttributes().
6739     hasAttribute(Attribute::OptimizeForSize);
6740
6741   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6742
6743   if (V1IsUndef && V2IsUndef)
6744     return DAG.getUNDEF(VT);
6745
6746   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6747
6748   // Vector shuffle lowering takes 3 steps:
6749   //
6750   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6751   //    narrowing and commutation of operands should be handled.
6752   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6753   //    shuffle nodes.
6754   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6755   //    so the shuffle can be broken into other shuffles and the legalizer can
6756   //    try the lowering again.
6757   //
6758   // The general idea is that no vector_shuffle operation should be left to
6759   // be matched during isel, all of them must be converted to a target specific
6760   // node here.
6761
6762   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6763   // narrowing and commutation of operands should be handled. The actual code
6764   // doesn't include all of those, work in progress...
6765   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6766   if (NewOp.getNode())
6767     return NewOp;
6768
6769   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6770
6771   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6772   // unpckh_undef). Only use pshufd if speed is more important than size.
6773   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6774     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6775   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6776     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6777
6778   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6779       V2IsUndef && MayFoldVectorLoad(V1))
6780     return getMOVDDup(Op, dl, V1, DAG);
6781
6782   if (isMOVHLPS_v_undef_Mask(M, VT))
6783     return getMOVHighToLow(Op, dl, DAG);
6784
6785   // Use to match splats
6786   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6787       (VT == MVT::v2f64 || VT == MVT::v2i64))
6788     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6789
6790   if (isPSHUFDMask(M, VT)) {
6791     // The actual implementation will match the mask in the if above and then
6792     // during isel it can match several different instructions, not only pshufd
6793     // as its name says, sad but true, emulate the behavior for now...
6794     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6795       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6796
6797     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6798
6799     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6800       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6801
6802     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6803       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6804                                   DAG);
6805
6806     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6807                                 TargetMask, DAG);
6808   }
6809
6810   // Check if this can be converted into a logical shift.
6811   bool isLeft = false;
6812   unsigned ShAmt = 0;
6813   SDValue ShVal;
6814   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6815   if (isShift && ShVal.hasOneUse()) {
6816     // If the shifted value has multiple uses, it may be cheaper to use
6817     // v_set0 + movlhps or movhlps, etc.
6818     EVT EltVT = VT.getVectorElementType();
6819     ShAmt *= EltVT.getSizeInBits();
6820     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6821   }
6822
6823   if (isMOVLMask(M, VT)) {
6824     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6825       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6826     if (!isMOVLPMask(M, VT)) {
6827       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6828         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6829
6830       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6831         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6832     }
6833   }
6834
6835   // FIXME: fold these into legal mask.
6836   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6837     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6838
6839   if (isMOVHLPSMask(M, VT))
6840     return getMOVHighToLow(Op, dl, DAG);
6841
6842   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6843     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6844
6845   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6846     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6847
6848   if (isMOVLPMask(M, VT))
6849     return getMOVLP(Op, dl, DAG, HasSSE2);
6850
6851   if (ShouldXformToMOVHLPS(M, VT) ||
6852       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6853     return CommuteVectorShuffle(SVOp, DAG);
6854
6855   if (isShift) {
6856     // No better options. Use a vshldq / vsrldq.
6857     EVT EltVT = VT.getVectorElementType();
6858     ShAmt *= EltVT.getSizeInBits();
6859     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6860   }
6861
6862   bool Commuted = false;
6863   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6864   // 1,1,1,1 -> v8i16 though.
6865   V1IsSplat = isSplatVector(V1.getNode());
6866   V2IsSplat = isSplatVector(V2.getNode());
6867
6868   // Canonicalize the splat or undef, if present, to be on the RHS.
6869   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6870     CommuteVectorShuffleMask(M, NumElems);
6871     std::swap(V1, V2);
6872     std::swap(V1IsSplat, V2IsSplat);
6873     Commuted = true;
6874   }
6875
6876   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6877     // Shuffling low element of v1 into undef, just return v1.
6878     if (V2IsUndef)
6879       return V1;
6880     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6881     // the instruction selector will not match, so get a canonical MOVL with
6882     // swapped operands to undo the commute.
6883     return getMOVL(DAG, dl, VT, V2, V1);
6884   }
6885
6886   if (isUNPCKLMask(M, VT, HasInt256))
6887     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6888
6889   if (isUNPCKHMask(M, VT, HasInt256))
6890     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6891
6892   if (V2IsSplat) {
6893     // Normalize mask so all entries that point to V2 points to its first
6894     // element then try to match unpck{h|l} again. If match, return a
6895     // new vector_shuffle with the corrected mask.p
6896     SmallVector<int, 8> NewMask(M.begin(), M.end());
6897     NormalizeMask(NewMask, NumElems);
6898     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6899       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6900     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6901       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6902   }
6903
6904   if (Commuted) {
6905     // Commute is back and try unpck* again.
6906     // FIXME: this seems wrong.
6907     CommuteVectorShuffleMask(M, NumElems);
6908     std::swap(V1, V2);
6909     std::swap(V1IsSplat, V2IsSplat);
6910     Commuted = false;
6911
6912     if (isUNPCKLMask(M, VT, HasInt256))
6913       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6914
6915     if (isUNPCKHMask(M, VT, HasInt256))
6916       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6917   }
6918
6919   // Normalize the node to match x86 shuffle ops if needed
6920   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6921     return CommuteVectorShuffle(SVOp, DAG);
6922
6923   // The checks below are all present in isShuffleMaskLegal, but they are
6924   // inlined here right now to enable us to directly emit target specific
6925   // nodes, and remove one by one until they don't return Op anymore.
6926
6927   if (isPALIGNRMask(M, VT, Subtarget))
6928     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6929                                 getShufflePALIGNRImmediate(SVOp),
6930                                 DAG);
6931
6932   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6933       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6934     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6935       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6936   }
6937
6938   if (isPSHUFHWMask(M, VT, HasInt256))
6939     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6940                                 getShufflePSHUFHWImmediate(SVOp),
6941                                 DAG);
6942
6943   if (isPSHUFLWMask(M, VT, HasInt256))
6944     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6945                                 getShufflePSHUFLWImmediate(SVOp),
6946                                 DAG);
6947
6948   if (isSHUFPMask(M, VT, HasFp256))
6949     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6950                                 getShuffleSHUFImmediate(SVOp), DAG);
6951
6952   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6953     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6954   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6955     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6956
6957   //===--------------------------------------------------------------------===//
6958   // Generate target specific nodes for 128 or 256-bit shuffles only
6959   // supported in the AVX instruction set.
6960   //
6961
6962   // Handle VMOVDDUPY permutations
6963   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6964     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6965
6966   // Handle VPERMILPS/D* permutations
6967   if (isVPERMILPMask(M, VT, HasFp256)) {
6968     if (HasInt256 && VT == MVT::v8i32)
6969       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6970                                   getShuffleSHUFImmediate(SVOp), DAG);
6971     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6972                                 getShuffleSHUFImmediate(SVOp), DAG);
6973   }
6974
6975   // Handle VPERM2F128/VPERM2I128 permutations
6976   if (isVPERM2X128Mask(M, VT, HasFp256))
6977     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6978                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6979
6980   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6981   if (BlendOp.getNode())
6982     return BlendOp;
6983
6984   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6985     SmallVector<SDValue, 8> permclMask;
6986     for (unsigned i = 0; i != 8; ++i) {
6987       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6988     }
6989     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6990                                &permclMask[0], 8);
6991     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6992     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6993                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6994   }
6995
6996   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6997     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6998                                 getShuffleCLImmediate(SVOp), DAG);
6999
7000   //===--------------------------------------------------------------------===//
7001   // Since no target specific shuffle was selected for this generic one,
7002   // lower it into other known shuffles. FIXME: this isn't true yet, but
7003   // this is the plan.
7004   //
7005
7006   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7007   if (VT == MVT::v8i16) {
7008     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7009     if (NewOp.getNode())
7010       return NewOp;
7011   }
7012
7013   if (VT == MVT::v16i8) {
7014     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7015     if (NewOp.getNode())
7016       return NewOp;
7017   }
7018
7019   if (VT == MVT::v32i8) {
7020     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7021     if (NewOp.getNode())
7022       return NewOp;
7023   }
7024
7025   // Handle all 128-bit wide vectors with 4 elements, and match them with
7026   // several different shuffle types.
7027   if (NumElems == 4 && VT.is128BitVector())
7028     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7029
7030   // Handle general 256-bit shuffles
7031   if (VT.is256BitVector())
7032     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7033
7034   return SDValue();
7035 }
7036
7037 SDValue
7038 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7039                                                 SelectionDAG &DAG) const {
7040   EVT VT = Op.getValueType();
7041   DebugLoc dl = Op.getDebugLoc();
7042
7043   if (!Op.getOperand(0).getValueType().is128BitVector())
7044     return SDValue();
7045
7046   if (VT.getSizeInBits() == 8) {
7047     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7048                                   Op.getOperand(0), Op.getOperand(1));
7049     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7050                                   DAG.getValueType(VT));
7051     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7052   }
7053
7054   if (VT.getSizeInBits() == 16) {
7055     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7056     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7057     if (Idx == 0)
7058       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7059                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7060                                      DAG.getNode(ISD::BITCAST, dl,
7061                                                  MVT::v4i32,
7062                                                  Op.getOperand(0)),
7063                                      Op.getOperand(1)));
7064     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7065                                   Op.getOperand(0), Op.getOperand(1));
7066     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7067                                   DAG.getValueType(VT));
7068     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7069   }
7070
7071   if (VT == MVT::f32) {
7072     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7073     // the result back to FR32 register. It's only worth matching if the
7074     // result has a single use which is a store or a bitcast to i32.  And in
7075     // the case of a store, it's not worth it if the index is a constant 0,
7076     // because a MOVSSmr can be used instead, which is smaller and faster.
7077     if (!Op.hasOneUse())
7078       return SDValue();
7079     SDNode *User = *Op.getNode()->use_begin();
7080     if ((User->getOpcode() != ISD::STORE ||
7081          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7082           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7083         (User->getOpcode() != ISD::BITCAST ||
7084          User->getValueType(0) != MVT::i32))
7085       return SDValue();
7086     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7087                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7088                                               Op.getOperand(0)),
7089                                               Op.getOperand(1));
7090     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7091   }
7092
7093   if (VT == MVT::i32 || VT == MVT::i64) {
7094     // ExtractPS/pextrq works with constant index.
7095     if (isa<ConstantSDNode>(Op.getOperand(1)))
7096       return Op;
7097   }
7098   return SDValue();
7099 }
7100
7101 SDValue
7102 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7103                                            SelectionDAG &DAG) const {
7104   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7105     return SDValue();
7106
7107   SDValue Vec = Op.getOperand(0);
7108   EVT VecVT = Vec.getValueType();
7109
7110   // If this is a 256-bit vector result, first extract the 128-bit vector and
7111   // then extract the element from the 128-bit vector.
7112   if (VecVT.is256BitVector()) {
7113     DebugLoc dl = Op.getNode()->getDebugLoc();
7114     unsigned NumElems = VecVT.getVectorNumElements();
7115     SDValue Idx = Op.getOperand(1);
7116     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7117
7118     // Get the 128-bit vector.
7119     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7120
7121     if (IdxVal >= NumElems/2)
7122       IdxVal -= NumElems/2;
7123     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7124                        DAG.getConstant(IdxVal, MVT::i32));
7125   }
7126
7127   assert(VecVT.is128BitVector() && "Unexpected vector length");
7128
7129   if (Subtarget->hasSSE41()) {
7130     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7131     if (Res.getNode())
7132       return Res;
7133   }
7134
7135   EVT VT = Op.getValueType();
7136   DebugLoc dl = Op.getDebugLoc();
7137   // TODO: handle v16i8.
7138   if (VT.getSizeInBits() == 16) {
7139     SDValue Vec = Op.getOperand(0);
7140     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7141     if (Idx == 0)
7142       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7143                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7144                                      DAG.getNode(ISD::BITCAST, dl,
7145                                                  MVT::v4i32, Vec),
7146                                      Op.getOperand(1)));
7147     // Transform it so it match pextrw which produces a 32-bit result.
7148     EVT EltVT = MVT::i32;
7149     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7150                                   Op.getOperand(0), Op.getOperand(1));
7151     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7152                                   DAG.getValueType(VT));
7153     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7154   }
7155
7156   if (VT.getSizeInBits() == 32) {
7157     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7158     if (Idx == 0)
7159       return Op;
7160
7161     // SHUFPS the element to the lowest double word, then movss.
7162     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7163     EVT VVT = Op.getOperand(0).getValueType();
7164     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7165                                        DAG.getUNDEF(VVT), Mask);
7166     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7167                        DAG.getIntPtrConstant(0));
7168   }
7169
7170   if (VT.getSizeInBits() == 64) {
7171     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7172     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7173     //        to match extract_elt for f64.
7174     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7175     if (Idx == 0)
7176       return Op;
7177
7178     // UNPCKHPD the element to the lowest double word, then movsd.
7179     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7180     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7181     int Mask[2] = { 1, -1 };
7182     EVT VVT = Op.getOperand(0).getValueType();
7183     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7184                                        DAG.getUNDEF(VVT), Mask);
7185     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7186                        DAG.getIntPtrConstant(0));
7187   }
7188
7189   return SDValue();
7190 }
7191
7192 SDValue
7193 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7194                                                SelectionDAG &DAG) const {
7195   EVT VT = Op.getValueType();
7196   EVT EltVT = VT.getVectorElementType();
7197   DebugLoc dl = Op.getDebugLoc();
7198
7199   SDValue N0 = Op.getOperand(0);
7200   SDValue N1 = Op.getOperand(1);
7201   SDValue N2 = Op.getOperand(2);
7202
7203   if (!VT.is128BitVector())
7204     return SDValue();
7205
7206   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7207       isa<ConstantSDNode>(N2)) {
7208     unsigned Opc;
7209     if (VT == MVT::v8i16)
7210       Opc = X86ISD::PINSRW;
7211     else if (VT == MVT::v16i8)
7212       Opc = X86ISD::PINSRB;
7213     else
7214       Opc = X86ISD::PINSRB;
7215
7216     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7217     // argument.
7218     if (N1.getValueType() != MVT::i32)
7219       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7220     if (N2.getValueType() != MVT::i32)
7221       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7222     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7223   }
7224
7225   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7226     // Bits [7:6] of the constant are the source select.  This will always be
7227     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7228     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7229     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7230     // Bits [5:4] of the constant are the destination select.  This is the
7231     //  value of the incoming immediate.
7232     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7233     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7234     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7235     // Create this as a scalar to vector..
7236     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7237     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7238   }
7239
7240   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7241     // PINSR* works with constant index.
7242     return Op;
7243   }
7244   return SDValue();
7245 }
7246
7247 SDValue
7248 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7249   EVT VT = Op.getValueType();
7250   EVT EltVT = VT.getVectorElementType();
7251
7252   DebugLoc dl = Op.getDebugLoc();
7253   SDValue N0 = Op.getOperand(0);
7254   SDValue N1 = Op.getOperand(1);
7255   SDValue N2 = Op.getOperand(2);
7256
7257   // If this is a 256-bit vector result, first extract the 128-bit vector,
7258   // insert the element into the extracted half and then place it back.
7259   if (VT.is256BitVector()) {
7260     if (!isa<ConstantSDNode>(N2))
7261       return SDValue();
7262
7263     // Get the desired 128-bit vector half.
7264     unsigned NumElems = VT.getVectorNumElements();
7265     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7266     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7267
7268     // Insert the element into the desired half.
7269     bool Upper = IdxVal >= NumElems/2;
7270     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7271                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7272
7273     // Insert the changed part back to the 256-bit vector
7274     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7275   }
7276
7277   if (Subtarget->hasSSE41())
7278     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7279
7280   if (EltVT == MVT::i8)
7281     return SDValue();
7282
7283   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7284     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7285     // as its second argument.
7286     if (N1.getValueType() != MVT::i32)
7287       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7288     if (N2.getValueType() != MVT::i32)
7289       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7290     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7291   }
7292   return SDValue();
7293 }
7294
7295 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7296   LLVMContext *Context = DAG.getContext();
7297   DebugLoc dl = Op.getDebugLoc();
7298   EVT OpVT = Op.getValueType();
7299
7300   // If this is a 256-bit vector result, first insert into a 128-bit
7301   // vector and then insert into the 256-bit vector.
7302   if (!OpVT.is128BitVector()) {
7303     // Insert into a 128-bit vector.
7304     EVT VT128 = EVT::getVectorVT(*Context,
7305                                  OpVT.getVectorElementType(),
7306                                  OpVT.getVectorNumElements() / 2);
7307
7308     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7309
7310     // Insert the 128-bit vector.
7311     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7312   }
7313
7314   if (OpVT == MVT::v1i64 &&
7315       Op.getOperand(0).getValueType() == MVT::i64)
7316     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7317
7318   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7319   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7320   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7321                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7322 }
7323
7324 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7325 // a simple subregister reference or explicit instructions to grab
7326 // upper bits of a vector.
7327 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7328                                       SelectionDAG &DAG) {
7329   if (Subtarget->hasFp256()) {
7330     DebugLoc dl = Op.getNode()->getDebugLoc();
7331     SDValue Vec = Op.getNode()->getOperand(0);
7332     SDValue Idx = Op.getNode()->getOperand(1);
7333
7334     if (Op.getNode()->getValueType(0).is128BitVector() &&
7335         Vec.getNode()->getValueType(0).is256BitVector() &&
7336         isa<ConstantSDNode>(Idx)) {
7337       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7338       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7339     }
7340   }
7341   return SDValue();
7342 }
7343
7344 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7345 // simple superregister reference or explicit instructions to insert
7346 // the upper bits of a vector.
7347 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7348                                      SelectionDAG &DAG) {
7349   if (Subtarget->hasFp256()) {
7350     DebugLoc dl = Op.getNode()->getDebugLoc();
7351     SDValue Vec = Op.getNode()->getOperand(0);
7352     SDValue SubVec = Op.getNode()->getOperand(1);
7353     SDValue Idx = Op.getNode()->getOperand(2);
7354
7355     if (Op.getNode()->getValueType(0).is256BitVector() &&
7356         SubVec.getNode()->getValueType(0).is128BitVector() &&
7357         isa<ConstantSDNode>(Idx)) {
7358       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7359       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7360     }
7361   }
7362   return SDValue();
7363 }
7364
7365 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7366 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7367 // one of the above mentioned nodes. It has to be wrapped because otherwise
7368 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7369 // be used to form addressing mode. These wrapped nodes will be selected
7370 // into MOV32ri.
7371 SDValue
7372 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7373   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7374
7375   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7376   // global base reg.
7377   unsigned char OpFlag = 0;
7378   unsigned WrapperKind = X86ISD::Wrapper;
7379   CodeModel::Model M = getTargetMachine().getCodeModel();
7380
7381   if (Subtarget->isPICStyleRIPRel() &&
7382       (M == CodeModel::Small || M == CodeModel::Kernel))
7383     WrapperKind = X86ISD::WrapperRIP;
7384   else if (Subtarget->isPICStyleGOT())
7385     OpFlag = X86II::MO_GOTOFF;
7386   else if (Subtarget->isPICStyleStubPIC())
7387     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7388
7389   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7390                                              CP->getAlignment(),
7391                                              CP->getOffset(), OpFlag);
7392   DebugLoc DL = CP->getDebugLoc();
7393   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7394   // With PIC, the address is actually $g + Offset.
7395   if (OpFlag) {
7396     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7397                          DAG.getNode(X86ISD::GlobalBaseReg,
7398                                      DebugLoc(), getPointerTy()),
7399                          Result);
7400   }
7401
7402   return Result;
7403 }
7404
7405 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7406   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7407
7408   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7409   // global base reg.
7410   unsigned char OpFlag = 0;
7411   unsigned WrapperKind = X86ISD::Wrapper;
7412   CodeModel::Model M = getTargetMachine().getCodeModel();
7413
7414   if (Subtarget->isPICStyleRIPRel() &&
7415       (M == CodeModel::Small || M == CodeModel::Kernel))
7416     WrapperKind = X86ISD::WrapperRIP;
7417   else if (Subtarget->isPICStyleGOT())
7418     OpFlag = X86II::MO_GOTOFF;
7419   else if (Subtarget->isPICStyleStubPIC())
7420     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7421
7422   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7423                                           OpFlag);
7424   DebugLoc DL = JT->getDebugLoc();
7425   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7426
7427   // With PIC, the address is actually $g + Offset.
7428   if (OpFlag)
7429     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7430                          DAG.getNode(X86ISD::GlobalBaseReg,
7431                                      DebugLoc(), getPointerTy()),
7432                          Result);
7433
7434   return Result;
7435 }
7436
7437 SDValue
7438 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7439   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7440
7441   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7442   // global base reg.
7443   unsigned char OpFlag = 0;
7444   unsigned WrapperKind = X86ISD::Wrapper;
7445   CodeModel::Model M = getTargetMachine().getCodeModel();
7446
7447   if (Subtarget->isPICStyleRIPRel() &&
7448       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7449     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7450       OpFlag = X86II::MO_GOTPCREL;
7451     WrapperKind = X86ISD::WrapperRIP;
7452   } else if (Subtarget->isPICStyleGOT()) {
7453     OpFlag = X86II::MO_GOT;
7454   } else if (Subtarget->isPICStyleStubPIC()) {
7455     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7456   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7457     OpFlag = X86II::MO_DARWIN_NONLAZY;
7458   }
7459
7460   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7461
7462   DebugLoc DL = Op.getDebugLoc();
7463   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7464
7465   // With PIC, the address is actually $g + Offset.
7466   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7467       !Subtarget->is64Bit()) {
7468     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7469                          DAG.getNode(X86ISD::GlobalBaseReg,
7470                                      DebugLoc(), getPointerTy()),
7471                          Result);
7472   }
7473
7474   // For symbols that require a load from a stub to get the address, emit the
7475   // load.
7476   if (isGlobalStubReference(OpFlag))
7477     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7478                          MachinePointerInfo::getGOT(), false, false, false, 0);
7479
7480   return Result;
7481 }
7482
7483 SDValue
7484 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7485   // Create the TargetBlockAddressAddress node.
7486   unsigned char OpFlags =
7487     Subtarget->ClassifyBlockAddressReference();
7488   CodeModel::Model M = getTargetMachine().getCodeModel();
7489   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7490   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7491   DebugLoc dl = Op.getDebugLoc();
7492   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7493                                              OpFlags);
7494
7495   if (Subtarget->isPICStyleRIPRel() &&
7496       (M == CodeModel::Small || M == CodeModel::Kernel))
7497     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7498   else
7499     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7500
7501   // With PIC, the address is actually $g + Offset.
7502   if (isGlobalRelativeToPICBase(OpFlags)) {
7503     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7504                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7505                          Result);
7506   }
7507
7508   return Result;
7509 }
7510
7511 SDValue
7512 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7513                                       int64_t Offset,
7514                                       SelectionDAG &DAG) const {
7515   // Create the TargetGlobalAddress node, folding in the constant
7516   // offset if it is legal.
7517   unsigned char OpFlags =
7518     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7519   CodeModel::Model M = getTargetMachine().getCodeModel();
7520   SDValue Result;
7521   if (OpFlags == X86II::MO_NO_FLAG &&
7522       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7523     // A direct static reference to a global.
7524     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7525     Offset = 0;
7526   } else {
7527     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7528   }
7529
7530   if (Subtarget->isPICStyleRIPRel() &&
7531       (M == CodeModel::Small || M == CodeModel::Kernel))
7532     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7533   else
7534     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7535
7536   // With PIC, the address is actually $g + Offset.
7537   if (isGlobalRelativeToPICBase(OpFlags)) {
7538     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7539                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7540                          Result);
7541   }
7542
7543   // For globals that require a load from a stub to get the address, emit the
7544   // load.
7545   if (isGlobalStubReference(OpFlags))
7546     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7547                          MachinePointerInfo::getGOT(), false, false, false, 0);
7548
7549   // If there was a non-zero offset that we didn't fold, create an explicit
7550   // addition for it.
7551   if (Offset != 0)
7552     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7553                          DAG.getConstant(Offset, getPointerTy()));
7554
7555   return Result;
7556 }
7557
7558 SDValue
7559 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7560   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7561   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7562   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7563 }
7564
7565 static SDValue
7566 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7567            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7568            unsigned char OperandFlags, bool LocalDynamic = false) {
7569   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7570   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7571   DebugLoc dl = GA->getDebugLoc();
7572   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7573                                            GA->getValueType(0),
7574                                            GA->getOffset(),
7575                                            OperandFlags);
7576
7577   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7578                                            : X86ISD::TLSADDR;
7579
7580   if (InFlag) {
7581     SDValue Ops[] = { Chain,  TGA, *InFlag };
7582     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7583   } else {
7584     SDValue Ops[]  = { Chain, TGA };
7585     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7586   }
7587
7588   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7589   MFI->setAdjustsStack(true);
7590
7591   SDValue Flag = Chain.getValue(1);
7592   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7593 }
7594
7595 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7596 static SDValue
7597 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7598                                 const EVT PtrVT) {
7599   SDValue InFlag;
7600   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7601   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7602                                    DAG.getNode(X86ISD::GlobalBaseReg,
7603                                                DebugLoc(), PtrVT), InFlag);
7604   InFlag = Chain.getValue(1);
7605
7606   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7607 }
7608
7609 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7610 static SDValue
7611 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7612                                 const EVT PtrVT) {
7613   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7614                     X86::RAX, X86II::MO_TLSGD);
7615 }
7616
7617 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7618                                            SelectionDAG &DAG,
7619                                            const EVT PtrVT,
7620                                            bool is64Bit) {
7621   DebugLoc dl = GA->getDebugLoc();
7622
7623   // Get the start address of the TLS block for this module.
7624   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7625       .getInfo<X86MachineFunctionInfo>();
7626   MFI->incNumLocalDynamicTLSAccesses();
7627
7628   SDValue Base;
7629   if (is64Bit) {
7630     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7631                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7632   } else {
7633     SDValue InFlag;
7634     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7635         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7636     InFlag = Chain.getValue(1);
7637     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7638                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7639   }
7640
7641   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7642   // of Base.
7643
7644   // Build x@dtpoff.
7645   unsigned char OperandFlags = X86II::MO_DTPOFF;
7646   unsigned WrapperKind = X86ISD::Wrapper;
7647   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7648                                            GA->getValueType(0),
7649                                            GA->getOffset(), OperandFlags);
7650   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7651
7652   // Add x@dtpoff with the base.
7653   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7654 }
7655
7656 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7657 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7658                                    const EVT PtrVT, TLSModel::Model model,
7659                                    bool is64Bit, bool isPIC) {
7660   DebugLoc dl = GA->getDebugLoc();
7661
7662   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7663   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7664                                                          is64Bit ? 257 : 256));
7665
7666   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7667                                       DAG.getIntPtrConstant(0),
7668                                       MachinePointerInfo(Ptr),
7669                                       false, false, false, 0);
7670
7671   unsigned char OperandFlags = 0;
7672   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7673   // initialexec.
7674   unsigned WrapperKind = X86ISD::Wrapper;
7675   if (model == TLSModel::LocalExec) {
7676     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7677   } else if (model == TLSModel::InitialExec) {
7678     if (is64Bit) {
7679       OperandFlags = X86II::MO_GOTTPOFF;
7680       WrapperKind = X86ISD::WrapperRIP;
7681     } else {
7682       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7683     }
7684   } else {
7685     llvm_unreachable("Unexpected model");
7686   }
7687
7688   // emit "addl x@ntpoff,%eax" (local exec)
7689   // or "addl x@indntpoff,%eax" (initial exec)
7690   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7691   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7692                                            GA->getValueType(0),
7693                                            GA->getOffset(), OperandFlags);
7694   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7695
7696   if (model == TLSModel::InitialExec) {
7697     if (isPIC && !is64Bit) {
7698       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7699                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7700                            Offset);
7701     }
7702
7703     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7704                          MachinePointerInfo::getGOT(), false, false, false,
7705                          0);
7706   }
7707
7708   // The address of the thread local variable is the add of the thread
7709   // pointer with the offset of the variable.
7710   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7711 }
7712
7713 SDValue
7714 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7715
7716   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7717   const GlobalValue *GV = GA->getGlobal();
7718
7719   if (Subtarget->isTargetELF()) {
7720     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7721
7722     switch (model) {
7723       case TLSModel::GeneralDynamic:
7724         if (Subtarget->is64Bit())
7725           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7726         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7727       case TLSModel::LocalDynamic:
7728         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7729                                            Subtarget->is64Bit());
7730       case TLSModel::InitialExec:
7731       case TLSModel::LocalExec:
7732         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7733                                    Subtarget->is64Bit(),
7734                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7735     }
7736     llvm_unreachable("Unknown TLS model.");
7737   }
7738
7739   if (Subtarget->isTargetDarwin()) {
7740     // Darwin only has one model of TLS.  Lower to that.
7741     unsigned char OpFlag = 0;
7742     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7743                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7744
7745     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7746     // global base reg.
7747     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7748                   !Subtarget->is64Bit();
7749     if (PIC32)
7750       OpFlag = X86II::MO_TLVP_PIC_BASE;
7751     else
7752       OpFlag = X86II::MO_TLVP;
7753     DebugLoc DL = Op.getDebugLoc();
7754     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7755                                                 GA->getValueType(0),
7756                                                 GA->getOffset(), OpFlag);
7757     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7758
7759     // With PIC32, the address is actually $g + Offset.
7760     if (PIC32)
7761       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7762                            DAG.getNode(X86ISD::GlobalBaseReg,
7763                                        DebugLoc(), getPointerTy()),
7764                            Offset);
7765
7766     // Lowering the machine isd will make sure everything is in the right
7767     // location.
7768     SDValue Chain = DAG.getEntryNode();
7769     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7770     SDValue Args[] = { Chain, Offset };
7771     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7772
7773     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7774     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7775     MFI->setAdjustsStack(true);
7776
7777     // And our return value (tls address) is in the standard call return value
7778     // location.
7779     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7780     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7781                               Chain.getValue(1));
7782   }
7783
7784   if (Subtarget->isTargetWindows()) {
7785     // Just use the implicit TLS architecture
7786     // Need to generate someting similar to:
7787     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7788     //                                  ; from TEB
7789     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7790     //   mov     rcx, qword [rdx+rcx*8]
7791     //   mov     eax, .tls$:tlsvar
7792     //   [rax+rcx] contains the address
7793     // Windows 64bit: gs:0x58
7794     // Windows 32bit: fs:__tls_array
7795
7796     // If GV is an alias then use the aliasee for determining
7797     // thread-localness.
7798     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7799       GV = GA->resolveAliasedGlobal(false);
7800     DebugLoc dl = GA->getDebugLoc();
7801     SDValue Chain = DAG.getEntryNode();
7802
7803     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7804     // %gs:0x58 (64-bit).
7805     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7806                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7807                                                              256)
7808                                         : Type::getInt32PtrTy(*DAG.getContext(),
7809                                                               257));
7810
7811     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7812                                         Subtarget->is64Bit()
7813                                         ? DAG.getIntPtrConstant(0x58)
7814                                         : DAG.getExternalSymbol("_tls_array",
7815                                                                 getPointerTy()),
7816                                         MachinePointerInfo(Ptr),
7817                                         false, false, false, 0);
7818
7819     // Load the _tls_index variable
7820     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7821     if (Subtarget->is64Bit())
7822       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7823                            IDX, MachinePointerInfo(), MVT::i32,
7824                            false, false, 0);
7825     else
7826       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7827                         false, false, false, 0);
7828
7829     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7830                                     getPointerTy());
7831     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7832
7833     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7834     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7835                       false, false, false, 0);
7836
7837     // Get the offset of start of .tls section
7838     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7839                                              GA->getValueType(0),
7840                                              GA->getOffset(), X86II::MO_SECREL);
7841     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7842
7843     // The address of the thread local variable is the add of the thread
7844     // pointer with the offset of the variable.
7845     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7846   }
7847
7848   llvm_unreachable("TLS not implemented for this target.");
7849 }
7850
7851 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7852 /// and take a 2 x i32 value to shift plus a shift amount.
7853 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7854   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7855   EVT VT = Op.getValueType();
7856   unsigned VTBits = VT.getSizeInBits();
7857   DebugLoc dl = Op.getDebugLoc();
7858   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7859   SDValue ShOpLo = Op.getOperand(0);
7860   SDValue ShOpHi = Op.getOperand(1);
7861   SDValue ShAmt  = Op.getOperand(2);
7862   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7863                                      DAG.getConstant(VTBits - 1, MVT::i8))
7864                        : DAG.getConstant(0, VT);
7865
7866   SDValue Tmp2, Tmp3;
7867   if (Op.getOpcode() == ISD::SHL_PARTS) {
7868     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7869     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7870   } else {
7871     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7872     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7873   }
7874
7875   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7876                                 DAG.getConstant(VTBits, MVT::i8));
7877   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7878                              AndNode, DAG.getConstant(0, MVT::i8));
7879
7880   SDValue Hi, Lo;
7881   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7882   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7883   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7884
7885   if (Op.getOpcode() == ISD::SHL_PARTS) {
7886     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7887     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7888   } else {
7889     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7890     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7891   }
7892
7893   SDValue Ops[2] = { Lo, Hi };
7894   return DAG.getMergeValues(Ops, 2, dl);
7895 }
7896
7897 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7898                                            SelectionDAG &DAG) const {
7899   EVT SrcVT = Op.getOperand(0).getValueType();
7900
7901   if (SrcVT.isVector())
7902     return SDValue();
7903
7904   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7905          "Unknown SINT_TO_FP to lower!");
7906
7907   // These are really Legal; return the operand so the caller accepts it as
7908   // Legal.
7909   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7910     return Op;
7911   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7912       Subtarget->is64Bit()) {
7913     return Op;
7914   }
7915
7916   DebugLoc dl = Op.getDebugLoc();
7917   unsigned Size = SrcVT.getSizeInBits()/8;
7918   MachineFunction &MF = DAG.getMachineFunction();
7919   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7920   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7921   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7922                                StackSlot,
7923                                MachinePointerInfo::getFixedStack(SSFI),
7924                                false, false, 0);
7925   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7926 }
7927
7928 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7929                                      SDValue StackSlot,
7930                                      SelectionDAG &DAG) const {
7931   // Build the FILD
7932   DebugLoc DL = Op.getDebugLoc();
7933   SDVTList Tys;
7934   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7935   if (useSSE)
7936     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7937   else
7938     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7939
7940   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7941
7942   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7943   MachineMemOperand *MMO;
7944   if (FI) {
7945     int SSFI = FI->getIndex();
7946     MMO =
7947       DAG.getMachineFunction()
7948       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7949                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7950   } else {
7951     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7952     StackSlot = StackSlot.getOperand(1);
7953   }
7954   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7955   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7956                                            X86ISD::FILD, DL,
7957                                            Tys, Ops, array_lengthof(Ops),
7958                                            SrcVT, MMO);
7959
7960   if (useSSE) {
7961     Chain = Result.getValue(1);
7962     SDValue InFlag = Result.getValue(2);
7963
7964     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7965     // shouldn't be necessary except that RFP cannot be live across
7966     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7967     MachineFunction &MF = DAG.getMachineFunction();
7968     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7969     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7970     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7971     Tys = DAG.getVTList(MVT::Other);
7972     SDValue Ops[] = {
7973       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7974     };
7975     MachineMemOperand *MMO =
7976       DAG.getMachineFunction()
7977       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7978                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7979
7980     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7981                                     Ops, array_lengthof(Ops),
7982                                     Op.getValueType(), MMO);
7983     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7984                          MachinePointerInfo::getFixedStack(SSFI),
7985                          false, false, false, 0);
7986   }
7987
7988   return Result;
7989 }
7990
7991 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7992 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7993                                                SelectionDAG &DAG) const {
7994   // This algorithm is not obvious. Here it is what we're trying to output:
7995   /*
7996      movq       %rax,  %xmm0
7997      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7998      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7999      #ifdef __SSE3__
8000        haddpd   %xmm0, %xmm0
8001      #else
8002        pshufd   $0x4e, %xmm0, %xmm1
8003        addpd    %xmm1, %xmm0
8004      #endif
8005   */
8006
8007   DebugLoc dl = Op.getDebugLoc();
8008   LLVMContext *Context = DAG.getContext();
8009
8010   // Build some magic constants.
8011   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8012   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8013   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8014
8015   SmallVector<Constant*,2> CV1;
8016   CV1.push_back(
8017         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8018   CV1.push_back(
8019         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8020   Constant *C1 = ConstantVector::get(CV1);
8021   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8022
8023   // Load the 64-bit value into an XMM register.
8024   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8025                             Op.getOperand(0));
8026   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8027                               MachinePointerInfo::getConstantPool(),
8028                               false, false, false, 16);
8029   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8030                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8031                               CLod0);
8032
8033   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8034                               MachinePointerInfo::getConstantPool(),
8035                               false, false, false, 16);
8036   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8037   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8038   SDValue Result;
8039
8040   if (Subtarget->hasSSE3()) {
8041     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8042     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8043   } else {
8044     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8045     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8046                                            S2F, 0x4E, DAG);
8047     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8048                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8049                          Sub);
8050   }
8051
8052   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8053                      DAG.getIntPtrConstant(0));
8054 }
8055
8056 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8057 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8058                                                SelectionDAG &DAG) const {
8059   DebugLoc dl = Op.getDebugLoc();
8060   // FP constant to bias correct the final result.
8061   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8062                                    MVT::f64);
8063
8064   // Load the 32-bit value into an XMM register.
8065   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8066                              Op.getOperand(0));
8067
8068   // Zero out the upper parts of the register.
8069   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8070
8071   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8072                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8073                      DAG.getIntPtrConstant(0));
8074
8075   // Or the load with the bias.
8076   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8077                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8078                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8079                                                    MVT::v2f64, Load)),
8080                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8081                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8082                                                    MVT::v2f64, Bias)));
8083   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8084                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8085                    DAG.getIntPtrConstant(0));
8086
8087   // Subtract the bias.
8088   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8089
8090   // Handle final rounding.
8091   EVT DestVT = Op.getValueType();
8092
8093   if (DestVT.bitsLT(MVT::f64))
8094     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8095                        DAG.getIntPtrConstant(0));
8096   if (DestVT.bitsGT(MVT::f64))
8097     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8098
8099   // Handle final rounding.
8100   return Sub;
8101 }
8102
8103 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8104                                                SelectionDAG &DAG) const {
8105   SDValue N0 = Op.getOperand(0);
8106   EVT SVT = N0.getValueType();
8107   DebugLoc dl = Op.getDebugLoc();
8108
8109   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8110           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8111          "Custom UINT_TO_FP is not supported!");
8112
8113   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8114   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8115                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8116 }
8117
8118 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8119                                            SelectionDAG &DAG) const {
8120   SDValue N0 = Op.getOperand(0);
8121   DebugLoc dl = Op.getDebugLoc();
8122
8123   if (Op.getValueType().isVector())
8124     return lowerUINT_TO_FP_vec(Op, DAG);
8125
8126   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8127   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8128   // the optimization here.
8129   if (DAG.SignBitIsZero(N0))
8130     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8131
8132   EVT SrcVT = N0.getValueType();
8133   EVT DstVT = Op.getValueType();
8134   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8135     return LowerUINT_TO_FP_i64(Op, DAG);
8136   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8137     return LowerUINT_TO_FP_i32(Op, DAG);
8138   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8139     return SDValue();
8140
8141   // Make a 64-bit buffer, and use it to build an FILD.
8142   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8143   if (SrcVT == MVT::i32) {
8144     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8145     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8146                                      getPointerTy(), StackSlot, WordOff);
8147     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8148                                   StackSlot, MachinePointerInfo(),
8149                                   false, false, 0);
8150     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8151                                   OffsetSlot, MachinePointerInfo(),
8152                                   false, false, 0);
8153     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8154     return Fild;
8155   }
8156
8157   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8158   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8159                                StackSlot, MachinePointerInfo(),
8160                                false, false, 0);
8161   // For i64 source, we need to add the appropriate power of 2 if the input
8162   // was negative.  This is the same as the optimization in
8163   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8164   // we must be careful to do the computation in x87 extended precision, not
8165   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8166   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8167   MachineMemOperand *MMO =
8168     DAG.getMachineFunction()
8169     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8170                           MachineMemOperand::MOLoad, 8, 8);
8171
8172   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8173   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8174   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8175                                          MVT::i64, MMO);
8176
8177   APInt FF(32, 0x5F800000ULL);
8178
8179   // Check whether the sign bit is set.
8180   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8181                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8182                                  ISD::SETLT);
8183
8184   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8185   SDValue FudgePtr = DAG.getConstantPool(
8186                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8187                                          getPointerTy());
8188
8189   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8190   SDValue Zero = DAG.getIntPtrConstant(0);
8191   SDValue Four = DAG.getIntPtrConstant(4);
8192   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8193                                Zero, Four);
8194   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8195
8196   // Load the value out, extending it from f32 to f80.
8197   // FIXME: Avoid the extend by constructing the right constant pool?
8198   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8199                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8200                                  MVT::f32, false, false, 4);
8201   // Extend everything to 80 bits to force it to be done on x87.
8202   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8203   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8204 }
8205
8206 std::pair<SDValue,SDValue> X86TargetLowering::
8207 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8208   DebugLoc DL = Op.getDebugLoc();
8209
8210   EVT DstTy = Op.getValueType();
8211
8212   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8213     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8214     DstTy = MVT::i64;
8215   }
8216
8217   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8218          DstTy.getSimpleVT() >= MVT::i16 &&
8219          "Unknown FP_TO_INT to lower!");
8220
8221   // These are really Legal.
8222   if (DstTy == MVT::i32 &&
8223       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8224     return std::make_pair(SDValue(), SDValue());
8225   if (Subtarget->is64Bit() &&
8226       DstTy == MVT::i64 &&
8227       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8228     return std::make_pair(SDValue(), SDValue());
8229
8230   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8231   // stack slot, or into the FTOL runtime function.
8232   MachineFunction &MF = DAG.getMachineFunction();
8233   unsigned MemSize = DstTy.getSizeInBits()/8;
8234   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8235   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8236
8237   unsigned Opc;
8238   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8239     Opc = X86ISD::WIN_FTOL;
8240   else
8241     switch (DstTy.getSimpleVT().SimpleTy) {
8242     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8243     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8244     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8245     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8246     }
8247
8248   SDValue Chain = DAG.getEntryNode();
8249   SDValue Value = Op.getOperand(0);
8250   EVT TheVT = Op.getOperand(0).getValueType();
8251   // FIXME This causes a redundant load/store if the SSE-class value is already
8252   // in memory, such as if it is on the callstack.
8253   if (isScalarFPTypeInSSEReg(TheVT)) {
8254     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8255     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8256                          MachinePointerInfo::getFixedStack(SSFI),
8257                          false, false, 0);
8258     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8259     SDValue Ops[] = {
8260       Chain, StackSlot, DAG.getValueType(TheVT)
8261     };
8262
8263     MachineMemOperand *MMO =
8264       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8265                               MachineMemOperand::MOLoad, MemSize, MemSize);
8266     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8267                                     DstTy, MMO);
8268     Chain = Value.getValue(1);
8269     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8270     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8271   }
8272
8273   MachineMemOperand *MMO =
8274     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8275                             MachineMemOperand::MOStore, MemSize, MemSize);
8276
8277   if (Opc != X86ISD::WIN_FTOL) {
8278     // Build the FP_TO_INT*_IN_MEM
8279     SDValue Ops[] = { Chain, Value, StackSlot };
8280     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8281                                            Ops, 3, DstTy, MMO);
8282     return std::make_pair(FIST, StackSlot);
8283   } else {
8284     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8285       DAG.getVTList(MVT::Other, MVT::Glue),
8286       Chain, Value);
8287     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8288       MVT::i32, ftol.getValue(1));
8289     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8290       MVT::i32, eax.getValue(2));
8291     SDValue Ops[] = { eax, edx };
8292     SDValue pair = IsReplace
8293       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8294       : DAG.getMergeValues(Ops, 2, DL);
8295     return std::make_pair(pair, SDValue());
8296   }
8297 }
8298
8299 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8300                               const X86Subtarget *Subtarget) {
8301   EVT VT = Op->getValueType(0);
8302   SDValue In = Op->getOperand(0);
8303   EVT InVT = In.getValueType();
8304   DebugLoc dl = Op->getDebugLoc();
8305
8306   // Optimize vectors in AVX mode:
8307   //
8308   //   v8i16 -> v8i32
8309   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8310   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8311   //   Concat upper and lower parts.
8312   //
8313   //   v4i32 -> v4i64
8314   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8315   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8316   //   Concat upper and lower parts.
8317   //
8318
8319   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8320       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8321     return SDValue();
8322
8323   if (Subtarget->hasInt256())
8324     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8325
8326   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8327   SDValue Undef = DAG.getUNDEF(InVT);
8328   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8329   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8330   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8331
8332   EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8333                              VT.getVectorNumElements()/2);
8334
8335   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8336   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8337
8338   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8339 }
8340
8341 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8342                                            SelectionDAG &DAG) const {
8343   if (Subtarget->hasFp256()) {
8344     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8345     if (Res.getNode())
8346       return Res;
8347   }
8348
8349   return SDValue();
8350 }
8351 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8352                                             SelectionDAG &DAG) const {
8353   DebugLoc DL = Op.getDebugLoc();
8354   EVT VT = Op.getValueType();
8355   SDValue In = Op.getOperand(0);
8356   EVT SVT = In.getValueType();
8357
8358   if (Subtarget->hasFp256()) {
8359     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8360     if (Res.getNode())
8361       return Res;
8362   }
8363
8364   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8365       VT.getVectorNumElements() != SVT.getVectorNumElements())
8366     return SDValue();
8367
8368   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8369
8370   // AVX2 has better support of integer extending.
8371   if (Subtarget->hasInt256())
8372     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8373
8374   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8375   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8376   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8377                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8378                                                 DAG.getUNDEF(MVT::v8i16),
8379                                                 &Mask[0]));
8380
8381   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8382 }
8383
8384 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8385   DebugLoc DL = Op.getDebugLoc();
8386   EVT VT = Op.getValueType();
8387   SDValue In = Op.getOperand(0);
8388   EVT SVT = In.getValueType();
8389
8390   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8391     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8392     if (Subtarget->hasInt256()) {
8393       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8394       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8395       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8396                                 ShufMask);
8397       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8398                          DAG.getIntPtrConstant(0));
8399     }
8400
8401     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8402     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8403                                DAG.getIntPtrConstant(0));
8404     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8405                                DAG.getIntPtrConstant(2));
8406
8407     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8408     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8409
8410     // The PSHUFD mask:
8411     static const int ShufMask1[] = {0, 2, 0, 0};
8412     SDValue Undef = DAG.getUNDEF(VT);
8413     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8414     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8415
8416     // The MOVLHPS mask:
8417     static const int ShufMask2[] = {0, 1, 4, 5};
8418     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8419   }
8420
8421   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8422     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8423     if (Subtarget->hasInt256()) {
8424       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8425
8426       SmallVector<SDValue,32> pshufbMask;
8427       for (unsigned i = 0; i < 2; ++i) {
8428         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8429         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8430         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8431         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8432         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8433         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8434         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8435         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8436         for (unsigned j = 0; j < 8; ++j)
8437           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8438       }
8439       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8440                                &pshufbMask[0], 32);
8441       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8442       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8443
8444       static const int ShufMask[] = {0,  2,  -1,  -1};
8445       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8446                                 &ShufMask[0]);
8447       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8448                        DAG.getIntPtrConstant(0));
8449       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8450     }
8451
8452     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8453                                DAG.getIntPtrConstant(0));
8454
8455     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8456                                DAG.getIntPtrConstant(4));
8457
8458     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8459     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8460
8461     // The PSHUFB mask:
8462     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8463                                    -1, -1, -1, -1, -1, -1, -1, -1};
8464
8465     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8466     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8467     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8468
8469     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8470     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8471
8472     // The MOVLHPS Mask:
8473     static const int ShufMask2[] = {0, 1, 4, 5};
8474     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8475     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8476   }
8477
8478   // Handle truncation of V256 to V128 using shuffles.
8479   if (!VT.is128BitVector() || !SVT.is256BitVector())
8480     return SDValue();
8481
8482   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8483          "Invalid op");
8484   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8485
8486   unsigned NumElems = VT.getVectorNumElements();
8487   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8488                              NumElems * 2);
8489
8490   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8491   // Prepare truncation shuffle mask
8492   for (unsigned i = 0; i != NumElems; ++i)
8493     MaskVec[i] = i * 2;
8494   SDValue V = DAG.getVectorShuffle(NVT, DL,
8495                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8496                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8497   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8498                      DAG.getIntPtrConstant(0));
8499 }
8500
8501 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8502                                            SelectionDAG &DAG) const {
8503   if (Op.getValueType().isVector()) {
8504     if (Op.getValueType() == MVT::v8i16)
8505       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8506                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8507                                      MVT::v8i32, Op.getOperand(0)));
8508     return SDValue();
8509   }
8510
8511   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8512     /*IsSigned=*/ true, /*IsReplace=*/ false);
8513   SDValue FIST = Vals.first, StackSlot = Vals.second;
8514   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8515   if (FIST.getNode() == 0) return Op;
8516
8517   if (StackSlot.getNode())
8518     // Load the result.
8519     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8520                        FIST, StackSlot, MachinePointerInfo(),
8521                        false, false, false, 0);
8522
8523   // The node is the result.
8524   return FIST;
8525 }
8526
8527 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8528                                            SelectionDAG &DAG) const {
8529   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8530     /*IsSigned=*/ false, /*IsReplace=*/ false);
8531   SDValue FIST = Vals.first, StackSlot = Vals.second;
8532   assert(FIST.getNode() && "Unexpected failure");
8533
8534   if (StackSlot.getNode())
8535     // Load the result.
8536     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8537                        FIST, StackSlot, MachinePointerInfo(),
8538                        false, false, false, 0);
8539
8540   // The node is the result.
8541   return FIST;
8542 }
8543
8544 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8545                                           SelectionDAG &DAG) const {
8546   DebugLoc DL = Op.getDebugLoc();
8547   EVT VT = Op.getValueType();
8548   SDValue In = Op.getOperand(0);
8549   EVT SVT = In.getValueType();
8550
8551   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8552
8553   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8554                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8555                                  In, DAG.getUNDEF(SVT)));
8556 }
8557
8558 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8559   LLVMContext *Context = DAG.getContext();
8560   DebugLoc dl = Op.getDebugLoc();
8561   EVT VT = Op.getValueType();
8562   EVT EltVT = VT;
8563   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8564   if (VT.isVector()) {
8565     EltVT = VT.getVectorElementType();
8566     NumElts = VT.getVectorNumElements();
8567   }
8568   Constant *C;
8569   if (EltVT == MVT::f64)
8570     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8571   else
8572     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8573   C = ConstantVector::getSplat(NumElts, C);
8574   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8575   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8576   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8577                              MachinePointerInfo::getConstantPool(),
8578                              false, false, false, Alignment);
8579   if (VT.isVector()) {
8580     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8581     return DAG.getNode(ISD::BITCAST, dl, VT,
8582                        DAG.getNode(ISD::AND, dl, ANDVT,
8583                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8584                                                Op.getOperand(0)),
8585                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8586   }
8587   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8588 }
8589
8590 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8591   LLVMContext *Context = DAG.getContext();
8592   DebugLoc dl = Op.getDebugLoc();
8593   EVT VT = Op.getValueType();
8594   EVT EltVT = VT;
8595   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8596   if (VT.isVector()) {
8597     EltVT = VT.getVectorElementType();
8598     NumElts = VT.getVectorNumElements();
8599   }
8600   Constant *C;
8601   if (EltVT == MVT::f64)
8602     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8603   else
8604     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8605   C = ConstantVector::getSplat(NumElts, C);
8606   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8607   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8608   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8609                              MachinePointerInfo::getConstantPool(),
8610                              false, false, false, Alignment);
8611   if (VT.isVector()) {
8612     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8613     return DAG.getNode(ISD::BITCAST, dl, VT,
8614                        DAG.getNode(ISD::XOR, dl, XORVT,
8615                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8616                                                Op.getOperand(0)),
8617                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8618   }
8619
8620   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8621 }
8622
8623 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8624   LLVMContext *Context = DAG.getContext();
8625   SDValue Op0 = Op.getOperand(0);
8626   SDValue Op1 = Op.getOperand(1);
8627   DebugLoc dl = Op.getDebugLoc();
8628   EVT VT = Op.getValueType();
8629   EVT SrcVT = Op1.getValueType();
8630
8631   // If second operand is smaller, extend it first.
8632   if (SrcVT.bitsLT(VT)) {
8633     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8634     SrcVT = VT;
8635   }
8636   // And if it is bigger, shrink it first.
8637   if (SrcVT.bitsGT(VT)) {
8638     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8639     SrcVT = VT;
8640   }
8641
8642   // At this point the operands and the result should have the same
8643   // type, and that won't be f80 since that is not custom lowered.
8644
8645   // First get the sign bit of second operand.
8646   SmallVector<Constant*,4> CV;
8647   if (SrcVT == MVT::f64) {
8648     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8649     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8650   } else {
8651     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8652     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8653     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8654     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8655   }
8656   Constant *C = ConstantVector::get(CV);
8657   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8658   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8659                               MachinePointerInfo::getConstantPool(),
8660                               false, false, false, 16);
8661   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8662
8663   // Shift sign bit right or left if the two operands have different types.
8664   if (SrcVT.bitsGT(VT)) {
8665     // Op0 is MVT::f32, Op1 is MVT::f64.
8666     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8667     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8668                           DAG.getConstant(32, MVT::i32));
8669     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8670     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8671                           DAG.getIntPtrConstant(0));
8672   }
8673
8674   // Clear first operand sign bit.
8675   CV.clear();
8676   if (VT == MVT::f64) {
8677     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8678     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8679   } else {
8680     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8681     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8682     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8683     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8684   }
8685   C = ConstantVector::get(CV);
8686   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8687   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8688                               MachinePointerInfo::getConstantPool(),
8689                               false, false, false, 16);
8690   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8691
8692   // Or the value with the sign bit.
8693   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8694 }
8695
8696 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8697   SDValue N0 = Op.getOperand(0);
8698   DebugLoc dl = Op.getDebugLoc();
8699   EVT VT = Op.getValueType();
8700
8701   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8702   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8703                                   DAG.getConstant(1, VT));
8704   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8705 }
8706
8707 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8708 //
8709 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8710   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8711
8712   if (!Subtarget->hasSSE41())
8713     return SDValue();
8714
8715   if (!Op->hasOneUse())
8716     return SDValue();
8717
8718   SDNode *N = Op.getNode();
8719   DebugLoc DL = N->getDebugLoc();
8720
8721   SmallVector<SDValue, 8> Opnds;
8722   DenseMap<SDValue, unsigned> VecInMap;
8723   EVT VT = MVT::Other;
8724
8725   // Recognize a special case where a vector is casted into wide integer to
8726   // test all 0s.
8727   Opnds.push_back(N->getOperand(0));
8728   Opnds.push_back(N->getOperand(1));
8729
8730   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8731     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8732     // BFS traverse all OR'd operands.
8733     if (I->getOpcode() == ISD::OR) {
8734       Opnds.push_back(I->getOperand(0));
8735       Opnds.push_back(I->getOperand(1));
8736       // Re-evaluate the number of nodes to be traversed.
8737       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8738       continue;
8739     }
8740
8741     // Quit if a non-EXTRACT_VECTOR_ELT
8742     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8743       return SDValue();
8744
8745     // Quit if without a constant index.
8746     SDValue Idx = I->getOperand(1);
8747     if (!isa<ConstantSDNode>(Idx))
8748       return SDValue();
8749
8750     SDValue ExtractedFromVec = I->getOperand(0);
8751     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8752     if (M == VecInMap.end()) {
8753       VT = ExtractedFromVec.getValueType();
8754       // Quit if not 128/256-bit vector.
8755       if (!VT.is128BitVector() && !VT.is256BitVector())
8756         return SDValue();
8757       // Quit if not the same type.
8758       if (VecInMap.begin() != VecInMap.end() &&
8759           VT != VecInMap.begin()->first.getValueType())
8760         return SDValue();
8761       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8762     }
8763     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8764   }
8765
8766   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8767          "Not extracted from 128-/256-bit vector.");
8768
8769   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8770   SmallVector<SDValue, 8> VecIns;
8771
8772   for (DenseMap<SDValue, unsigned>::const_iterator
8773         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8774     // Quit if not all elements are used.
8775     if (I->second != FullMask)
8776       return SDValue();
8777     VecIns.push_back(I->first);
8778   }
8779
8780   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8781
8782   // Cast all vectors into TestVT for PTEST.
8783   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8784     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8785
8786   // If more than one full vectors are evaluated, OR them first before PTEST.
8787   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8788     // Each iteration will OR 2 nodes and append the result until there is only
8789     // 1 node left, i.e. the final OR'd value of all vectors.
8790     SDValue LHS = VecIns[Slot];
8791     SDValue RHS = VecIns[Slot + 1];
8792     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8793   }
8794
8795   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8796                      VecIns.back(), VecIns.back());
8797 }
8798
8799 /// Emit nodes that will be selected as "test Op0,Op0", or something
8800 /// equivalent.
8801 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8802                                     SelectionDAG &DAG) const {
8803   DebugLoc dl = Op.getDebugLoc();
8804
8805   // CF and OF aren't always set the way we want. Determine which
8806   // of these we need.
8807   bool NeedCF = false;
8808   bool NeedOF = false;
8809   switch (X86CC) {
8810   default: break;
8811   case X86::COND_A: case X86::COND_AE:
8812   case X86::COND_B: case X86::COND_BE:
8813     NeedCF = true;
8814     break;
8815   case X86::COND_G: case X86::COND_GE:
8816   case X86::COND_L: case X86::COND_LE:
8817   case X86::COND_O: case X86::COND_NO:
8818     NeedOF = true;
8819     break;
8820   }
8821
8822   // See if we can use the EFLAGS value from the operand instead of
8823   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8824   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8825   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8826     // Emit a CMP with 0, which is the TEST pattern.
8827     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8828                        DAG.getConstant(0, Op.getValueType()));
8829
8830   unsigned Opcode = 0;
8831   unsigned NumOperands = 0;
8832
8833   // Truncate operations may prevent the merge of the SETCC instruction
8834   // and the arithmetic intruction before it. Attempt to truncate the operands
8835   // of the arithmetic instruction and use a reduced bit-width instruction.
8836   bool NeedTruncation = false;
8837   SDValue ArithOp = Op;
8838   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8839     SDValue Arith = Op->getOperand(0);
8840     // Both the trunc and the arithmetic op need to have one user each.
8841     if (Arith->hasOneUse())
8842       switch (Arith.getOpcode()) {
8843         default: break;
8844         case ISD::ADD:
8845         case ISD::SUB:
8846         case ISD::AND:
8847         case ISD::OR:
8848         case ISD::XOR: {
8849           NeedTruncation = true;
8850           ArithOp = Arith;
8851         }
8852       }
8853   }
8854
8855   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8856   // which may be the result of a CAST.  We use the variable 'Op', which is the
8857   // non-casted variable when we check for possible users.
8858   switch (ArithOp.getOpcode()) {
8859   case ISD::ADD:
8860     // Due to an isel shortcoming, be conservative if this add is likely to be
8861     // selected as part of a load-modify-store instruction. When the root node
8862     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8863     // uses of other nodes in the match, such as the ADD in this case. This
8864     // leads to the ADD being left around and reselected, with the result being
8865     // two adds in the output.  Alas, even if none our users are stores, that
8866     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8867     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8868     // climbing the DAG back to the root, and it doesn't seem to be worth the
8869     // effort.
8870     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8871          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8872       if (UI->getOpcode() != ISD::CopyToReg &&
8873           UI->getOpcode() != ISD::SETCC &&
8874           UI->getOpcode() != ISD::STORE)
8875         goto default_case;
8876
8877     if (ConstantSDNode *C =
8878         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8879       // An add of one will be selected as an INC.
8880       if (C->getAPIntValue() == 1) {
8881         Opcode = X86ISD::INC;
8882         NumOperands = 1;
8883         break;
8884       }
8885
8886       // An add of negative one (subtract of one) will be selected as a DEC.
8887       if (C->getAPIntValue().isAllOnesValue()) {
8888         Opcode = X86ISD::DEC;
8889         NumOperands = 1;
8890         break;
8891       }
8892     }
8893
8894     // Otherwise use a regular EFLAGS-setting add.
8895     Opcode = X86ISD::ADD;
8896     NumOperands = 2;
8897     break;
8898   case ISD::AND: {
8899     // If the primary and result isn't used, don't bother using X86ISD::AND,
8900     // because a TEST instruction will be better.
8901     bool NonFlagUse = false;
8902     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8903            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8904       SDNode *User = *UI;
8905       unsigned UOpNo = UI.getOperandNo();
8906       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8907         // Look pass truncate.
8908         UOpNo = User->use_begin().getOperandNo();
8909         User = *User->use_begin();
8910       }
8911
8912       if (User->getOpcode() != ISD::BRCOND &&
8913           User->getOpcode() != ISD::SETCC &&
8914           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8915         NonFlagUse = true;
8916         break;
8917       }
8918     }
8919
8920     if (!NonFlagUse)
8921       break;
8922   }
8923     // FALL THROUGH
8924   case ISD::SUB:
8925   case ISD::OR:
8926   case ISD::XOR:
8927     // Due to the ISEL shortcoming noted above, be conservative if this op is
8928     // likely to be selected as part of a load-modify-store instruction.
8929     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8930            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8931       if (UI->getOpcode() == ISD::STORE)
8932         goto default_case;
8933
8934     // Otherwise use a regular EFLAGS-setting instruction.
8935     switch (ArithOp.getOpcode()) {
8936     default: llvm_unreachable("unexpected operator!");
8937     case ISD::SUB: Opcode = X86ISD::SUB; break;
8938     case ISD::XOR: Opcode = X86ISD::XOR; break;
8939     case ISD::AND: Opcode = X86ISD::AND; break;
8940     case ISD::OR: {
8941       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8942         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8943         if (EFLAGS.getNode())
8944           return EFLAGS;
8945       }
8946       Opcode = X86ISD::OR;
8947       break;
8948     }
8949     }
8950
8951     NumOperands = 2;
8952     break;
8953   case X86ISD::ADD:
8954   case X86ISD::SUB:
8955   case X86ISD::INC:
8956   case X86ISD::DEC:
8957   case X86ISD::OR:
8958   case X86ISD::XOR:
8959   case X86ISD::AND:
8960     return SDValue(Op.getNode(), 1);
8961   default:
8962   default_case:
8963     break;
8964   }
8965
8966   // If we found that truncation is beneficial, perform the truncation and
8967   // update 'Op'.
8968   if (NeedTruncation) {
8969     EVT VT = Op.getValueType();
8970     SDValue WideVal = Op->getOperand(0);
8971     EVT WideVT = WideVal.getValueType();
8972     unsigned ConvertedOp = 0;
8973     // Use a target machine opcode to prevent further DAGCombine
8974     // optimizations that may separate the arithmetic operations
8975     // from the setcc node.
8976     switch (WideVal.getOpcode()) {
8977       default: break;
8978       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8979       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8980       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8981       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8982       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8983     }
8984
8985     if (ConvertedOp) {
8986       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8987       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8988         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8989         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8990         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8991       }
8992     }
8993   }
8994
8995   if (Opcode == 0)
8996     // Emit a CMP with 0, which is the TEST pattern.
8997     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8998                        DAG.getConstant(0, Op.getValueType()));
8999
9000   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9001   SmallVector<SDValue, 4> Ops;
9002   for (unsigned i = 0; i != NumOperands; ++i)
9003     Ops.push_back(Op.getOperand(i));
9004
9005   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9006   DAG.ReplaceAllUsesWith(Op, New);
9007   return SDValue(New.getNode(), 1);
9008 }
9009
9010 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9011 /// equivalent.
9012 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9013                                    SelectionDAG &DAG) const {
9014   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9015     if (C->getAPIntValue() == 0)
9016       return EmitTest(Op0, X86CC, DAG);
9017
9018   DebugLoc dl = Op0.getDebugLoc();
9019   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9020        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9021     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9022     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9023     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9024                               Op0, Op1);
9025     return SDValue(Sub.getNode(), 1);
9026   }
9027   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9028 }
9029
9030 /// Convert a comparison if required by the subtarget.
9031 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9032                                                  SelectionDAG &DAG) const {
9033   // If the subtarget does not support the FUCOMI instruction, floating-point
9034   // comparisons have to be converted.
9035   if (Subtarget->hasCMov() ||
9036       Cmp.getOpcode() != X86ISD::CMP ||
9037       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9038       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9039     return Cmp;
9040
9041   // The instruction selector will select an FUCOM instruction instead of
9042   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9043   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9044   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9045   DebugLoc dl = Cmp.getDebugLoc();
9046   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9047   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9048   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9049                             DAG.getConstant(8, MVT::i8));
9050   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9051   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9052 }
9053
9054 static bool isAllOnes(SDValue V) {
9055   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9056   return C && C->isAllOnesValue();
9057 }
9058
9059 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9060 /// if it's possible.
9061 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9062                                      DebugLoc dl, SelectionDAG &DAG) const {
9063   SDValue Op0 = And.getOperand(0);
9064   SDValue Op1 = And.getOperand(1);
9065   if (Op0.getOpcode() == ISD::TRUNCATE)
9066     Op0 = Op0.getOperand(0);
9067   if (Op1.getOpcode() == ISD::TRUNCATE)
9068     Op1 = Op1.getOperand(0);
9069
9070   SDValue LHS, RHS;
9071   if (Op1.getOpcode() == ISD::SHL)
9072     std::swap(Op0, Op1);
9073   if (Op0.getOpcode() == ISD::SHL) {
9074     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9075       if (And00C->getZExtValue() == 1) {
9076         // If we looked past a truncate, check that it's only truncating away
9077         // known zeros.
9078         unsigned BitWidth = Op0.getValueSizeInBits();
9079         unsigned AndBitWidth = And.getValueSizeInBits();
9080         if (BitWidth > AndBitWidth) {
9081           APInt Zeros, Ones;
9082           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9083           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9084             return SDValue();
9085         }
9086         LHS = Op1;
9087         RHS = Op0.getOperand(1);
9088       }
9089   } else if (Op1.getOpcode() == ISD::Constant) {
9090     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9091     uint64_t AndRHSVal = AndRHS->getZExtValue();
9092     SDValue AndLHS = Op0;
9093
9094     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9095       LHS = AndLHS.getOperand(0);
9096       RHS = AndLHS.getOperand(1);
9097     }
9098
9099     // Use BT if the immediate can't be encoded in a TEST instruction.
9100     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9101       LHS = AndLHS;
9102       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9103     }
9104   }
9105
9106   if (LHS.getNode()) {
9107     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9108     // the condition code later.
9109     bool Invert = false;
9110     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9111       Invert = true;
9112       LHS = LHS.getOperand(0);
9113     }
9114
9115     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9116     // instruction.  Since the shift amount is in-range-or-undefined, we know
9117     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9118     // the encoding for the i16 version is larger than the i32 version.
9119     // Also promote i16 to i32 for performance / code size reason.
9120     if (LHS.getValueType() == MVT::i8 ||
9121         LHS.getValueType() == MVT::i16)
9122       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9123
9124     // If the operand types disagree, extend the shift amount to match.  Since
9125     // BT ignores high bits (like shifts) we can use anyextend.
9126     if (LHS.getValueType() != RHS.getValueType())
9127       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9128
9129     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9130     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9131     // Flip the condition if the LHS was a not instruction
9132     if (Invert)
9133       Cond = X86::GetOppositeBranchCondition(Cond);
9134     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9135                        DAG.getConstant(Cond, MVT::i8), BT);
9136   }
9137
9138   return SDValue();
9139 }
9140
9141 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9142
9143   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
9144
9145   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
9146   SDValue Op0 = Op.getOperand(0);
9147   SDValue Op1 = Op.getOperand(1);
9148   DebugLoc dl = Op.getDebugLoc();
9149   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9150
9151   // Optimize to BT if possible.
9152   // Lower (X & (1 << N)) == 0 to BT(X, N).
9153   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9154   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9155   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9156       Op1.getOpcode() == ISD::Constant &&
9157       cast<ConstantSDNode>(Op1)->isNullValue() &&
9158       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9159     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9160     if (NewSetCC.getNode())
9161       return NewSetCC;
9162   }
9163
9164   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9165   // these.
9166   if (Op1.getOpcode() == ISD::Constant &&
9167       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9168        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9169       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9170
9171     // If the input is a setcc, then reuse the input setcc or use a new one with
9172     // the inverted condition.
9173     if (Op0.getOpcode() == X86ISD::SETCC) {
9174       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9175       bool Invert = (CC == ISD::SETNE) ^
9176         cast<ConstantSDNode>(Op1)->isNullValue();
9177       if (!Invert) return Op0;
9178
9179       CCode = X86::GetOppositeBranchCondition(CCode);
9180       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9181                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9182     }
9183   }
9184
9185   bool isFP = Op1.getValueType().isFloatingPoint();
9186   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9187   if (X86CC == X86::COND_INVALID)
9188     return SDValue();
9189
9190   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9191   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9192   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9193                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9194 }
9195
9196 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9197 // ones, and then concatenate the result back.
9198 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9199   EVT VT = Op.getValueType();
9200
9201   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9202          "Unsupported value type for operation");
9203
9204   unsigned NumElems = VT.getVectorNumElements();
9205   DebugLoc dl = Op.getDebugLoc();
9206   SDValue CC = Op.getOperand(2);
9207
9208   // Extract the LHS vectors
9209   SDValue LHS = Op.getOperand(0);
9210   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9211   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9212
9213   // Extract the RHS vectors
9214   SDValue RHS = Op.getOperand(1);
9215   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9216   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9217
9218   // Issue the operation on the smaller types and concatenate the result back
9219   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9220   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9221   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9222                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9223                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9224 }
9225
9226 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9227   SDValue Cond;
9228   SDValue Op0 = Op.getOperand(0);
9229   SDValue Op1 = Op.getOperand(1);
9230   SDValue CC = Op.getOperand(2);
9231   EVT VT = Op.getValueType();
9232   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9233   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9234   DebugLoc dl = Op.getDebugLoc();
9235
9236   if (isFP) {
9237 #ifndef NDEBUG
9238     EVT EltVT = Op0.getValueType().getVectorElementType();
9239     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9240 #endif
9241
9242     unsigned SSECC;
9243     bool Swap = false;
9244
9245     // SSE Condition code mapping:
9246     //  0 - EQ
9247     //  1 - LT
9248     //  2 - LE
9249     //  3 - UNORD
9250     //  4 - NEQ
9251     //  5 - NLT
9252     //  6 - NLE
9253     //  7 - ORD
9254     switch (SetCCOpcode) {
9255     default: llvm_unreachable("Unexpected SETCC condition");
9256     case ISD::SETOEQ:
9257     case ISD::SETEQ:  SSECC = 0; break;
9258     case ISD::SETOGT:
9259     case ISD::SETGT: Swap = true; // Fallthrough
9260     case ISD::SETLT:
9261     case ISD::SETOLT: SSECC = 1; break;
9262     case ISD::SETOGE:
9263     case ISD::SETGE: Swap = true; // Fallthrough
9264     case ISD::SETLE:
9265     case ISD::SETOLE: SSECC = 2; break;
9266     case ISD::SETUO:  SSECC = 3; break;
9267     case ISD::SETUNE:
9268     case ISD::SETNE:  SSECC = 4; break;
9269     case ISD::SETULE: Swap = true; // Fallthrough
9270     case ISD::SETUGE: SSECC = 5; break;
9271     case ISD::SETULT: Swap = true; // Fallthrough
9272     case ISD::SETUGT: SSECC = 6; break;
9273     case ISD::SETO:   SSECC = 7; break;
9274     case ISD::SETUEQ:
9275     case ISD::SETONE: SSECC = 8; break;
9276     }
9277     if (Swap)
9278       std::swap(Op0, Op1);
9279
9280     // In the two special cases we can't handle, emit two comparisons.
9281     if (SSECC == 8) {
9282       unsigned CC0, CC1;
9283       unsigned CombineOpc;
9284       if (SetCCOpcode == ISD::SETUEQ) {
9285         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9286       } else {
9287         assert(SetCCOpcode == ISD::SETONE);
9288         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9289       }
9290
9291       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9292                                  DAG.getConstant(CC0, MVT::i8));
9293       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9294                                  DAG.getConstant(CC1, MVT::i8));
9295       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9296     }
9297     // Handle all other FP comparisons here.
9298     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9299                        DAG.getConstant(SSECC, MVT::i8));
9300   }
9301
9302   // Break 256-bit integer vector compare into smaller ones.
9303   if (VT.is256BitVector() && !Subtarget->hasInt256())
9304     return Lower256IntVSETCC(Op, DAG);
9305
9306   // We are handling one of the integer comparisons here.  Since SSE only has
9307   // GT and EQ comparisons for integer, swapping operands and multiple
9308   // operations may be required for some comparisons.
9309   unsigned Opc;
9310   bool Swap = false, Invert = false, FlipSigns = false;
9311
9312   switch (SetCCOpcode) {
9313   default: llvm_unreachable("Unexpected SETCC condition");
9314   case ISD::SETNE:  Invert = true;
9315   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9316   case ISD::SETLT:  Swap = true;
9317   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9318   case ISD::SETGE:  Swap = true;
9319   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9320   case ISD::SETULT: Swap = true;
9321   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9322   case ISD::SETUGE: Swap = true;
9323   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9324   }
9325   if (Swap)
9326     std::swap(Op0, Op1);
9327
9328   // Check that the operation in question is available (most are plain SSE2,
9329   // but PCMPGTQ and PCMPEQQ have different requirements).
9330   if (VT == MVT::v2i64) {
9331     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9332       return SDValue();
9333     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9334       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9335       // pcmpeqd + pshufd + pand.
9336       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9337
9338       // First cast everything to the right type,
9339       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9340       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9341
9342       // Do the compare.
9343       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9344
9345       // Make sure the lower and upper halves are both all-ones.
9346       const int Mask[] = { 1, 0, 3, 2 };
9347       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9348       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9349
9350       if (Invert)
9351         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9352
9353       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9354     }
9355   }
9356
9357   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9358   // bits of the inputs before performing those operations.
9359   if (FlipSigns) {
9360     EVT EltVT = VT.getVectorElementType();
9361     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9362                                       EltVT);
9363     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9364     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9365                                     SignBits.size());
9366     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9367     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9368   }
9369
9370   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9371
9372   // If the logical-not of the result is required, perform that now.
9373   if (Invert)
9374     Result = DAG.getNOT(dl, Result, VT);
9375
9376   return Result;
9377 }
9378
9379 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9380 static bool isX86LogicalCmp(SDValue Op) {
9381   unsigned Opc = Op.getNode()->getOpcode();
9382   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9383       Opc == X86ISD::SAHF)
9384     return true;
9385   if (Op.getResNo() == 1 &&
9386       (Opc == X86ISD::ADD ||
9387        Opc == X86ISD::SUB ||
9388        Opc == X86ISD::ADC ||
9389        Opc == X86ISD::SBB ||
9390        Opc == X86ISD::SMUL ||
9391        Opc == X86ISD::UMUL ||
9392        Opc == X86ISD::INC ||
9393        Opc == X86ISD::DEC ||
9394        Opc == X86ISD::OR ||
9395        Opc == X86ISD::XOR ||
9396        Opc == X86ISD::AND))
9397     return true;
9398
9399   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9400     return true;
9401
9402   return false;
9403 }
9404
9405 static bool isZero(SDValue V) {
9406   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9407   return C && C->isNullValue();
9408 }
9409
9410 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9411   if (V.getOpcode() != ISD::TRUNCATE)
9412     return false;
9413
9414   SDValue VOp0 = V.getOperand(0);
9415   unsigned InBits = VOp0.getValueSizeInBits();
9416   unsigned Bits = V.getValueSizeInBits();
9417   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9418 }
9419
9420 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9421   bool addTest = true;
9422   SDValue Cond  = Op.getOperand(0);
9423   SDValue Op1 = Op.getOperand(1);
9424   SDValue Op2 = Op.getOperand(2);
9425   DebugLoc DL = Op.getDebugLoc();
9426   SDValue CC;
9427
9428   if (Cond.getOpcode() == ISD::SETCC) {
9429     SDValue NewCond = LowerSETCC(Cond, DAG);
9430     if (NewCond.getNode())
9431       Cond = NewCond;
9432   }
9433
9434   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9435   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9436   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9437   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9438   if (Cond.getOpcode() == X86ISD::SETCC &&
9439       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9440       isZero(Cond.getOperand(1).getOperand(1))) {
9441     SDValue Cmp = Cond.getOperand(1);
9442
9443     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9444
9445     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9446         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9447       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9448
9449       SDValue CmpOp0 = Cmp.getOperand(0);
9450       // Apply further optimizations for special cases
9451       // (select (x != 0), -1, 0) -> neg & sbb
9452       // (select (x == 0), 0, -1) -> neg & sbb
9453       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9454         if (YC->isNullValue() &&
9455             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9456           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9457           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9458                                     DAG.getConstant(0, CmpOp0.getValueType()),
9459                                     CmpOp0);
9460           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9461                                     DAG.getConstant(X86::COND_B, MVT::i8),
9462                                     SDValue(Neg.getNode(), 1));
9463           return Res;
9464         }
9465
9466       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9467                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9468       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9469
9470       SDValue Res =   // Res = 0 or -1.
9471         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9472                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9473
9474       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9475         Res = DAG.getNOT(DL, Res, Res.getValueType());
9476
9477       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9478       if (N2C == 0 || !N2C->isNullValue())
9479         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9480       return Res;
9481     }
9482   }
9483
9484   // Look past (and (setcc_carry (cmp ...)), 1).
9485   if (Cond.getOpcode() == ISD::AND &&
9486       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9487     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9488     if (C && C->getAPIntValue() == 1)
9489       Cond = Cond.getOperand(0);
9490   }
9491
9492   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9493   // setting operand in place of the X86ISD::SETCC.
9494   unsigned CondOpcode = Cond.getOpcode();
9495   if (CondOpcode == X86ISD::SETCC ||
9496       CondOpcode == X86ISD::SETCC_CARRY) {
9497     CC = Cond.getOperand(0);
9498
9499     SDValue Cmp = Cond.getOperand(1);
9500     unsigned Opc = Cmp.getOpcode();
9501     EVT VT = Op.getValueType();
9502
9503     bool IllegalFPCMov = false;
9504     if (VT.isFloatingPoint() && !VT.isVector() &&
9505         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9506       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9507
9508     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9509         Opc == X86ISD::BT) { // FIXME
9510       Cond = Cmp;
9511       addTest = false;
9512     }
9513   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9514              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9515              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9516               Cond.getOperand(0).getValueType() != MVT::i8)) {
9517     SDValue LHS = Cond.getOperand(0);
9518     SDValue RHS = Cond.getOperand(1);
9519     unsigned X86Opcode;
9520     unsigned X86Cond;
9521     SDVTList VTs;
9522     switch (CondOpcode) {
9523     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9524     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9525     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9526     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9527     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9528     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9529     default: llvm_unreachable("unexpected overflowing operator");
9530     }
9531     if (CondOpcode == ISD::UMULO)
9532       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9533                           MVT::i32);
9534     else
9535       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9536
9537     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9538
9539     if (CondOpcode == ISD::UMULO)
9540       Cond = X86Op.getValue(2);
9541     else
9542       Cond = X86Op.getValue(1);
9543
9544     CC = DAG.getConstant(X86Cond, MVT::i8);
9545     addTest = false;
9546   }
9547
9548   if (addTest) {
9549     // Look pass the truncate if the high bits are known zero.
9550     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9551         Cond = Cond.getOperand(0);
9552
9553     // We know the result of AND is compared against zero. Try to match
9554     // it to BT.
9555     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9556       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9557       if (NewSetCC.getNode()) {
9558         CC = NewSetCC.getOperand(0);
9559         Cond = NewSetCC.getOperand(1);
9560         addTest = false;
9561       }
9562     }
9563   }
9564
9565   if (addTest) {
9566     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9567     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9568   }
9569
9570   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9571   // a <  b ?  0 : -1 -> RES = setcc_carry
9572   // a >= b ? -1 :  0 -> RES = setcc_carry
9573   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9574   if (Cond.getOpcode() == X86ISD::SUB) {
9575     Cond = ConvertCmpIfNecessary(Cond, DAG);
9576     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9577
9578     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9579         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9580       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9581                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9582       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9583         return DAG.getNOT(DL, Res, Res.getValueType());
9584       return Res;
9585     }
9586   }
9587
9588   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9589   // widen the cmov and push the truncate through. This avoids introducing a new
9590   // branch during isel and doesn't add any extensions.
9591   if (Op.getValueType() == MVT::i8 &&
9592       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9593     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9594     if (T1.getValueType() == T2.getValueType() &&
9595         // Blacklist CopyFromReg to avoid partial register stalls.
9596         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9597       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9598       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9599       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9600     }
9601   }
9602
9603   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9604   // condition is true.
9605   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9606   SDValue Ops[] = { Op2, Op1, CC, Cond };
9607   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9608 }
9609
9610 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9611                                             SelectionDAG &DAG) const {
9612   EVT VT = Op->getValueType(0);
9613   SDValue In = Op->getOperand(0);
9614   EVT InVT = In.getValueType();
9615   DebugLoc dl = Op->getDebugLoc();
9616
9617   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9618       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9619     return SDValue();
9620
9621   if (Subtarget->hasInt256())
9622     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9623
9624   // Optimize vectors in AVX mode
9625   // Sign extend  v8i16 to v8i32 and
9626   //              v4i32 to v4i64
9627   //
9628   // Divide input vector into two parts
9629   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9630   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9631   // concat the vectors to original VT
9632
9633   unsigned NumElems = InVT.getVectorNumElements();
9634   SDValue Undef = DAG.getUNDEF(InVT);
9635
9636   SmallVector<int,8> ShufMask1(NumElems, -1);
9637   for (unsigned i = 0; i != NumElems/2; ++i)
9638     ShufMask1[i] = i;
9639
9640   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9641
9642   SmallVector<int,8> ShufMask2(NumElems, -1);
9643   for (unsigned i = 0; i != NumElems/2; ++i)
9644     ShufMask2[i] = i + NumElems/2;
9645
9646   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9647
9648   EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
9649                                 VT.getVectorNumElements()/2);
9650
9651   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9652   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9653
9654   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9655 }
9656
9657 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9658 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9659 // from the AND / OR.
9660 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9661   Opc = Op.getOpcode();
9662   if (Opc != ISD::OR && Opc != ISD::AND)
9663     return false;
9664   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9665           Op.getOperand(0).hasOneUse() &&
9666           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9667           Op.getOperand(1).hasOneUse());
9668 }
9669
9670 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9671 // 1 and that the SETCC node has a single use.
9672 static bool isXor1OfSetCC(SDValue Op) {
9673   if (Op.getOpcode() != ISD::XOR)
9674     return false;
9675   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9676   if (N1C && N1C->getAPIntValue() == 1) {
9677     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9678       Op.getOperand(0).hasOneUse();
9679   }
9680   return false;
9681 }
9682
9683 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9684   bool addTest = true;
9685   SDValue Chain = Op.getOperand(0);
9686   SDValue Cond  = Op.getOperand(1);
9687   SDValue Dest  = Op.getOperand(2);
9688   DebugLoc dl = Op.getDebugLoc();
9689   SDValue CC;
9690   bool Inverted = false;
9691
9692   if (Cond.getOpcode() == ISD::SETCC) {
9693     // Check for setcc([su]{add,sub,mul}o == 0).
9694     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9695         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9696         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9697         Cond.getOperand(0).getResNo() == 1 &&
9698         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9699          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9700          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9701          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9702          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9703          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9704       Inverted = true;
9705       Cond = Cond.getOperand(0);
9706     } else {
9707       SDValue NewCond = LowerSETCC(Cond, DAG);
9708       if (NewCond.getNode())
9709         Cond = NewCond;
9710     }
9711   }
9712 #if 0
9713   // FIXME: LowerXALUO doesn't handle these!!
9714   else if (Cond.getOpcode() == X86ISD::ADD  ||
9715            Cond.getOpcode() == X86ISD::SUB  ||
9716            Cond.getOpcode() == X86ISD::SMUL ||
9717            Cond.getOpcode() == X86ISD::UMUL)
9718     Cond = LowerXALUO(Cond, DAG);
9719 #endif
9720
9721   // Look pass (and (setcc_carry (cmp ...)), 1).
9722   if (Cond.getOpcode() == ISD::AND &&
9723       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9724     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9725     if (C && C->getAPIntValue() == 1)
9726       Cond = Cond.getOperand(0);
9727   }
9728
9729   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9730   // setting operand in place of the X86ISD::SETCC.
9731   unsigned CondOpcode = Cond.getOpcode();
9732   if (CondOpcode == X86ISD::SETCC ||
9733       CondOpcode == X86ISD::SETCC_CARRY) {
9734     CC = Cond.getOperand(0);
9735
9736     SDValue Cmp = Cond.getOperand(1);
9737     unsigned Opc = Cmp.getOpcode();
9738     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9739     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9740       Cond = Cmp;
9741       addTest = false;
9742     } else {
9743       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9744       default: break;
9745       case X86::COND_O:
9746       case X86::COND_B:
9747         // These can only come from an arithmetic instruction with overflow,
9748         // e.g. SADDO, UADDO.
9749         Cond = Cond.getNode()->getOperand(1);
9750         addTest = false;
9751         break;
9752       }
9753     }
9754   }
9755   CondOpcode = Cond.getOpcode();
9756   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9757       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9758       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9759        Cond.getOperand(0).getValueType() != MVT::i8)) {
9760     SDValue LHS = Cond.getOperand(0);
9761     SDValue RHS = Cond.getOperand(1);
9762     unsigned X86Opcode;
9763     unsigned X86Cond;
9764     SDVTList VTs;
9765     switch (CondOpcode) {
9766     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9767     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9768     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9769     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9770     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9771     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9772     default: llvm_unreachable("unexpected overflowing operator");
9773     }
9774     if (Inverted)
9775       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9776     if (CondOpcode == ISD::UMULO)
9777       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9778                           MVT::i32);
9779     else
9780       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9781
9782     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9783
9784     if (CondOpcode == ISD::UMULO)
9785       Cond = X86Op.getValue(2);
9786     else
9787       Cond = X86Op.getValue(1);
9788
9789     CC = DAG.getConstant(X86Cond, MVT::i8);
9790     addTest = false;
9791   } else {
9792     unsigned CondOpc;
9793     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9794       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9795       if (CondOpc == ISD::OR) {
9796         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9797         // two branches instead of an explicit OR instruction with a
9798         // separate test.
9799         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9800             isX86LogicalCmp(Cmp)) {
9801           CC = Cond.getOperand(0).getOperand(0);
9802           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9803                               Chain, Dest, CC, Cmp);
9804           CC = Cond.getOperand(1).getOperand(0);
9805           Cond = Cmp;
9806           addTest = false;
9807         }
9808       } else { // ISD::AND
9809         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9810         // two branches instead of an explicit AND instruction with a
9811         // separate test. However, we only do this if this block doesn't
9812         // have a fall-through edge, because this requires an explicit
9813         // jmp when the condition is false.
9814         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9815             isX86LogicalCmp(Cmp) &&
9816             Op.getNode()->hasOneUse()) {
9817           X86::CondCode CCode =
9818             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9819           CCode = X86::GetOppositeBranchCondition(CCode);
9820           CC = DAG.getConstant(CCode, MVT::i8);
9821           SDNode *User = *Op.getNode()->use_begin();
9822           // Look for an unconditional branch following this conditional branch.
9823           // We need this because we need to reverse the successors in order
9824           // to implement FCMP_OEQ.
9825           if (User->getOpcode() == ISD::BR) {
9826             SDValue FalseBB = User->getOperand(1);
9827             SDNode *NewBR =
9828               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9829             assert(NewBR == User);
9830             (void)NewBR;
9831             Dest = FalseBB;
9832
9833             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9834                                 Chain, Dest, CC, Cmp);
9835             X86::CondCode CCode =
9836               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9837             CCode = X86::GetOppositeBranchCondition(CCode);
9838             CC = DAG.getConstant(CCode, MVT::i8);
9839             Cond = Cmp;
9840             addTest = false;
9841           }
9842         }
9843       }
9844     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9845       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9846       // It should be transformed during dag combiner except when the condition
9847       // is set by a arithmetics with overflow node.
9848       X86::CondCode CCode =
9849         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9850       CCode = X86::GetOppositeBranchCondition(CCode);
9851       CC = DAG.getConstant(CCode, MVT::i8);
9852       Cond = Cond.getOperand(0).getOperand(1);
9853       addTest = false;
9854     } else if (Cond.getOpcode() == ISD::SETCC &&
9855                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9856       // For FCMP_OEQ, we can emit
9857       // two branches instead of an explicit AND instruction with a
9858       // separate test. However, we only do this if this block doesn't
9859       // have a fall-through edge, because this requires an explicit
9860       // jmp when the condition is false.
9861       if (Op.getNode()->hasOneUse()) {
9862         SDNode *User = *Op.getNode()->use_begin();
9863         // Look for an unconditional branch following this conditional branch.
9864         // We need this because we need to reverse the successors in order
9865         // to implement FCMP_OEQ.
9866         if (User->getOpcode() == ISD::BR) {
9867           SDValue FalseBB = User->getOperand(1);
9868           SDNode *NewBR =
9869             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9870           assert(NewBR == User);
9871           (void)NewBR;
9872           Dest = FalseBB;
9873
9874           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9875                                     Cond.getOperand(0), Cond.getOperand(1));
9876           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9877           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9878           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9879                               Chain, Dest, CC, Cmp);
9880           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9881           Cond = Cmp;
9882           addTest = false;
9883         }
9884       }
9885     } else if (Cond.getOpcode() == ISD::SETCC &&
9886                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9887       // For FCMP_UNE, we can emit
9888       // two branches instead of an explicit AND instruction with a
9889       // separate test. However, we only do this if this block doesn't
9890       // have a fall-through edge, because this requires an explicit
9891       // jmp when the condition is false.
9892       if (Op.getNode()->hasOneUse()) {
9893         SDNode *User = *Op.getNode()->use_begin();
9894         // Look for an unconditional branch following this conditional branch.
9895         // We need this because we need to reverse the successors in order
9896         // to implement FCMP_UNE.
9897         if (User->getOpcode() == ISD::BR) {
9898           SDValue FalseBB = User->getOperand(1);
9899           SDNode *NewBR =
9900             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9901           assert(NewBR == User);
9902           (void)NewBR;
9903
9904           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9905                                     Cond.getOperand(0), Cond.getOperand(1));
9906           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9907           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9908           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9909                               Chain, Dest, CC, Cmp);
9910           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9911           Cond = Cmp;
9912           addTest = false;
9913           Dest = FalseBB;
9914         }
9915       }
9916     }
9917   }
9918
9919   if (addTest) {
9920     // Look pass the truncate if the high bits are known zero.
9921     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9922         Cond = Cond.getOperand(0);
9923
9924     // We know the result of AND is compared against zero. Try to match
9925     // it to BT.
9926     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9927       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9928       if (NewSetCC.getNode()) {
9929         CC = NewSetCC.getOperand(0);
9930         Cond = NewSetCC.getOperand(1);
9931         addTest = false;
9932       }
9933     }
9934   }
9935
9936   if (addTest) {
9937     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9938     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9939   }
9940   Cond = ConvertCmpIfNecessary(Cond, DAG);
9941   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9942                      Chain, Dest, CC, Cond);
9943 }
9944
9945 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9946 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9947 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9948 // that the guard pages used by the OS virtual memory manager are allocated in
9949 // correct sequence.
9950 SDValue
9951 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9952                                            SelectionDAG &DAG) const {
9953   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9954           getTargetMachine().Options.EnableSegmentedStacks) &&
9955          "This should be used only on Windows targets or when segmented stacks "
9956          "are being used");
9957   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9958   DebugLoc dl = Op.getDebugLoc();
9959
9960   // Get the inputs.
9961   SDValue Chain = Op.getOperand(0);
9962   SDValue Size  = Op.getOperand(1);
9963   // FIXME: Ensure alignment here
9964
9965   bool Is64Bit = Subtarget->is64Bit();
9966   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9967
9968   if (getTargetMachine().Options.EnableSegmentedStacks) {
9969     MachineFunction &MF = DAG.getMachineFunction();
9970     MachineRegisterInfo &MRI = MF.getRegInfo();
9971
9972     if (Is64Bit) {
9973       // The 64 bit implementation of segmented stacks needs to clobber both r10
9974       // r11. This makes it impossible to use it along with nested parameters.
9975       const Function *F = MF.getFunction();
9976
9977       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9978            I != E; ++I)
9979         if (I->hasNestAttr())
9980           report_fatal_error("Cannot use segmented stacks with functions that "
9981                              "have nested arguments.");
9982     }
9983
9984     const TargetRegisterClass *AddrRegClass =
9985       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9986     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9987     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9988     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9989                                 DAG.getRegister(Vreg, SPTy));
9990     SDValue Ops1[2] = { Value, Chain };
9991     return DAG.getMergeValues(Ops1, 2, dl);
9992   } else {
9993     SDValue Flag;
9994     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9995
9996     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9997     Flag = Chain.getValue(1);
9998     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9999
10000     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10001     Flag = Chain.getValue(1);
10002
10003     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10004                                SPTy).getValue(1);
10005
10006     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10007     return DAG.getMergeValues(Ops1, 2, dl);
10008   }
10009 }
10010
10011 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10012   MachineFunction &MF = DAG.getMachineFunction();
10013   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10014
10015   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10016   DebugLoc DL = Op.getDebugLoc();
10017
10018   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10019     // vastart just stores the address of the VarArgsFrameIndex slot into the
10020     // memory location argument.
10021     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10022                                    getPointerTy());
10023     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10024                         MachinePointerInfo(SV), false, false, 0);
10025   }
10026
10027   // __va_list_tag:
10028   //   gp_offset         (0 - 6 * 8)
10029   //   fp_offset         (48 - 48 + 8 * 16)
10030   //   overflow_arg_area (point to parameters coming in memory).
10031   //   reg_save_area
10032   SmallVector<SDValue, 8> MemOps;
10033   SDValue FIN = Op.getOperand(1);
10034   // Store gp_offset
10035   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10036                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10037                                                MVT::i32),
10038                                FIN, MachinePointerInfo(SV), false, false, 0);
10039   MemOps.push_back(Store);
10040
10041   // Store fp_offset
10042   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10043                     FIN, DAG.getIntPtrConstant(4));
10044   Store = DAG.getStore(Op.getOperand(0), DL,
10045                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10046                                        MVT::i32),
10047                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10048   MemOps.push_back(Store);
10049
10050   // Store ptr to overflow_arg_area
10051   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10052                     FIN, DAG.getIntPtrConstant(4));
10053   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10054                                     getPointerTy());
10055   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10056                        MachinePointerInfo(SV, 8),
10057                        false, false, 0);
10058   MemOps.push_back(Store);
10059
10060   // Store ptr to reg_save_area.
10061   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10062                     FIN, DAG.getIntPtrConstant(8));
10063   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10064                                     getPointerTy());
10065   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10066                        MachinePointerInfo(SV, 16), false, false, 0);
10067   MemOps.push_back(Store);
10068   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10069                      &MemOps[0], MemOps.size());
10070 }
10071
10072 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10073   assert(Subtarget->is64Bit() &&
10074          "LowerVAARG only handles 64-bit va_arg!");
10075   assert((Subtarget->isTargetLinux() ||
10076           Subtarget->isTargetDarwin()) &&
10077           "Unhandled target in LowerVAARG");
10078   assert(Op.getNode()->getNumOperands() == 4);
10079   SDValue Chain = Op.getOperand(0);
10080   SDValue SrcPtr = Op.getOperand(1);
10081   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10082   unsigned Align = Op.getConstantOperandVal(3);
10083   DebugLoc dl = Op.getDebugLoc();
10084
10085   EVT ArgVT = Op.getNode()->getValueType(0);
10086   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10087   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10088   uint8_t ArgMode;
10089
10090   // Decide which area this value should be read from.
10091   // TODO: Implement the AMD64 ABI in its entirety. This simple
10092   // selection mechanism works only for the basic types.
10093   if (ArgVT == MVT::f80) {
10094     llvm_unreachable("va_arg for f80 not yet implemented");
10095   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10096     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10097   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10098     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10099   } else {
10100     llvm_unreachable("Unhandled argument type in LowerVAARG");
10101   }
10102
10103   if (ArgMode == 2) {
10104     // Sanity Check: Make sure using fp_offset makes sense.
10105     assert(!getTargetMachine().Options.UseSoftFloat &&
10106            !(DAG.getMachineFunction()
10107                 .getFunction()->getFnAttributes()
10108                 .hasAttribute(Attribute::NoImplicitFloat)) &&
10109            Subtarget->hasSSE1());
10110   }
10111
10112   // Insert VAARG_64 node into the DAG
10113   // VAARG_64 returns two values: Variable Argument Address, Chain
10114   SmallVector<SDValue, 11> InstOps;
10115   InstOps.push_back(Chain);
10116   InstOps.push_back(SrcPtr);
10117   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10118   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10119   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10120   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10121   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10122                                           VTs, &InstOps[0], InstOps.size(),
10123                                           MVT::i64,
10124                                           MachinePointerInfo(SV),
10125                                           /*Align=*/0,
10126                                           /*Volatile=*/false,
10127                                           /*ReadMem=*/true,
10128                                           /*WriteMem=*/true);
10129   Chain = VAARG.getValue(1);
10130
10131   // Load the next argument and return it
10132   return DAG.getLoad(ArgVT, dl,
10133                      Chain,
10134                      VAARG,
10135                      MachinePointerInfo(),
10136                      false, false, false, 0);
10137 }
10138
10139 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10140                            SelectionDAG &DAG) {
10141   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10142   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10143   SDValue Chain = Op.getOperand(0);
10144   SDValue DstPtr = Op.getOperand(1);
10145   SDValue SrcPtr = Op.getOperand(2);
10146   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10147   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10148   DebugLoc DL = Op.getDebugLoc();
10149
10150   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10151                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10152                        false,
10153                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10154 }
10155
10156 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10157 // may or may not be a constant. Takes immediate version of shift as input.
10158 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10159                                    SDValue SrcOp, SDValue ShAmt,
10160                                    SelectionDAG &DAG) {
10161   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10162
10163   if (isa<ConstantSDNode>(ShAmt)) {
10164     // Constant may be a TargetConstant. Use a regular constant.
10165     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10166     switch (Opc) {
10167       default: llvm_unreachable("Unknown target vector shift node");
10168       case X86ISD::VSHLI:
10169       case X86ISD::VSRLI:
10170       case X86ISD::VSRAI:
10171         return DAG.getNode(Opc, dl, VT, SrcOp,
10172                            DAG.getConstant(ShiftAmt, MVT::i32));
10173     }
10174   }
10175
10176   // Change opcode to non-immediate version
10177   switch (Opc) {
10178     default: llvm_unreachable("Unknown target vector shift node");
10179     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10180     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10181     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10182   }
10183
10184   // Need to build a vector containing shift amount
10185   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10186   SDValue ShOps[4];
10187   ShOps[0] = ShAmt;
10188   ShOps[1] = DAG.getConstant(0, MVT::i32);
10189   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10190   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10191
10192   // The return type has to be a 128-bit type with the same element
10193   // type as the input type.
10194   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10195   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10196
10197   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10198   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10199 }
10200
10201 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10202   DebugLoc dl = Op.getDebugLoc();
10203   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10204   switch (IntNo) {
10205   default: return SDValue();    // Don't custom lower most intrinsics.
10206   // Comparison intrinsics.
10207   case Intrinsic::x86_sse_comieq_ss:
10208   case Intrinsic::x86_sse_comilt_ss:
10209   case Intrinsic::x86_sse_comile_ss:
10210   case Intrinsic::x86_sse_comigt_ss:
10211   case Intrinsic::x86_sse_comige_ss:
10212   case Intrinsic::x86_sse_comineq_ss:
10213   case Intrinsic::x86_sse_ucomieq_ss:
10214   case Intrinsic::x86_sse_ucomilt_ss:
10215   case Intrinsic::x86_sse_ucomile_ss:
10216   case Intrinsic::x86_sse_ucomigt_ss:
10217   case Intrinsic::x86_sse_ucomige_ss:
10218   case Intrinsic::x86_sse_ucomineq_ss:
10219   case Intrinsic::x86_sse2_comieq_sd:
10220   case Intrinsic::x86_sse2_comilt_sd:
10221   case Intrinsic::x86_sse2_comile_sd:
10222   case Intrinsic::x86_sse2_comigt_sd:
10223   case Intrinsic::x86_sse2_comige_sd:
10224   case Intrinsic::x86_sse2_comineq_sd:
10225   case Intrinsic::x86_sse2_ucomieq_sd:
10226   case Intrinsic::x86_sse2_ucomilt_sd:
10227   case Intrinsic::x86_sse2_ucomile_sd:
10228   case Intrinsic::x86_sse2_ucomigt_sd:
10229   case Intrinsic::x86_sse2_ucomige_sd:
10230   case Intrinsic::x86_sse2_ucomineq_sd: {
10231     unsigned Opc;
10232     ISD::CondCode CC;
10233     switch (IntNo) {
10234     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10235     case Intrinsic::x86_sse_comieq_ss:
10236     case Intrinsic::x86_sse2_comieq_sd:
10237       Opc = X86ISD::COMI;
10238       CC = ISD::SETEQ;
10239       break;
10240     case Intrinsic::x86_sse_comilt_ss:
10241     case Intrinsic::x86_sse2_comilt_sd:
10242       Opc = X86ISD::COMI;
10243       CC = ISD::SETLT;
10244       break;
10245     case Intrinsic::x86_sse_comile_ss:
10246     case Intrinsic::x86_sse2_comile_sd:
10247       Opc = X86ISD::COMI;
10248       CC = ISD::SETLE;
10249       break;
10250     case Intrinsic::x86_sse_comigt_ss:
10251     case Intrinsic::x86_sse2_comigt_sd:
10252       Opc = X86ISD::COMI;
10253       CC = ISD::SETGT;
10254       break;
10255     case Intrinsic::x86_sse_comige_ss:
10256     case Intrinsic::x86_sse2_comige_sd:
10257       Opc = X86ISD::COMI;
10258       CC = ISD::SETGE;
10259       break;
10260     case Intrinsic::x86_sse_comineq_ss:
10261     case Intrinsic::x86_sse2_comineq_sd:
10262       Opc = X86ISD::COMI;
10263       CC = ISD::SETNE;
10264       break;
10265     case Intrinsic::x86_sse_ucomieq_ss:
10266     case Intrinsic::x86_sse2_ucomieq_sd:
10267       Opc = X86ISD::UCOMI;
10268       CC = ISD::SETEQ;
10269       break;
10270     case Intrinsic::x86_sse_ucomilt_ss:
10271     case Intrinsic::x86_sse2_ucomilt_sd:
10272       Opc = X86ISD::UCOMI;
10273       CC = ISD::SETLT;
10274       break;
10275     case Intrinsic::x86_sse_ucomile_ss:
10276     case Intrinsic::x86_sse2_ucomile_sd:
10277       Opc = X86ISD::UCOMI;
10278       CC = ISD::SETLE;
10279       break;
10280     case Intrinsic::x86_sse_ucomigt_ss:
10281     case Intrinsic::x86_sse2_ucomigt_sd:
10282       Opc = X86ISD::UCOMI;
10283       CC = ISD::SETGT;
10284       break;
10285     case Intrinsic::x86_sse_ucomige_ss:
10286     case Intrinsic::x86_sse2_ucomige_sd:
10287       Opc = X86ISD::UCOMI;
10288       CC = ISD::SETGE;
10289       break;
10290     case Intrinsic::x86_sse_ucomineq_ss:
10291     case Intrinsic::x86_sse2_ucomineq_sd:
10292       Opc = X86ISD::UCOMI;
10293       CC = ISD::SETNE;
10294       break;
10295     }
10296
10297     SDValue LHS = Op.getOperand(1);
10298     SDValue RHS = Op.getOperand(2);
10299     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10300     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10301     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10302     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10303                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10304     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10305   }
10306
10307   // Arithmetic intrinsics.
10308   case Intrinsic::x86_sse2_pmulu_dq:
10309   case Intrinsic::x86_avx2_pmulu_dq:
10310     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10311                        Op.getOperand(1), Op.getOperand(2));
10312
10313   // SSE2/AVX2 sub with unsigned saturation intrinsics
10314   case Intrinsic::x86_sse2_psubus_b:
10315   case Intrinsic::x86_sse2_psubus_w:
10316   case Intrinsic::x86_avx2_psubus_b:
10317   case Intrinsic::x86_avx2_psubus_w:
10318     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10319                        Op.getOperand(1), Op.getOperand(2));
10320
10321   // SSE3/AVX horizontal add/sub intrinsics
10322   case Intrinsic::x86_sse3_hadd_ps:
10323   case Intrinsic::x86_sse3_hadd_pd:
10324   case Intrinsic::x86_avx_hadd_ps_256:
10325   case Intrinsic::x86_avx_hadd_pd_256:
10326   case Intrinsic::x86_sse3_hsub_ps:
10327   case Intrinsic::x86_sse3_hsub_pd:
10328   case Intrinsic::x86_avx_hsub_ps_256:
10329   case Intrinsic::x86_avx_hsub_pd_256:
10330   case Intrinsic::x86_ssse3_phadd_w_128:
10331   case Intrinsic::x86_ssse3_phadd_d_128:
10332   case Intrinsic::x86_avx2_phadd_w:
10333   case Intrinsic::x86_avx2_phadd_d:
10334   case Intrinsic::x86_ssse3_phsub_w_128:
10335   case Intrinsic::x86_ssse3_phsub_d_128:
10336   case Intrinsic::x86_avx2_phsub_w:
10337   case Intrinsic::x86_avx2_phsub_d: {
10338     unsigned Opcode;
10339     switch (IntNo) {
10340     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10341     case Intrinsic::x86_sse3_hadd_ps:
10342     case Intrinsic::x86_sse3_hadd_pd:
10343     case Intrinsic::x86_avx_hadd_ps_256:
10344     case Intrinsic::x86_avx_hadd_pd_256:
10345       Opcode = X86ISD::FHADD;
10346       break;
10347     case Intrinsic::x86_sse3_hsub_ps:
10348     case Intrinsic::x86_sse3_hsub_pd:
10349     case Intrinsic::x86_avx_hsub_ps_256:
10350     case Intrinsic::x86_avx_hsub_pd_256:
10351       Opcode = X86ISD::FHSUB;
10352       break;
10353     case Intrinsic::x86_ssse3_phadd_w_128:
10354     case Intrinsic::x86_ssse3_phadd_d_128:
10355     case Intrinsic::x86_avx2_phadd_w:
10356     case Intrinsic::x86_avx2_phadd_d:
10357       Opcode = X86ISD::HADD;
10358       break;
10359     case Intrinsic::x86_ssse3_phsub_w_128:
10360     case Intrinsic::x86_ssse3_phsub_d_128:
10361     case Intrinsic::x86_avx2_phsub_w:
10362     case Intrinsic::x86_avx2_phsub_d:
10363       Opcode = X86ISD::HSUB;
10364       break;
10365     }
10366     return DAG.getNode(Opcode, dl, Op.getValueType(),
10367                        Op.getOperand(1), Op.getOperand(2));
10368   }
10369
10370   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10371   case Intrinsic::x86_sse2_pmaxu_b:
10372   case Intrinsic::x86_sse41_pmaxuw:
10373   case Intrinsic::x86_sse41_pmaxud:
10374   case Intrinsic::x86_avx2_pmaxu_b:
10375   case Intrinsic::x86_avx2_pmaxu_w:
10376   case Intrinsic::x86_avx2_pmaxu_d:
10377     return DAG.getNode(X86ISD::UMAX, dl, Op.getValueType(),
10378                        Op.getOperand(1), Op.getOperand(2));
10379   case Intrinsic::x86_sse2_pminu_b:
10380   case Intrinsic::x86_sse41_pminuw:
10381   case Intrinsic::x86_sse41_pminud:
10382   case Intrinsic::x86_avx2_pminu_b:
10383   case Intrinsic::x86_avx2_pminu_w:
10384   case Intrinsic::x86_avx2_pminu_d:
10385     return DAG.getNode(X86ISD::UMIN, dl, Op.getValueType(),
10386                        Op.getOperand(1), Op.getOperand(2));
10387   case Intrinsic::x86_sse41_pmaxsb:
10388   case Intrinsic::x86_sse2_pmaxs_w:
10389   case Intrinsic::x86_sse41_pmaxsd:
10390   case Intrinsic::x86_avx2_pmaxs_b:
10391   case Intrinsic::x86_avx2_pmaxs_w:
10392   case Intrinsic::x86_avx2_pmaxs_d:
10393     return DAG.getNode(X86ISD::SMAX, dl, Op.getValueType(),
10394                        Op.getOperand(1), Op.getOperand(2));
10395   case Intrinsic::x86_sse41_pminsb:
10396   case Intrinsic::x86_sse2_pmins_w:
10397   case Intrinsic::x86_sse41_pminsd:
10398   case Intrinsic::x86_avx2_pmins_b:
10399   case Intrinsic::x86_avx2_pmins_w:
10400   case Intrinsic::x86_avx2_pmins_d:
10401     return DAG.getNode(X86ISD::SMIN, dl, Op.getValueType(),
10402                        Op.getOperand(1), Op.getOperand(2));
10403
10404   // AVX2 variable shift intrinsics
10405   case Intrinsic::x86_avx2_psllv_d:
10406   case Intrinsic::x86_avx2_psllv_q:
10407   case Intrinsic::x86_avx2_psllv_d_256:
10408   case Intrinsic::x86_avx2_psllv_q_256:
10409   case Intrinsic::x86_avx2_psrlv_d:
10410   case Intrinsic::x86_avx2_psrlv_q:
10411   case Intrinsic::x86_avx2_psrlv_d_256:
10412   case Intrinsic::x86_avx2_psrlv_q_256:
10413   case Intrinsic::x86_avx2_psrav_d:
10414   case Intrinsic::x86_avx2_psrav_d_256: {
10415     unsigned Opcode;
10416     switch (IntNo) {
10417     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10418     case Intrinsic::x86_avx2_psllv_d:
10419     case Intrinsic::x86_avx2_psllv_q:
10420     case Intrinsic::x86_avx2_psllv_d_256:
10421     case Intrinsic::x86_avx2_psllv_q_256:
10422       Opcode = ISD::SHL;
10423       break;
10424     case Intrinsic::x86_avx2_psrlv_d:
10425     case Intrinsic::x86_avx2_psrlv_q:
10426     case Intrinsic::x86_avx2_psrlv_d_256:
10427     case Intrinsic::x86_avx2_psrlv_q_256:
10428       Opcode = ISD::SRL;
10429       break;
10430     case Intrinsic::x86_avx2_psrav_d:
10431     case Intrinsic::x86_avx2_psrav_d_256:
10432       Opcode = ISD::SRA;
10433       break;
10434     }
10435     return DAG.getNode(Opcode, dl, Op.getValueType(),
10436                        Op.getOperand(1), Op.getOperand(2));
10437   }
10438
10439   case Intrinsic::x86_ssse3_pshuf_b_128:
10440   case Intrinsic::x86_avx2_pshuf_b:
10441     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10442                        Op.getOperand(1), Op.getOperand(2));
10443
10444   case Intrinsic::x86_ssse3_psign_b_128:
10445   case Intrinsic::x86_ssse3_psign_w_128:
10446   case Intrinsic::x86_ssse3_psign_d_128:
10447   case Intrinsic::x86_avx2_psign_b:
10448   case Intrinsic::x86_avx2_psign_w:
10449   case Intrinsic::x86_avx2_psign_d:
10450     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10451                        Op.getOperand(1), Op.getOperand(2));
10452
10453   case Intrinsic::x86_sse41_insertps:
10454     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10455                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10456
10457   case Intrinsic::x86_avx_vperm2f128_ps_256:
10458   case Intrinsic::x86_avx_vperm2f128_pd_256:
10459   case Intrinsic::x86_avx_vperm2f128_si_256:
10460   case Intrinsic::x86_avx2_vperm2i128:
10461     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10462                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10463
10464   case Intrinsic::x86_avx2_permd:
10465   case Intrinsic::x86_avx2_permps:
10466     // Operands intentionally swapped. Mask is last operand to intrinsic,
10467     // but second operand for node/intruction.
10468     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10469                        Op.getOperand(2), Op.getOperand(1));
10470
10471   // ptest and testp intrinsics. The intrinsic these come from are designed to
10472   // return an integer value, not just an instruction so lower it to the ptest
10473   // or testp pattern and a setcc for the result.
10474   case Intrinsic::x86_sse41_ptestz:
10475   case Intrinsic::x86_sse41_ptestc:
10476   case Intrinsic::x86_sse41_ptestnzc:
10477   case Intrinsic::x86_avx_ptestz_256:
10478   case Intrinsic::x86_avx_ptestc_256:
10479   case Intrinsic::x86_avx_ptestnzc_256:
10480   case Intrinsic::x86_avx_vtestz_ps:
10481   case Intrinsic::x86_avx_vtestc_ps:
10482   case Intrinsic::x86_avx_vtestnzc_ps:
10483   case Intrinsic::x86_avx_vtestz_pd:
10484   case Intrinsic::x86_avx_vtestc_pd:
10485   case Intrinsic::x86_avx_vtestnzc_pd:
10486   case Intrinsic::x86_avx_vtestz_ps_256:
10487   case Intrinsic::x86_avx_vtestc_ps_256:
10488   case Intrinsic::x86_avx_vtestnzc_ps_256:
10489   case Intrinsic::x86_avx_vtestz_pd_256:
10490   case Intrinsic::x86_avx_vtestc_pd_256:
10491   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10492     bool IsTestPacked = false;
10493     unsigned X86CC;
10494     switch (IntNo) {
10495     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10496     case Intrinsic::x86_avx_vtestz_ps:
10497     case Intrinsic::x86_avx_vtestz_pd:
10498     case Intrinsic::x86_avx_vtestz_ps_256:
10499     case Intrinsic::x86_avx_vtestz_pd_256:
10500       IsTestPacked = true; // Fallthrough
10501     case Intrinsic::x86_sse41_ptestz:
10502     case Intrinsic::x86_avx_ptestz_256:
10503       // ZF = 1
10504       X86CC = X86::COND_E;
10505       break;
10506     case Intrinsic::x86_avx_vtestc_ps:
10507     case Intrinsic::x86_avx_vtestc_pd:
10508     case Intrinsic::x86_avx_vtestc_ps_256:
10509     case Intrinsic::x86_avx_vtestc_pd_256:
10510       IsTestPacked = true; // Fallthrough
10511     case Intrinsic::x86_sse41_ptestc:
10512     case Intrinsic::x86_avx_ptestc_256:
10513       // CF = 1
10514       X86CC = X86::COND_B;
10515       break;
10516     case Intrinsic::x86_avx_vtestnzc_ps:
10517     case Intrinsic::x86_avx_vtestnzc_pd:
10518     case Intrinsic::x86_avx_vtestnzc_ps_256:
10519     case Intrinsic::x86_avx_vtestnzc_pd_256:
10520       IsTestPacked = true; // Fallthrough
10521     case Intrinsic::x86_sse41_ptestnzc:
10522     case Intrinsic::x86_avx_ptestnzc_256:
10523       // ZF and CF = 0
10524       X86CC = X86::COND_A;
10525       break;
10526     }
10527
10528     SDValue LHS = Op.getOperand(1);
10529     SDValue RHS = Op.getOperand(2);
10530     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10531     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10532     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10533     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10534     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10535   }
10536
10537   // SSE/AVX shift intrinsics
10538   case Intrinsic::x86_sse2_psll_w:
10539   case Intrinsic::x86_sse2_psll_d:
10540   case Intrinsic::x86_sse2_psll_q:
10541   case Intrinsic::x86_avx2_psll_w:
10542   case Intrinsic::x86_avx2_psll_d:
10543   case Intrinsic::x86_avx2_psll_q:
10544   case Intrinsic::x86_sse2_psrl_w:
10545   case Intrinsic::x86_sse2_psrl_d:
10546   case Intrinsic::x86_sse2_psrl_q:
10547   case Intrinsic::x86_avx2_psrl_w:
10548   case Intrinsic::x86_avx2_psrl_d:
10549   case Intrinsic::x86_avx2_psrl_q:
10550   case Intrinsic::x86_sse2_psra_w:
10551   case Intrinsic::x86_sse2_psra_d:
10552   case Intrinsic::x86_avx2_psra_w:
10553   case Intrinsic::x86_avx2_psra_d: {
10554     unsigned Opcode;
10555     switch (IntNo) {
10556     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10557     case Intrinsic::x86_sse2_psll_w:
10558     case Intrinsic::x86_sse2_psll_d:
10559     case Intrinsic::x86_sse2_psll_q:
10560     case Intrinsic::x86_avx2_psll_w:
10561     case Intrinsic::x86_avx2_psll_d:
10562     case Intrinsic::x86_avx2_psll_q:
10563       Opcode = X86ISD::VSHL;
10564       break;
10565     case Intrinsic::x86_sse2_psrl_w:
10566     case Intrinsic::x86_sse2_psrl_d:
10567     case Intrinsic::x86_sse2_psrl_q:
10568     case Intrinsic::x86_avx2_psrl_w:
10569     case Intrinsic::x86_avx2_psrl_d:
10570     case Intrinsic::x86_avx2_psrl_q:
10571       Opcode = X86ISD::VSRL;
10572       break;
10573     case Intrinsic::x86_sse2_psra_w:
10574     case Intrinsic::x86_sse2_psra_d:
10575     case Intrinsic::x86_avx2_psra_w:
10576     case Intrinsic::x86_avx2_psra_d:
10577       Opcode = X86ISD::VSRA;
10578       break;
10579     }
10580     return DAG.getNode(Opcode, dl, Op.getValueType(),
10581                        Op.getOperand(1), Op.getOperand(2));
10582   }
10583
10584   // SSE/AVX immediate shift intrinsics
10585   case Intrinsic::x86_sse2_pslli_w:
10586   case Intrinsic::x86_sse2_pslli_d:
10587   case Intrinsic::x86_sse2_pslli_q:
10588   case Intrinsic::x86_avx2_pslli_w:
10589   case Intrinsic::x86_avx2_pslli_d:
10590   case Intrinsic::x86_avx2_pslli_q:
10591   case Intrinsic::x86_sse2_psrli_w:
10592   case Intrinsic::x86_sse2_psrli_d:
10593   case Intrinsic::x86_sse2_psrli_q:
10594   case Intrinsic::x86_avx2_psrli_w:
10595   case Intrinsic::x86_avx2_psrli_d:
10596   case Intrinsic::x86_avx2_psrli_q:
10597   case Intrinsic::x86_sse2_psrai_w:
10598   case Intrinsic::x86_sse2_psrai_d:
10599   case Intrinsic::x86_avx2_psrai_w:
10600   case Intrinsic::x86_avx2_psrai_d: {
10601     unsigned Opcode;
10602     switch (IntNo) {
10603     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10604     case Intrinsic::x86_sse2_pslli_w:
10605     case Intrinsic::x86_sse2_pslli_d:
10606     case Intrinsic::x86_sse2_pslli_q:
10607     case Intrinsic::x86_avx2_pslli_w:
10608     case Intrinsic::x86_avx2_pslli_d:
10609     case Intrinsic::x86_avx2_pslli_q:
10610       Opcode = X86ISD::VSHLI;
10611       break;
10612     case Intrinsic::x86_sse2_psrli_w:
10613     case Intrinsic::x86_sse2_psrli_d:
10614     case Intrinsic::x86_sse2_psrli_q:
10615     case Intrinsic::x86_avx2_psrli_w:
10616     case Intrinsic::x86_avx2_psrli_d:
10617     case Intrinsic::x86_avx2_psrli_q:
10618       Opcode = X86ISD::VSRLI;
10619       break;
10620     case Intrinsic::x86_sse2_psrai_w:
10621     case Intrinsic::x86_sse2_psrai_d:
10622     case Intrinsic::x86_avx2_psrai_w:
10623     case Intrinsic::x86_avx2_psrai_d:
10624       Opcode = X86ISD::VSRAI;
10625       break;
10626     }
10627     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10628                                Op.getOperand(1), Op.getOperand(2), DAG);
10629   }
10630
10631   case Intrinsic::x86_sse42_pcmpistria128:
10632   case Intrinsic::x86_sse42_pcmpestria128:
10633   case Intrinsic::x86_sse42_pcmpistric128:
10634   case Intrinsic::x86_sse42_pcmpestric128:
10635   case Intrinsic::x86_sse42_pcmpistrio128:
10636   case Intrinsic::x86_sse42_pcmpestrio128:
10637   case Intrinsic::x86_sse42_pcmpistris128:
10638   case Intrinsic::x86_sse42_pcmpestris128:
10639   case Intrinsic::x86_sse42_pcmpistriz128:
10640   case Intrinsic::x86_sse42_pcmpestriz128: {
10641     unsigned Opcode;
10642     unsigned X86CC;
10643     switch (IntNo) {
10644     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10645     case Intrinsic::x86_sse42_pcmpistria128:
10646       Opcode = X86ISD::PCMPISTRI;
10647       X86CC = X86::COND_A;
10648       break;
10649     case Intrinsic::x86_sse42_pcmpestria128:
10650       Opcode = X86ISD::PCMPESTRI;
10651       X86CC = X86::COND_A;
10652       break;
10653     case Intrinsic::x86_sse42_pcmpistric128:
10654       Opcode = X86ISD::PCMPISTRI;
10655       X86CC = X86::COND_B;
10656       break;
10657     case Intrinsic::x86_sse42_pcmpestric128:
10658       Opcode = X86ISD::PCMPESTRI;
10659       X86CC = X86::COND_B;
10660       break;
10661     case Intrinsic::x86_sse42_pcmpistrio128:
10662       Opcode = X86ISD::PCMPISTRI;
10663       X86CC = X86::COND_O;
10664       break;
10665     case Intrinsic::x86_sse42_pcmpestrio128:
10666       Opcode = X86ISD::PCMPESTRI;
10667       X86CC = X86::COND_O;
10668       break;
10669     case Intrinsic::x86_sse42_pcmpistris128:
10670       Opcode = X86ISD::PCMPISTRI;
10671       X86CC = X86::COND_S;
10672       break;
10673     case Intrinsic::x86_sse42_pcmpestris128:
10674       Opcode = X86ISD::PCMPESTRI;
10675       X86CC = X86::COND_S;
10676       break;
10677     case Intrinsic::x86_sse42_pcmpistriz128:
10678       Opcode = X86ISD::PCMPISTRI;
10679       X86CC = X86::COND_E;
10680       break;
10681     case Intrinsic::x86_sse42_pcmpestriz128:
10682       Opcode = X86ISD::PCMPESTRI;
10683       X86CC = X86::COND_E;
10684       break;
10685     }
10686     SmallVector<SDValue, 5> NewOps;
10687     NewOps.append(Op->op_begin()+1, Op->op_end());
10688     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10689     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10690     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10691                                 DAG.getConstant(X86CC, MVT::i8),
10692                                 SDValue(PCMP.getNode(), 1));
10693     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10694   }
10695
10696   case Intrinsic::x86_sse42_pcmpistri128:
10697   case Intrinsic::x86_sse42_pcmpestri128: {
10698     unsigned Opcode;
10699     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10700       Opcode = X86ISD::PCMPISTRI;
10701     else
10702       Opcode = X86ISD::PCMPESTRI;
10703
10704     SmallVector<SDValue, 5> NewOps;
10705     NewOps.append(Op->op_begin()+1, Op->op_end());
10706     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10707     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10708   }
10709   case Intrinsic::x86_fma_vfmadd_ps:
10710   case Intrinsic::x86_fma_vfmadd_pd:
10711   case Intrinsic::x86_fma_vfmsub_ps:
10712   case Intrinsic::x86_fma_vfmsub_pd:
10713   case Intrinsic::x86_fma_vfnmadd_ps:
10714   case Intrinsic::x86_fma_vfnmadd_pd:
10715   case Intrinsic::x86_fma_vfnmsub_ps:
10716   case Intrinsic::x86_fma_vfnmsub_pd:
10717   case Intrinsic::x86_fma_vfmaddsub_ps:
10718   case Intrinsic::x86_fma_vfmaddsub_pd:
10719   case Intrinsic::x86_fma_vfmsubadd_ps:
10720   case Intrinsic::x86_fma_vfmsubadd_pd:
10721   case Intrinsic::x86_fma_vfmadd_ps_256:
10722   case Intrinsic::x86_fma_vfmadd_pd_256:
10723   case Intrinsic::x86_fma_vfmsub_ps_256:
10724   case Intrinsic::x86_fma_vfmsub_pd_256:
10725   case Intrinsic::x86_fma_vfnmadd_ps_256:
10726   case Intrinsic::x86_fma_vfnmadd_pd_256:
10727   case Intrinsic::x86_fma_vfnmsub_ps_256:
10728   case Intrinsic::x86_fma_vfnmsub_pd_256:
10729   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10730   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10731   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10732   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10733     unsigned Opc;
10734     switch (IntNo) {
10735     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10736     case Intrinsic::x86_fma_vfmadd_ps:
10737     case Intrinsic::x86_fma_vfmadd_pd:
10738     case Intrinsic::x86_fma_vfmadd_ps_256:
10739     case Intrinsic::x86_fma_vfmadd_pd_256:
10740       Opc = X86ISD::FMADD;
10741       break;
10742     case Intrinsic::x86_fma_vfmsub_ps:
10743     case Intrinsic::x86_fma_vfmsub_pd:
10744     case Intrinsic::x86_fma_vfmsub_ps_256:
10745     case Intrinsic::x86_fma_vfmsub_pd_256:
10746       Opc = X86ISD::FMSUB;
10747       break;
10748     case Intrinsic::x86_fma_vfnmadd_ps:
10749     case Intrinsic::x86_fma_vfnmadd_pd:
10750     case Intrinsic::x86_fma_vfnmadd_ps_256:
10751     case Intrinsic::x86_fma_vfnmadd_pd_256:
10752       Opc = X86ISD::FNMADD;
10753       break;
10754     case Intrinsic::x86_fma_vfnmsub_ps:
10755     case Intrinsic::x86_fma_vfnmsub_pd:
10756     case Intrinsic::x86_fma_vfnmsub_ps_256:
10757     case Intrinsic::x86_fma_vfnmsub_pd_256:
10758       Opc = X86ISD::FNMSUB;
10759       break;
10760     case Intrinsic::x86_fma_vfmaddsub_ps:
10761     case Intrinsic::x86_fma_vfmaddsub_pd:
10762     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10763     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10764       Opc = X86ISD::FMADDSUB;
10765       break;
10766     case Intrinsic::x86_fma_vfmsubadd_ps:
10767     case Intrinsic::x86_fma_vfmsubadd_pd:
10768     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10769     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10770       Opc = X86ISD::FMSUBADD;
10771       break;
10772     }
10773
10774     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10775                        Op.getOperand(2), Op.getOperand(3));
10776   }
10777   }
10778 }
10779
10780 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10781   DebugLoc dl = Op.getDebugLoc();
10782   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10783   switch (IntNo) {
10784   default: return SDValue();    // Don't custom lower most intrinsics.
10785
10786   // RDRAND intrinsics.
10787   case Intrinsic::x86_rdrand_16:
10788   case Intrinsic::x86_rdrand_32:
10789   case Intrinsic::x86_rdrand_64: {
10790     // Emit the node with the right value type.
10791     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10792     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10793
10794     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10795     // return the value from Rand, which is always 0, casted to i32.
10796     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10797                       DAG.getConstant(1, Op->getValueType(1)),
10798                       DAG.getConstant(X86::COND_B, MVT::i32),
10799                       SDValue(Result.getNode(), 1) };
10800     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10801                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10802                                   Ops, 4);
10803
10804     // Return { result, isValid, chain }.
10805     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10806                        SDValue(Result.getNode(), 2));
10807   }
10808   }
10809 }
10810
10811 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10812                                            SelectionDAG &DAG) const {
10813   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10814   MFI->setReturnAddressIsTaken(true);
10815
10816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10817   DebugLoc dl = Op.getDebugLoc();
10818   EVT PtrVT = getPointerTy();
10819
10820   if (Depth > 0) {
10821     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10822     SDValue Offset =
10823       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10824     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10825                        DAG.getNode(ISD::ADD, dl, PtrVT,
10826                                    FrameAddr, Offset),
10827                        MachinePointerInfo(), false, false, false, 0);
10828   }
10829
10830   // Just load the return address.
10831   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10832   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10833                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10834 }
10835
10836 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10837   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10838   MFI->setFrameAddressIsTaken(true);
10839
10840   EVT VT = Op.getValueType();
10841   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10842   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10843   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10844   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10845   while (Depth--)
10846     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10847                             MachinePointerInfo(),
10848                             false, false, false, 0);
10849   return FrameAddr;
10850 }
10851
10852 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10853                                                      SelectionDAG &DAG) const {
10854   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10855 }
10856
10857 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10858   SDValue Chain     = Op.getOperand(0);
10859   SDValue Offset    = Op.getOperand(1);
10860   SDValue Handler   = Op.getOperand(2);
10861   DebugLoc dl       = Op.getDebugLoc();
10862
10863   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10864                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10865                                      getPointerTy());
10866   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10867
10868   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10869                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10870   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10871   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10872                        false, false, 0);
10873   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10874
10875   return DAG.getNode(X86ISD::EH_RETURN, dl,
10876                      MVT::Other,
10877                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10878 }
10879
10880 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10881                                                SelectionDAG &DAG) const {
10882   DebugLoc DL = Op.getDebugLoc();
10883   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10884                      DAG.getVTList(MVT::i32, MVT::Other),
10885                      Op.getOperand(0), Op.getOperand(1));
10886 }
10887
10888 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10889                                                 SelectionDAG &DAG) const {
10890   DebugLoc DL = Op.getDebugLoc();
10891   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10892                      Op.getOperand(0), Op.getOperand(1));
10893 }
10894
10895 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10896   return Op.getOperand(0);
10897 }
10898
10899 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10900                                                 SelectionDAG &DAG) const {
10901   SDValue Root = Op.getOperand(0);
10902   SDValue Trmp = Op.getOperand(1); // trampoline
10903   SDValue FPtr = Op.getOperand(2); // nested function
10904   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10905   DebugLoc dl  = Op.getDebugLoc();
10906
10907   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10908   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10909
10910   if (Subtarget->is64Bit()) {
10911     SDValue OutChains[6];
10912
10913     // Large code-model.
10914     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10915     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10916
10917     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10918     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10919
10920     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10921
10922     // Load the pointer to the nested function into R11.
10923     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10924     SDValue Addr = Trmp;
10925     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10926                                 Addr, MachinePointerInfo(TrmpAddr),
10927                                 false, false, 0);
10928
10929     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10930                        DAG.getConstant(2, MVT::i64));
10931     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10932                                 MachinePointerInfo(TrmpAddr, 2),
10933                                 false, false, 2);
10934
10935     // Load the 'nest' parameter value into R10.
10936     // R10 is specified in X86CallingConv.td
10937     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10938     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10939                        DAG.getConstant(10, MVT::i64));
10940     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10941                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10942                                 false, false, 0);
10943
10944     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10945                        DAG.getConstant(12, MVT::i64));
10946     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10947                                 MachinePointerInfo(TrmpAddr, 12),
10948                                 false, false, 2);
10949
10950     // Jump to the nested function.
10951     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10952     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10953                        DAG.getConstant(20, MVT::i64));
10954     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10955                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10956                                 false, false, 0);
10957
10958     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10959     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10960                        DAG.getConstant(22, MVT::i64));
10961     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10962                                 MachinePointerInfo(TrmpAddr, 22),
10963                                 false, false, 0);
10964
10965     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10966   } else {
10967     const Function *Func =
10968       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10969     CallingConv::ID CC = Func->getCallingConv();
10970     unsigned NestReg;
10971
10972     switch (CC) {
10973     default:
10974       llvm_unreachable("Unsupported calling convention");
10975     case CallingConv::C:
10976     case CallingConv::X86_StdCall: {
10977       // Pass 'nest' parameter in ECX.
10978       // Must be kept in sync with X86CallingConv.td
10979       NestReg = X86::ECX;
10980
10981       // Check that ECX wasn't needed by an 'inreg' parameter.
10982       FunctionType *FTy = Func->getFunctionType();
10983       const AttributeSet &Attrs = Func->getAttributes();
10984
10985       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10986         unsigned InRegCount = 0;
10987         unsigned Idx = 1;
10988
10989         for (FunctionType::param_iterator I = FTy->param_begin(),
10990              E = FTy->param_end(); I != E; ++I, ++Idx)
10991           if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
10992             // FIXME: should only count parameters that are lowered to integers.
10993             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10994
10995         if (InRegCount > 2) {
10996           report_fatal_error("Nest register in use - reduce number of inreg"
10997                              " parameters!");
10998         }
10999       }
11000       break;
11001     }
11002     case CallingConv::X86_FastCall:
11003     case CallingConv::X86_ThisCall:
11004     case CallingConv::Fast:
11005       // Pass 'nest' parameter in EAX.
11006       // Must be kept in sync with X86CallingConv.td
11007       NestReg = X86::EAX;
11008       break;
11009     }
11010
11011     SDValue OutChains[4];
11012     SDValue Addr, Disp;
11013
11014     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11015                        DAG.getConstant(10, MVT::i32));
11016     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11017
11018     // This is storing the opcode for MOV32ri.
11019     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11020     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11021     OutChains[0] = DAG.getStore(Root, dl,
11022                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11023                                 Trmp, MachinePointerInfo(TrmpAddr),
11024                                 false, false, 0);
11025
11026     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11027                        DAG.getConstant(1, MVT::i32));
11028     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11029                                 MachinePointerInfo(TrmpAddr, 1),
11030                                 false, false, 1);
11031
11032     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11033     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11034                        DAG.getConstant(5, MVT::i32));
11035     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11036                                 MachinePointerInfo(TrmpAddr, 5),
11037                                 false, false, 1);
11038
11039     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11040                        DAG.getConstant(6, MVT::i32));
11041     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11042                                 MachinePointerInfo(TrmpAddr, 6),
11043                                 false, false, 1);
11044
11045     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11046   }
11047 }
11048
11049 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11050                                             SelectionDAG &DAG) const {
11051   /*
11052    The rounding mode is in bits 11:10 of FPSR, and has the following
11053    settings:
11054      00 Round to nearest
11055      01 Round to -inf
11056      10 Round to +inf
11057      11 Round to 0
11058
11059   FLT_ROUNDS, on the other hand, expects the following:
11060     -1 Undefined
11061      0 Round to 0
11062      1 Round to nearest
11063      2 Round to +inf
11064      3 Round to -inf
11065
11066   To perform the conversion, we do:
11067     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11068   */
11069
11070   MachineFunction &MF = DAG.getMachineFunction();
11071   const TargetMachine &TM = MF.getTarget();
11072   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11073   unsigned StackAlignment = TFI.getStackAlignment();
11074   EVT VT = Op.getValueType();
11075   DebugLoc DL = Op.getDebugLoc();
11076
11077   // Save FP Control Word to stack slot
11078   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11079   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11080
11081   MachineMemOperand *MMO =
11082    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11083                            MachineMemOperand::MOStore, 2, 2);
11084
11085   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11086   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11087                                           DAG.getVTList(MVT::Other),
11088                                           Ops, 2, MVT::i16, MMO);
11089
11090   // Load FP Control Word from stack slot
11091   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11092                             MachinePointerInfo(), false, false, false, 0);
11093
11094   // Transform as necessary
11095   SDValue CWD1 =
11096     DAG.getNode(ISD::SRL, DL, MVT::i16,
11097                 DAG.getNode(ISD::AND, DL, MVT::i16,
11098                             CWD, DAG.getConstant(0x800, MVT::i16)),
11099                 DAG.getConstant(11, MVT::i8));
11100   SDValue CWD2 =
11101     DAG.getNode(ISD::SRL, DL, MVT::i16,
11102                 DAG.getNode(ISD::AND, DL, MVT::i16,
11103                             CWD, DAG.getConstant(0x400, MVT::i16)),
11104                 DAG.getConstant(9, MVT::i8));
11105
11106   SDValue RetVal =
11107     DAG.getNode(ISD::AND, DL, MVT::i16,
11108                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11109                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11110                             DAG.getConstant(1, MVT::i16)),
11111                 DAG.getConstant(3, MVT::i16));
11112
11113   return DAG.getNode((VT.getSizeInBits() < 16 ?
11114                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11115 }
11116
11117 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11118   EVT VT = Op.getValueType();
11119   EVT OpVT = VT;
11120   unsigned NumBits = VT.getSizeInBits();
11121   DebugLoc dl = Op.getDebugLoc();
11122
11123   Op = Op.getOperand(0);
11124   if (VT == MVT::i8) {
11125     // Zero extend to i32 since there is not an i8 bsr.
11126     OpVT = MVT::i32;
11127     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11128   }
11129
11130   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11131   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11132   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11133
11134   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11135   SDValue Ops[] = {
11136     Op,
11137     DAG.getConstant(NumBits+NumBits-1, OpVT),
11138     DAG.getConstant(X86::COND_E, MVT::i8),
11139     Op.getValue(1)
11140   };
11141   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11142
11143   // Finally xor with NumBits-1.
11144   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11145
11146   if (VT == MVT::i8)
11147     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11148   return Op;
11149 }
11150
11151 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11152   EVT VT = Op.getValueType();
11153   EVT OpVT = VT;
11154   unsigned NumBits = VT.getSizeInBits();
11155   DebugLoc dl = Op.getDebugLoc();
11156
11157   Op = Op.getOperand(0);
11158   if (VT == MVT::i8) {
11159     // Zero extend to i32 since there is not an i8 bsr.
11160     OpVT = MVT::i32;
11161     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11162   }
11163
11164   // Issue a bsr (scan bits in reverse).
11165   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11166   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11167
11168   // And xor with NumBits-1.
11169   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11170
11171   if (VT == MVT::i8)
11172     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11173   return Op;
11174 }
11175
11176 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11177   EVT VT = Op.getValueType();
11178   unsigned NumBits = VT.getSizeInBits();
11179   DebugLoc dl = Op.getDebugLoc();
11180   Op = Op.getOperand(0);
11181
11182   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11183   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11184   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11185
11186   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11187   SDValue Ops[] = {
11188     Op,
11189     DAG.getConstant(NumBits, VT),
11190     DAG.getConstant(X86::COND_E, MVT::i8),
11191     Op.getValue(1)
11192   };
11193   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11194 }
11195
11196 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11197 // ones, and then concatenate the result back.
11198 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11199   EVT VT = Op.getValueType();
11200
11201   assert(VT.is256BitVector() && VT.isInteger() &&
11202          "Unsupported value type for operation");
11203
11204   unsigned NumElems = VT.getVectorNumElements();
11205   DebugLoc dl = Op.getDebugLoc();
11206
11207   // Extract the LHS vectors
11208   SDValue LHS = Op.getOperand(0);
11209   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11210   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11211
11212   // Extract the RHS vectors
11213   SDValue RHS = Op.getOperand(1);
11214   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11215   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11216
11217   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11218   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11219
11220   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11221                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11222                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11223 }
11224
11225 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11226   assert(Op.getValueType().is256BitVector() &&
11227          Op.getValueType().isInteger() &&
11228          "Only handle AVX 256-bit vector integer operation");
11229   return Lower256IntArith(Op, DAG);
11230 }
11231
11232 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11233   assert(Op.getValueType().is256BitVector() &&
11234          Op.getValueType().isInteger() &&
11235          "Only handle AVX 256-bit vector integer operation");
11236   return Lower256IntArith(Op, DAG);
11237 }
11238
11239 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11240                         SelectionDAG &DAG) {
11241   DebugLoc dl = Op.getDebugLoc();
11242   EVT VT = Op.getValueType();
11243
11244   // Decompose 256-bit ops into smaller 128-bit ops.
11245   if (VT.is256BitVector() && !Subtarget->hasInt256())
11246     return Lower256IntArith(Op, DAG);
11247
11248   SDValue A = Op.getOperand(0);
11249   SDValue B = Op.getOperand(1);
11250
11251   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11252   if (VT == MVT::v4i32) {
11253     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11254            "Should not custom lower when pmuldq is available!");
11255
11256     // Extract the odd parts.
11257     const int UnpackMask[] = { 1, -1, 3, -1 };
11258     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11259     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11260
11261     // Multiply the even parts.
11262     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11263     // Now multiply odd parts.
11264     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11265
11266     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11267     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11268
11269     // Merge the two vectors back together with a shuffle. This expands into 2
11270     // shuffles.
11271     const int ShufMask[] = { 0, 4, 2, 6 };
11272     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11273   }
11274
11275   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11276          "Only know how to lower V2I64/V4I64 multiply");
11277
11278   //  Ahi = psrlqi(a, 32);
11279   //  Bhi = psrlqi(b, 32);
11280   //
11281   //  AloBlo = pmuludq(a, b);
11282   //  AloBhi = pmuludq(a, Bhi);
11283   //  AhiBlo = pmuludq(Ahi, b);
11284
11285   //  AloBhi = psllqi(AloBhi, 32);
11286   //  AhiBlo = psllqi(AhiBlo, 32);
11287   //  return AloBlo + AloBhi + AhiBlo;
11288
11289   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11290
11291   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11292   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11293
11294   // Bit cast to 32-bit vectors for MULUDQ
11295   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11296   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11297   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11298   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11299   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11300
11301   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11302   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11303   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11304
11305   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11306   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11307
11308   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11309   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11310 }
11311
11312 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11313
11314   EVT VT = Op.getValueType();
11315   DebugLoc dl = Op.getDebugLoc();
11316   SDValue R = Op.getOperand(0);
11317   SDValue Amt = Op.getOperand(1);
11318   LLVMContext *Context = DAG.getContext();
11319
11320   if (!Subtarget->hasSSE2())
11321     return SDValue();
11322
11323   // Optimize shl/srl/sra with constant shift amount.
11324   if (isSplatVector(Amt.getNode())) {
11325     SDValue SclrAmt = Amt->getOperand(0);
11326     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11327       uint64_t ShiftAmt = C->getZExtValue();
11328
11329       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11330           (Subtarget->hasInt256() &&
11331            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11332         if (Op.getOpcode() == ISD::SHL)
11333           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11334                              DAG.getConstant(ShiftAmt, MVT::i32));
11335         if (Op.getOpcode() == ISD::SRL)
11336           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11337                              DAG.getConstant(ShiftAmt, MVT::i32));
11338         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11339           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11340                              DAG.getConstant(ShiftAmt, MVT::i32));
11341       }
11342
11343       if (VT == MVT::v16i8) {
11344         if (Op.getOpcode() == ISD::SHL) {
11345           // Make a large shift.
11346           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11347                                     DAG.getConstant(ShiftAmt, MVT::i32));
11348           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11349           // Zero out the rightmost bits.
11350           SmallVector<SDValue, 16> V(16,
11351                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11352                                                      MVT::i8));
11353           return DAG.getNode(ISD::AND, dl, VT, SHL,
11354                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11355         }
11356         if (Op.getOpcode() == ISD::SRL) {
11357           // Make a large shift.
11358           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11359                                     DAG.getConstant(ShiftAmt, MVT::i32));
11360           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11361           // Zero out the leftmost bits.
11362           SmallVector<SDValue, 16> V(16,
11363                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11364                                                      MVT::i8));
11365           return DAG.getNode(ISD::AND, dl, VT, SRL,
11366                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11367         }
11368         if (Op.getOpcode() == ISD::SRA) {
11369           if (ShiftAmt == 7) {
11370             // R s>> 7  ===  R s< 0
11371             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11372             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11373           }
11374
11375           // R s>> a === ((R u>> a) ^ m) - m
11376           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11377           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11378                                                          MVT::i8));
11379           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11380           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11381           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11382           return Res;
11383         }
11384         llvm_unreachable("Unknown shift opcode.");
11385       }
11386
11387       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11388         if (Op.getOpcode() == ISD::SHL) {
11389           // Make a large shift.
11390           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11391                                     DAG.getConstant(ShiftAmt, MVT::i32));
11392           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11393           // Zero out the rightmost bits.
11394           SmallVector<SDValue, 32> V(32,
11395                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11396                                                      MVT::i8));
11397           return DAG.getNode(ISD::AND, dl, VT, SHL,
11398                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11399         }
11400         if (Op.getOpcode() == ISD::SRL) {
11401           // Make a large shift.
11402           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11403                                     DAG.getConstant(ShiftAmt, MVT::i32));
11404           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11405           // Zero out the leftmost bits.
11406           SmallVector<SDValue, 32> V(32,
11407                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11408                                                      MVT::i8));
11409           return DAG.getNode(ISD::AND, dl, VT, SRL,
11410                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11411         }
11412         if (Op.getOpcode() == ISD::SRA) {
11413           if (ShiftAmt == 7) {
11414             // R s>> 7  ===  R s< 0
11415             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11416             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11417           }
11418
11419           // R s>> a === ((R u>> a) ^ m) - m
11420           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11421           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11422                                                          MVT::i8));
11423           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11424           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11425           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11426           return Res;
11427         }
11428         llvm_unreachable("Unknown shift opcode.");
11429       }
11430     }
11431   }
11432
11433   // Lower SHL with variable shift amount.
11434   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11435     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11436                      DAG.getConstant(23, MVT::i32));
11437
11438     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11439     Constant *C = ConstantDataVector::get(*Context, CV);
11440     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11441     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11442                                  MachinePointerInfo::getConstantPool(),
11443                                  false, false, false, 16);
11444
11445     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11446     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11447     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11448     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11449   }
11450   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11451     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11452
11453     // a = a << 5;
11454     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11455                      DAG.getConstant(5, MVT::i32));
11456     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11457
11458     // Turn 'a' into a mask suitable for VSELECT
11459     SDValue VSelM = DAG.getConstant(0x80, VT);
11460     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11461     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11462
11463     SDValue CM1 = DAG.getConstant(0x0f, VT);
11464     SDValue CM2 = DAG.getConstant(0x3f, VT);
11465
11466     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11467     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11468     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11469                             DAG.getConstant(4, MVT::i32), DAG);
11470     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11471     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11472
11473     // a += a
11474     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11475     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11476     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11477
11478     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11479     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11480     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11481                             DAG.getConstant(2, MVT::i32), DAG);
11482     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11483     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11484
11485     // a += a
11486     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11487     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11488     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11489
11490     // return VSELECT(r, r+r, a);
11491     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11492                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11493     return R;
11494   }
11495
11496   // Decompose 256-bit shifts into smaller 128-bit shifts.
11497   if (VT.is256BitVector()) {
11498     unsigned NumElems = VT.getVectorNumElements();
11499     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11500     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11501
11502     // Extract the two vectors
11503     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11504     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11505
11506     // Recreate the shift amount vectors
11507     SDValue Amt1, Amt2;
11508     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11509       // Constant shift amount
11510       SmallVector<SDValue, 4> Amt1Csts;
11511       SmallVector<SDValue, 4> Amt2Csts;
11512       for (unsigned i = 0; i != NumElems/2; ++i)
11513         Amt1Csts.push_back(Amt->getOperand(i));
11514       for (unsigned i = NumElems/2; i != NumElems; ++i)
11515         Amt2Csts.push_back(Amt->getOperand(i));
11516
11517       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11518                                  &Amt1Csts[0], NumElems/2);
11519       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11520                                  &Amt2Csts[0], NumElems/2);
11521     } else {
11522       // Variable shift amount
11523       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11524       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11525     }
11526
11527     // Issue new vector shifts for the smaller types
11528     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11529     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11530
11531     // Concatenate the result back
11532     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11533   }
11534
11535   return SDValue();
11536 }
11537
11538 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11539   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11540   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11541   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11542   // has only one use.
11543   SDNode *N = Op.getNode();
11544   SDValue LHS = N->getOperand(0);
11545   SDValue RHS = N->getOperand(1);
11546   unsigned BaseOp = 0;
11547   unsigned Cond = 0;
11548   DebugLoc DL = Op.getDebugLoc();
11549   switch (Op.getOpcode()) {
11550   default: llvm_unreachable("Unknown ovf instruction!");
11551   case ISD::SADDO:
11552     // A subtract of one will be selected as a INC. Note that INC doesn't
11553     // set CF, so we can't do this for UADDO.
11554     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11555       if (C->isOne()) {
11556         BaseOp = X86ISD::INC;
11557         Cond = X86::COND_O;
11558         break;
11559       }
11560     BaseOp = X86ISD::ADD;
11561     Cond = X86::COND_O;
11562     break;
11563   case ISD::UADDO:
11564     BaseOp = X86ISD::ADD;
11565     Cond = X86::COND_B;
11566     break;
11567   case ISD::SSUBO:
11568     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11569     // set CF, so we can't do this for USUBO.
11570     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11571       if (C->isOne()) {
11572         BaseOp = X86ISD::DEC;
11573         Cond = X86::COND_O;
11574         break;
11575       }
11576     BaseOp = X86ISD::SUB;
11577     Cond = X86::COND_O;
11578     break;
11579   case ISD::USUBO:
11580     BaseOp = X86ISD::SUB;
11581     Cond = X86::COND_B;
11582     break;
11583   case ISD::SMULO:
11584     BaseOp = X86ISD::SMUL;
11585     Cond = X86::COND_O;
11586     break;
11587   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11588     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11589                                  MVT::i32);
11590     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11591
11592     SDValue SetCC =
11593       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11594                   DAG.getConstant(X86::COND_O, MVT::i32),
11595                   SDValue(Sum.getNode(), 2));
11596
11597     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11598   }
11599   }
11600
11601   // Also sets EFLAGS.
11602   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11603   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11604
11605   SDValue SetCC =
11606     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11607                 DAG.getConstant(Cond, MVT::i32),
11608                 SDValue(Sum.getNode(), 1));
11609
11610   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11611 }
11612
11613 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11614                                                   SelectionDAG &DAG) const {
11615   DebugLoc dl = Op.getDebugLoc();
11616   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11617   EVT VT = Op.getValueType();
11618
11619   if (!Subtarget->hasSSE2() || !VT.isVector())
11620     return SDValue();
11621
11622   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11623                       ExtraVT.getScalarType().getSizeInBits();
11624   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11625
11626   switch (VT.getSimpleVT().SimpleTy) {
11627     default: return SDValue();
11628     case MVT::v8i32:
11629     case MVT::v16i16:
11630       if (!Subtarget->hasFp256())
11631         return SDValue();
11632       if (!Subtarget->hasInt256()) {
11633         // needs to be split
11634         unsigned NumElems = VT.getVectorNumElements();
11635
11636         // Extract the LHS vectors
11637         SDValue LHS = Op.getOperand(0);
11638         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11639         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11640
11641         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11642         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11643
11644         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11645         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11646         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11647                                    ExtraNumElems/2);
11648         SDValue Extra = DAG.getValueType(ExtraVT);
11649
11650         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11651         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11652
11653         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11654       }
11655       // fall through
11656     case MVT::v4i32:
11657     case MVT::v8i16: {
11658       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11659                                          Op.getOperand(0), ShAmt, DAG);
11660       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11661     }
11662   }
11663 }
11664
11665 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11666                               SelectionDAG &DAG) {
11667   DebugLoc dl = Op.getDebugLoc();
11668
11669   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11670   // There isn't any reason to disable it if the target processor supports it.
11671   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11672     SDValue Chain = Op.getOperand(0);
11673     SDValue Zero = DAG.getConstant(0, MVT::i32);
11674     SDValue Ops[] = {
11675       DAG.getRegister(X86::ESP, MVT::i32), // Base
11676       DAG.getTargetConstant(1, MVT::i8),   // Scale
11677       DAG.getRegister(0, MVT::i32),        // Index
11678       DAG.getTargetConstant(0, MVT::i32),  // Disp
11679       DAG.getRegister(0, MVT::i32),        // Segment.
11680       Zero,
11681       Chain
11682     };
11683     SDNode *Res =
11684       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11685                           array_lengthof(Ops));
11686     return SDValue(Res, 0);
11687   }
11688
11689   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11690   if (!isDev)
11691     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11692
11693   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11694   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11695   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11696   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11697
11698   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11699   if (!Op1 && !Op2 && !Op3 && Op4)
11700     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11701
11702   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11703   if (Op1 && !Op2 && !Op3 && !Op4)
11704     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11705
11706   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11707   //           (MFENCE)>;
11708   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11709 }
11710
11711 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11712                                  SelectionDAG &DAG) {
11713   DebugLoc dl = Op.getDebugLoc();
11714   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11715     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11716   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11717     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11718
11719   // The only fence that needs an instruction is a sequentially-consistent
11720   // cross-thread fence.
11721   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11722     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11723     // no-sse2). There isn't any reason to disable it if the target processor
11724     // supports it.
11725     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11726       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11727
11728     SDValue Chain = Op.getOperand(0);
11729     SDValue Zero = DAG.getConstant(0, MVT::i32);
11730     SDValue Ops[] = {
11731       DAG.getRegister(X86::ESP, MVT::i32), // Base
11732       DAG.getTargetConstant(1, MVT::i8),   // Scale
11733       DAG.getRegister(0, MVT::i32),        // Index
11734       DAG.getTargetConstant(0, MVT::i32),  // Disp
11735       DAG.getRegister(0, MVT::i32),        // Segment.
11736       Zero,
11737       Chain
11738     };
11739     SDNode *Res =
11740       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11741                          array_lengthof(Ops));
11742     return SDValue(Res, 0);
11743   }
11744
11745   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11746   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11747 }
11748
11749 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11750                              SelectionDAG &DAG) {
11751   EVT T = Op.getValueType();
11752   DebugLoc DL = Op.getDebugLoc();
11753   unsigned Reg = 0;
11754   unsigned size = 0;
11755   switch(T.getSimpleVT().SimpleTy) {
11756   default: llvm_unreachable("Invalid value type!");
11757   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11758   case MVT::i16: Reg = X86::AX;  size = 2; break;
11759   case MVT::i32: Reg = X86::EAX; size = 4; break;
11760   case MVT::i64:
11761     assert(Subtarget->is64Bit() && "Node not type legal!");
11762     Reg = X86::RAX; size = 8;
11763     break;
11764   }
11765   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11766                                     Op.getOperand(2), SDValue());
11767   SDValue Ops[] = { cpIn.getValue(0),
11768                     Op.getOperand(1),
11769                     Op.getOperand(3),
11770                     DAG.getTargetConstant(size, MVT::i8),
11771                     cpIn.getValue(1) };
11772   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11773   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11774   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11775                                            Ops, 5, T, MMO);
11776   SDValue cpOut =
11777     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11778   return cpOut;
11779 }
11780
11781 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11782                                      SelectionDAG &DAG) {
11783   assert(Subtarget->is64Bit() && "Result not type legalized?");
11784   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11785   SDValue TheChain = Op.getOperand(0);
11786   DebugLoc dl = Op.getDebugLoc();
11787   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11788   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11789   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11790                                    rax.getValue(2));
11791   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11792                             DAG.getConstant(32, MVT::i8));
11793   SDValue Ops[] = {
11794     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11795     rdx.getValue(1)
11796   };
11797   return DAG.getMergeValues(Ops, 2, dl);
11798 }
11799
11800 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11801   EVT SrcVT = Op.getOperand(0).getValueType();
11802   EVT DstVT = Op.getValueType();
11803   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11804          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11805   assert((DstVT == MVT::i64 ||
11806           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11807          "Unexpected custom BITCAST");
11808   // i64 <=> MMX conversions are Legal.
11809   if (SrcVT==MVT::i64 && DstVT.isVector())
11810     return Op;
11811   if (DstVT==MVT::i64 && SrcVT.isVector())
11812     return Op;
11813   // MMX <=> MMX conversions are Legal.
11814   if (SrcVT.isVector() && DstVT.isVector())
11815     return Op;
11816   // All other conversions need to be expanded.
11817   return SDValue();
11818 }
11819
11820 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11821   SDNode *Node = Op.getNode();
11822   DebugLoc dl = Node->getDebugLoc();
11823   EVT T = Node->getValueType(0);
11824   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11825                               DAG.getConstant(0, T), Node->getOperand(2));
11826   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11827                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11828                        Node->getOperand(0),
11829                        Node->getOperand(1), negOp,
11830                        cast<AtomicSDNode>(Node)->getSrcValue(),
11831                        cast<AtomicSDNode>(Node)->getAlignment(),
11832                        cast<AtomicSDNode>(Node)->getOrdering(),
11833                        cast<AtomicSDNode>(Node)->getSynchScope());
11834 }
11835
11836 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11837   SDNode *Node = Op.getNode();
11838   DebugLoc dl = Node->getDebugLoc();
11839   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11840
11841   // Convert seq_cst store -> xchg
11842   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11843   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11844   //        (The only way to get a 16-byte store is cmpxchg16b)
11845   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11846   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11847       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11848     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11849                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11850                                  Node->getOperand(0),
11851                                  Node->getOperand(1), Node->getOperand(2),
11852                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11853                                  cast<AtomicSDNode>(Node)->getOrdering(),
11854                                  cast<AtomicSDNode>(Node)->getSynchScope());
11855     return Swap.getValue(1);
11856   }
11857   // Other atomic stores have a simple pattern.
11858   return Op;
11859 }
11860
11861 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11862   EVT VT = Op.getNode()->getValueType(0);
11863
11864   // Let legalize expand this if it isn't a legal type yet.
11865   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11866     return SDValue();
11867
11868   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11869
11870   unsigned Opc;
11871   bool ExtraOp = false;
11872   switch (Op.getOpcode()) {
11873   default: llvm_unreachable("Invalid code");
11874   case ISD::ADDC: Opc = X86ISD::ADD; break;
11875   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11876   case ISD::SUBC: Opc = X86ISD::SUB; break;
11877   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11878   }
11879
11880   if (!ExtraOp)
11881     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11882                        Op.getOperand(1));
11883   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11884                      Op.getOperand(1), Op.getOperand(2));
11885 }
11886
11887 /// LowerOperation - Provide custom lowering hooks for some operations.
11888 ///
11889 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11890   switch (Op.getOpcode()) {
11891   default: llvm_unreachable("Should not custom lower this!");
11892   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11893   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11894   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11895   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11896   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11897   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11898   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11899   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11900   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11901   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11902   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11903   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11904   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11905   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11906   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11907   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11908   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11909   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11910   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11911   case ISD::SHL_PARTS:
11912   case ISD::SRA_PARTS:
11913   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11914   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11915   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11916   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11917   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
11918   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
11919   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
11920   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11921   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11922   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11923   case ISD::FABS:               return LowerFABS(Op, DAG);
11924   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11925   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11926   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11927   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11928   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11929   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11930   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11931   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11932   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11933   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11934   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11935   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11936   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11937   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11938   case ISD::FRAME_TO_ARGS_OFFSET:
11939                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11940   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11941   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11942   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11943   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11944   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11945   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11946   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11947   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11948   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11949   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11950   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11951   case ISD::SRA:
11952   case ISD::SRL:
11953   case ISD::SHL:                return LowerShift(Op, DAG);
11954   case ISD::SADDO:
11955   case ISD::UADDO:
11956   case ISD::SSUBO:
11957   case ISD::USUBO:
11958   case ISD::SMULO:
11959   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11960   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11961   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11962   case ISD::ADDC:
11963   case ISD::ADDE:
11964   case ISD::SUBC:
11965   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11966   case ISD::ADD:                return LowerADD(Op, DAG);
11967   case ISD::SUB:                return LowerSUB(Op, DAG);
11968   }
11969 }
11970
11971 static void ReplaceATOMIC_LOAD(SDNode *Node,
11972                                   SmallVectorImpl<SDValue> &Results,
11973                                   SelectionDAG &DAG) {
11974   DebugLoc dl = Node->getDebugLoc();
11975   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11976
11977   // Convert wide load -> cmpxchg8b/cmpxchg16b
11978   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11979   //        (The only way to get a 16-byte load is cmpxchg16b)
11980   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11981   SDValue Zero = DAG.getConstant(0, VT);
11982   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11983                                Node->getOperand(0),
11984                                Node->getOperand(1), Zero, Zero,
11985                                cast<AtomicSDNode>(Node)->getMemOperand(),
11986                                cast<AtomicSDNode>(Node)->getOrdering(),
11987                                cast<AtomicSDNode>(Node)->getSynchScope());
11988   Results.push_back(Swap.getValue(0));
11989   Results.push_back(Swap.getValue(1));
11990 }
11991
11992 static void
11993 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11994                         SelectionDAG &DAG, unsigned NewOp) {
11995   DebugLoc dl = Node->getDebugLoc();
11996   assert (Node->getValueType(0) == MVT::i64 &&
11997           "Only know how to expand i64 atomics");
11998
11999   SDValue Chain = Node->getOperand(0);
12000   SDValue In1 = Node->getOperand(1);
12001   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12002                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12003   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12004                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12005   SDValue Ops[] = { Chain, In1, In2L, In2H };
12006   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12007   SDValue Result =
12008     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12009                             cast<MemSDNode>(Node)->getMemOperand());
12010   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12011   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12012   Results.push_back(Result.getValue(2));
12013 }
12014
12015 /// ReplaceNodeResults - Replace a node with an illegal result type
12016 /// with a new node built out of custom code.
12017 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12018                                            SmallVectorImpl<SDValue>&Results,
12019                                            SelectionDAG &DAG) const {
12020   DebugLoc dl = N->getDebugLoc();
12021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12022   switch (N->getOpcode()) {
12023   default:
12024     llvm_unreachable("Do not know how to custom type legalize this operation!");
12025   case ISD::SIGN_EXTEND_INREG:
12026   case ISD::ADDC:
12027   case ISD::ADDE:
12028   case ISD::SUBC:
12029   case ISD::SUBE:
12030     // We don't want to expand or promote these.
12031     return;
12032   case ISD::FP_TO_SINT:
12033   case ISD::FP_TO_UINT: {
12034     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12035
12036     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12037       return;
12038
12039     std::pair<SDValue,SDValue> Vals =
12040         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12041     SDValue FIST = Vals.first, StackSlot = Vals.second;
12042     if (FIST.getNode() != 0) {
12043       EVT VT = N->getValueType(0);
12044       // Return a load from the stack slot.
12045       if (StackSlot.getNode() != 0)
12046         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12047                                       MachinePointerInfo(),
12048                                       false, false, false, 0));
12049       else
12050         Results.push_back(FIST);
12051     }
12052     return;
12053   }
12054   case ISD::UINT_TO_FP: {
12055     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12056         N->getValueType(0) != MVT::v2f32)
12057       return;
12058     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12059                                  N->getOperand(0));
12060     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12061                                      MVT::f64);
12062     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12063     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12064                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12065     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12066     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12067     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12068     return;
12069   }
12070   case ISD::FP_ROUND: {
12071     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12072         return;
12073     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12074     Results.push_back(V);
12075     return;
12076   }
12077   case ISD::READCYCLECOUNTER: {
12078     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12079     SDValue TheChain = N->getOperand(0);
12080     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12081     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12082                                      rd.getValue(1));
12083     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12084                                      eax.getValue(2));
12085     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12086     SDValue Ops[] = { eax, edx };
12087     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12088     Results.push_back(edx.getValue(1));
12089     return;
12090   }
12091   case ISD::ATOMIC_CMP_SWAP: {
12092     EVT T = N->getValueType(0);
12093     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12094     bool Regs64bit = T == MVT::i128;
12095     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12096     SDValue cpInL, cpInH;
12097     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12098                         DAG.getConstant(0, HalfT));
12099     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12100                         DAG.getConstant(1, HalfT));
12101     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12102                              Regs64bit ? X86::RAX : X86::EAX,
12103                              cpInL, SDValue());
12104     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12105                              Regs64bit ? X86::RDX : X86::EDX,
12106                              cpInH, cpInL.getValue(1));
12107     SDValue swapInL, swapInH;
12108     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12109                           DAG.getConstant(0, HalfT));
12110     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12111                           DAG.getConstant(1, HalfT));
12112     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12113                                Regs64bit ? X86::RBX : X86::EBX,
12114                                swapInL, cpInH.getValue(1));
12115     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12116                                Regs64bit ? X86::RCX : X86::ECX,
12117                                swapInH, swapInL.getValue(1));
12118     SDValue Ops[] = { swapInH.getValue(0),
12119                       N->getOperand(1),
12120                       swapInH.getValue(1) };
12121     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12122     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12123     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12124                                   X86ISD::LCMPXCHG8_DAG;
12125     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12126                                              Ops, 3, T, MMO);
12127     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12128                                         Regs64bit ? X86::RAX : X86::EAX,
12129                                         HalfT, Result.getValue(1));
12130     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12131                                         Regs64bit ? X86::RDX : X86::EDX,
12132                                         HalfT, cpOutL.getValue(2));
12133     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12134     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12135     Results.push_back(cpOutH.getValue(1));
12136     return;
12137   }
12138   case ISD::ATOMIC_LOAD_ADD:
12139   case ISD::ATOMIC_LOAD_AND:
12140   case ISD::ATOMIC_LOAD_NAND:
12141   case ISD::ATOMIC_LOAD_OR:
12142   case ISD::ATOMIC_LOAD_SUB:
12143   case ISD::ATOMIC_LOAD_XOR:
12144   case ISD::ATOMIC_LOAD_MAX:
12145   case ISD::ATOMIC_LOAD_MIN:
12146   case ISD::ATOMIC_LOAD_UMAX:
12147   case ISD::ATOMIC_LOAD_UMIN:
12148   case ISD::ATOMIC_SWAP: {
12149     unsigned Opc;
12150     switch (N->getOpcode()) {
12151     default: llvm_unreachable("Unexpected opcode");
12152     case ISD::ATOMIC_LOAD_ADD:
12153       Opc = X86ISD::ATOMADD64_DAG;
12154       break;
12155     case ISD::ATOMIC_LOAD_AND:
12156       Opc = X86ISD::ATOMAND64_DAG;
12157       break;
12158     case ISD::ATOMIC_LOAD_NAND:
12159       Opc = X86ISD::ATOMNAND64_DAG;
12160       break;
12161     case ISD::ATOMIC_LOAD_OR:
12162       Opc = X86ISD::ATOMOR64_DAG;
12163       break;
12164     case ISD::ATOMIC_LOAD_SUB:
12165       Opc = X86ISD::ATOMSUB64_DAG;
12166       break;
12167     case ISD::ATOMIC_LOAD_XOR:
12168       Opc = X86ISD::ATOMXOR64_DAG;
12169       break;
12170     case ISD::ATOMIC_LOAD_MAX:
12171       Opc = X86ISD::ATOMMAX64_DAG;
12172       break;
12173     case ISD::ATOMIC_LOAD_MIN:
12174       Opc = X86ISD::ATOMMIN64_DAG;
12175       break;
12176     case ISD::ATOMIC_LOAD_UMAX:
12177       Opc = X86ISD::ATOMUMAX64_DAG;
12178       break;
12179     case ISD::ATOMIC_LOAD_UMIN:
12180       Opc = X86ISD::ATOMUMIN64_DAG;
12181       break;
12182     case ISD::ATOMIC_SWAP:
12183       Opc = X86ISD::ATOMSWAP64_DAG;
12184       break;
12185     }
12186     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12187     return;
12188   }
12189   case ISD::ATOMIC_LOAD:
12190     ReplaceATOMIC_LOAD(N, Results, DAG);
12191   }
12192 }
12193
12194 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12195   switch (Opcode) {
12196   default: return NULL;
12197   case X86ISD::BSF:                return "X86ISD::BSF";
12198   case X86ISD::BSR:                return "X86ISD::BSR";
12199   case X86ISD::SHLD:               return "X86ISD::SHLD";
12200   case X86ISD::SHRD:               return "X86ISD::SHRD";
12201   case X86ISD::FAND:               return "X86ISD::FAND";
12202   case X86ISD::FOR:                return "X86ISD::FOR";
12203   case X86ISD::FXOR:               return "X86ISD::FXOR";
12204   case X86ISD::FSRL:               return "X86ISD::FSRL";
12205   case X86ISD::FILD:               return "X86ISD::FILD";
12206   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12207   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12208   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12209   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12210   case X86ISD::FLD:                return "X86ISD::FLD";
12211   case X86ISD::FST:                return "X86ISD::FST";
12212   case X86ISD::CALL:               return "X86ISD::CALL";
12213   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12214   case X86ISD::BT:                 return "X86ISD::BT";
12215   case X86ISD::CMP:                return "X86ISD::CMP";
12216   case X86ISD::COMI:               return "X86ISD::COMI";
12217   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12218   case X86ISD::SETCC:              return "X86ISD::SETCC";
12219   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12220   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12221   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12222   case X86ISD::CMOV:               return "X86ISD::CMOV";
12223   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12224   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12225   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12226   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12227   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12228   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12229   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12230   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12231   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12232   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12233   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12234   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12235   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12236   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12237   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12238   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12239   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12240   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12241   case X86ISD::HADD:               return "X86ISD::HADD";
12242   case X86ISD::HSUB:               return "X86ISD::HSUB";
12243   case X86ISD::FHADD:              return "X86ISD::FHADD";
12244   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12245   case X86ISD::UMAX:               return "X86ISD::UMAX";
12246   case X86ISD::UMIN:               return "X86ISD::UMIN";
12247   case X86ISD::SMAX:               return "X86ISD::SMAX";
12248   case X86ISD::SMIN:               return "X86ISD::SMIN";
12249   case X86ISD::FMAX:               return "X86ISD::FMAX";
12250   case X86ISD::FMIN:               return "X86ISD::FMIN";
12251   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12252   case X86ISD::FMINC:              return "X86ISD::FMINC";
12253   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12254   case X86ISD::FRCP:               return "X86ISD::FRCP";
12255   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12256   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12257   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12258   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12259   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12260   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12261   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12262   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12263   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12264   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12265   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12266   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12267   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12268   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12269   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12270   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12271   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12272   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12273   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12274   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12275   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12276   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12277   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12278   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12279   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12280   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12281   case X86ISD::VSHL:               return "X86ISD::VSHL";
12282   case X86ISD::VSRL:               return "X86ISD::VSRL";
12283   case X86ISD::VSRA:               return "X86ISD::VSRA";
12284   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12285   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12286   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12287   case X86ISD::CMPP:               return "X86ISD::CMPP";
12288   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12289   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12290   case X86ISD::ADD:                return "X86ISD::ADD";
12291   case X86ISD::SUB:                return "X86ISD::SUB";
12292   case X86ISD::ADC:                return "X86ISD::ADC";
12293   case X86ISD::SBB:                return "X86ISD::SBB";
12294   case X86ISD::SMUL:               return "X86ISD::SMUL";
12295   case X86ISD::UMUL:               return "X86ISD::UMUL";
12296   case X86ISD::INC:                return "X86ISD::INC";
12297   case X86ISD::DEC:                return "X86ISD::DEC";
12298   case X86ISD::OR:                 return "X86ISD::OR";
12299   case X86ISD::XOR:                return "X86ISD::XOR";
12300   case X86ISD::AND:                return "X86ISD::AND";
12301   case X86ISD::BLSI:               return "X86ISD::BLSI";
12302   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12303   case X86ISD::BLSR:               return "X86ISD::BLSR";
12304   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12305   case X86ISD::PTEST:              return "X86ISD::PTEST";
12306   case X86ISD::TESTP:              return "X86ISD::TESTP";
12307   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12308   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12309   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12310   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12311   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12312   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12313   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12314   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12315   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12316   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12317   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12318   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12319   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12320   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12321   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12322   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12323   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12324   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12325   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12326   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12327   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12328   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12329   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12330   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12331   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12332   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12333   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12334   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12335   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12336   case X86ISD::SAHF:               return "X86ISD::SAHF";
12337   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12338   case X86ISD::FMADD:              return "X86ISD::FMADD";
12339   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12340   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12341   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12342   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12343   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12344   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12345   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12346   }
12347 }
12348
12349 // isLegalAddressingMode - Return true if the addressing mode represented
12350 // by AM is legal for this target, for a load/store of the specified type.
12351 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12352                                               Type *Ty) const {
12353   // X86 supports extremely general addressing modes.
12354   CodeModel::Model M = getTargetMachine().getCodeModel();
12355   Reloc::Model R = getTargetMachine().getRelocationModel();
12356
12357   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12358   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12359     return false;
12360
12361   if (AM.BaseGV) {
12362     unsigned GVFlags =
12363       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12364
12365     // If a reference to this global requires an extra load, we can't fold it.
12366     if (isGlobalStubReference(GVFlags))
12367       return false;
12368
12369     // If BaseGV requires a register for the PIC base, we cannot also have a
12370     // BaseReg specified.
12371     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12372       return false;
12373
12374     // If lower 4G is not available, then we must use rip-relative addressing.
12375     if ((M != CodeModel::Small || R != Reloc::Static) &&
12376         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12377       return false;
12378   }
12379
12380   switch (AM.Scale) {
12381   case 0:
12382   case 1:
12383   case 2:
12384   case 4:
12385   case 8:
12386     // These scales always work.
12387     break;
12388   case 3:
12389   case 5:
12390   case 9:
12391     // These scales are formed with basereg+scalereg.  Only accept if there is
12392     // no basereg yet.
12393     if (AM.HasBaseReg)
12394       return false;
12395     break;
12396   default:  // Other stuff never works.
12397     return false;
12398   }
12399
12400   return true;
12401 }
12402
12403 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12404   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12405     return false;
12406   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12407   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12408   if (NumBits1 <= NumBits2)
12409     return false;
12410   return true;
12411 }
12412
12413 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12414   return Imm == (int32_t)Imm;
12415 }
12416
12417 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12418   // Can also use sub to handle negated immediates.
12419   return Imm == (int32_t)Imm;
12420 }
12421
12422 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12423   if (!VT1.isInteger() || !VT2.isInteger())
12424     return false;
12425   unsigned NumBits1 = VT1.getSizeInBits();
12426   unsigned NumBits2 = VT2.getSizeInBits();
12427   if (NumBits1 <= NumBits2)
12428     return false;
12429   return true;
12430 }
12431
12432 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12433   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12434   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12435 }
12436
12437 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12438   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12439   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12440 }
12441
12442 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12443   EVT VT1 = Val.getValueType();
12444   if (isZExtFree(VT1, VT2))
12445     return true;
12446
12447   if (Val.getOpcode() != ISD::LOAD)
12448     return false;
12449
12450   if (!VT1.isSimple() || !VT1.isInteger() ||
12451       !VT2.isSimple() || !VT2.isInteger())
12452     return false;
12453
12454   switch (VT1.getSimpleVT().SimpleTy) {
12455   default: break;
12456   case MVT::i8:
12457   case MVT::i16:
12458   case MVT::i32:
12459     // X86 has 8, 16, and 32-bit zero-extending loads.
12460     return true;
12461   }
12462
12463   return false;
12464 }
12465
12466 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12467   // i16 instructions are longer (0x66 prefix) and potentially slower.
12468   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12469 }
12470
12471 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12472 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12473 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12474 /// are assumed to be legal.
12475 bool
12476 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12477                                       EVT VT) const {
12478   // Very little shuffling can be done for 64-bit vectors right now.
12479   if (VT.getSizeInBits() == 64)
12480     return false;
12481
12482   // FIXME: pshufb, blends, shifts.
12483   return (VT.getVectorNumElements() == 2 ||
12484           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12485           isMOVLMask(M, VT) ||
12486           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12487           isPSHUFDMask(M, VT) ||
12488           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12489           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12490           isPALIGNRMask(M, VT, Subtarget) ||
12491           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12492           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12493           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12494           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12495 }
12496
12497 bool
12498 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12499                                           EVT VT) const {
12500   unsigned NumElts = VT.getVectorNumElements();
12501   // FIXME: This collection of masks seems suspect.
12502   if (NumElts == 2)
12503     return true;
12504   if (NumElts == 4 && VT.is128BitVector()) {
12505     return (isMOVLMask(Mask, VT)  ||
12506             isCommutedMOVLMask(Mask, VT, true) ||
12507             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12508             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12509   }
12510   return false;
12511 }
12512
12513 //===----------------------------------------------------------------------===//
12514 //                           X86 Scheduler Hooks
12515 //===----------------------------------------------------------------------===//
12516
12517 /// Utility function to emit xbegin specifying the start of an RTM region.
12518 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12519                                      const TargetInstrInfo *TII) {
12520   DebugLoc DL = MI->getDebugLoc();
12521
12522   const BasicBlock *BB = MBB->getBasicBlock();
12523   MachineFunction::iterator I = MBB;
12524   ++I;
12525
12526   // For the v = xbegin(), we generate
12527   //
12528   // thisMBB:
12529   //  xbegin sinkMBB
12530   //
12531   // mainMBB:
12532   //  eax = -1
12533   //
12534   // sinkMBB:
12535   //  v = eax
12536
12537   MachineBasicBlock *thisMBB = MBB;
12538   MachineFunction *MF = MBB->getParent();
12539   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12540   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12541   MF->insert(I, mainMBB);
12542   MF->insert(I, sinkMBB);
12543
12544   // Transfer the remainder of BB and its successor edges to sinkMBB.
12545   sinkMBB->splice(sinkMBB->begin(), MBB,
12546                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12547   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12548
12549   // thisMBB:
12550   //  xbegin sinkMBB
12551   //  # fallthrough to mainMBB
12552   //  # abortion to sinkMBB
12553   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12554   thisMBB->addSuccessor(mainMBB);
12555   thisMBB->addSuccessor(sinkMBB);
12556
12557   // mainMBB:
12558   //  EAX = -1
12559   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12560   mainMBB->addSuccessor(sinkMBB);
12561
12562   // sinkMBB:
12563   // EAX is live into the sinkMBB
12564   sinkMBB->addLiveIn(X86::EAX);
12565   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12566           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12567     .addReg(X86::EAX);
12568
12569   MI->eraseFromParent();
12570   return sinkMBB;
12571 }
12572
12573 // Get CMPXCHG opcode for the specified data type.
12574 static unsigned getCmpXChgOpcode(EVT VT) {
12575   switch (VT.getSimpleVT().SimpleTy) {
12576   case MVT::i8:  return X86::LCMPXCHG8;
12577   case MVT::i16: return X86::LCMPXCHG16;
12578   case MVT::i32: return X86::LCMPXCHG32;
12579   case MVT::i64: return X86::LCMPXCHG64;
12580   default:
12581     break;
12582   }
12583   llvm_unreachable("Invalid operand size!");
12584 }
12585
12586 // Get LOAD opcode for the specified data type.
12587 static unsigned getLoadOpcode(EVT VT) {
12588   switch (VT.getSimpleVT().SimpleTy) {
12589   case MVT::i8:  return X86::MOV8rm;
12590   case MVT::i16: return X86::MOV16rm;
12591   case MVT::i32: return X86::MOV32rm;
12592   case MVT::i64: return X86::MOV64rm;
12593   default:
12594     break;
12595   }
12596   llvm_unreachable("Invalid operand size!");
12597 }
12598
12599 // Get opcode of the non-atomic one from the specified atomic instruction.
12600 static unsigned getNonAtomicOpcode(unsigned Opc) {
12601   switch (Opc) {
12602   case X86::ATOMAND8:  return X86::AND8rr;
12603   case X86::ATOMAND16: return X86::AND16rr;
12604   case X86::ATOMAND32: return X86::AND32rr;
12605   case X86::ATOMAND64: return X86::AND64rr;
12606   case X86::ATOMOR8:   return X86::OR8rr;
12607   case X86::ATOMOR16:  return X86::OR16rr;
12608   case X86::ATOMOR32:  return X86::OR32rr;
12609   case X86::ATOMOR64:  return X86::OR64rr;
12610   case X86::ATOMXOR8:  return X86::XOR8rr;
12611   case X86::ATOMXOR16: return X86::XOR16rr;
12612   case X86::ATOMXOR32: return X86::XOR32rr;
12613   case X86::ATOMXOR64: return X86::XOR64rr;
12614   }
12615   llvm_unreachable("Unhandled atomic-load-op opcode!");
12616 }
12617
12618 // Get opcode of the non-atomic one from the specified atomic instruction with
12619 // extra opcode.
12620 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12621                                                unsigned &ExtraOpc) {
12622   switch (Opc) {
12623   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12624   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12625   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12626   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12627   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12628   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12629   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12630   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12631   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12632   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12633   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12634   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12635   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12636   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12637   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12638   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12639   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12640   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12641   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12642   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12643   }
12644   llvm_unreachable("Unhandled atomic-load-op opcode!");
12645 }
12646
12647 // Get opcode of the non-atomic one from the specified atomic instruction for
12648 // 64-bit data type on 32-bit target.
12649 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12650   switch (Opc) {
12651   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12652   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12653   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12654   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12655   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12656   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12657   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12658   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12659   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12660   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12661   }
12662   llvm_unreachable("Unhandled atomic-load-op opcode!");
12663 }
12664
12665 // Get opcode of the non-atomic one from the specified atomic instruction for
12666 // 64-bit data type on 32-bit target with extra opcode.
12667 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12668                                                    unsigned &HiOpc,
12669                                                    unsigned &ExtraOpc) {
12670   switch (Opc) {
12671   case X86::ATOMNAND6432:
12672     ExtraOpc = X86::NOT32r;
12673     HiOpc = X86::AND32rr;
12674     return X86::AND32rr;
12675   }
12676   llvm_unreachable("Unhandled atomic-load-op opcode!");
12677 }
12678
12679 // Get pseudo CMOV opcode from the specified data type.
12680 static unsigned getPseudoCMOVOpc(EVT VT) {
12681   switch (VT.getSimpleVT().SimpleTy) {
12682   case MVT::i8:  return X86::CMOV_GR8;
12683   case MVT::i16: return X86::CMOV_GR16;
12684   case MVT::i32: return X86::CMOV_GR32;
12685   default:
12686     break;
12687   }
12688   llvm_unreachable("Unknown CMOV opcode!");
12689 }
12690
12691 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12692 // They will be translated into a spin-loop or compare-exchange loop from
12693 //
12694 //    ...
12695 //    dst = atomic-fetch-op MI.addr, MI.val
12696 //    ...
12697 //
12698 // to
12699 //
12700 //    ...
12701 //    EAX = LOAD MI.addr
12702 // loop:
12703 //    t1 = OP MI.val, EAX
12704 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12705 //    JNE loop
12706 // sink:
12707 //    dst = EAX
12708 //    ...
12709 MachineBasicBlock *
12710 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12711                                        MachineBasicBlock *MBB) const {
12712   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12713   DebugLoc DL = MI->getDebugLoc();
12714
12715   MachineFunction *MF = MBB->getParent();
12716   MachineRegisterInfo &MRI = MF->getRegInfo();
12717
12718   const BasicBlock *BB = MBB->getBasicBlock();
12719   MachineFunction::iterator I = MBB;
12720   ++I;
12721
12722   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12723          "Unexpected number of operands");
12724
12725   assert(MI->hasOneMemOperand() &&
12726          "Expected atomic-load-op to have one memoperand");
12727
12728   // Memory Reference
12729   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12730   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12731
12732   unsigned DstReg, SrcReg;
12733   unsigned MemOpndSlot;
12734
12735   unsigned CurOp = 0;
12736
12737   DstReg = MI->getOperand(CurOp++).getReg();
12738   MemOpndSlot = CurOp;
12739   CurOp += X86::AddrNumOperands;
12740   SrcReg = MI->getOperand(CurOp++).getReg();
12741
12742   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12743   MVT::SimpleValueType VT = *RC->vt_begin();
12744   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12745
12746   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12747   unsigned LOADOpc = getLoadOpcode(VT);
12748
12749   // For the atomic load-arith operator, we generate
12750   //
12751   //  thisMBB:
12752   //    EAX = LOAD [MI.addr]
12753   //  mainMBB:
12754   //    t1 = OP MI.val, EAX
12755   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12756   //    JNE mainMBB
12757   //  sinkMBB:
12758
12759   MachineBasicBlock *thisMBB = MBB;
12760   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12761   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12762   MF->insert(I, mainMBB);
12763   MF->insert(I, sinkMBB);
12764
12765   MachineInstrBuilder MIB;
12766
12767   // Transfer the remainder of BB and its successor edges to sinkMBB.
12768   sinkMBB->splice(sinkMBB->begin(), MBB,
12769                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12770   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12771
12772   // thisMBB:
12773   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12774   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12775     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12776   MIB.setMemRefs(MMOBegin, MMOEnd);
12777
12778   thisMBB->addSuccessor(mainMBB);
12779
12780   // mainMBB:
12781   MachineBasicBlock *origMainMBB = mainMBB;
12782   mainMBB->addLiveIn(AccPhyReg);
12783
12784   // Copy AccPhyReg as it is used more than once.
12785   unsigned AccReg = MRI.createVirtualRegister(RC);
12786   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12787     .addReg(AccPhyReg);
12788
12789   unsigned t1 = MRI.createVirtualRegister(RC);
12790   unsigned Opc = MI->getOpcode();
12791   switch (Opc) {
12792   default:
12793     llvm_unreachable("Unhandled atomic-load-op opcode!");
12794   case X86::ATOMAND8:
12795   case X86::ATOMAND16:
12796   case X86::ATOMAND32:
12797   case X86::ATOMAND64:
12798   case X86::ATOMOR8:
12799   case X86::ATOMOR16:
12800   case X86::ATOMOR32:
12801   case X86::ATOMOR64:
12802   case X86::ATOMXOR8:
12803   case X86::ATOMXOR16:
12804   case X86::ATOMXOR32:
12805   case X86::ATOMXOR64: {
12806     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12807     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12808       .addReg(AccReg);
12809     break;
12810   }
12811   case X86::ATOMNAND8:
12812   case X86::ATOMNAND16:
12813   case X86::ATOMNAND32:
12814   case X86::ATOMNAND64: {
12815     unsigned t2 = MRI.createVirtualRegister(RC);
12816     unsigned NOTOpc;
12817     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12818     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12819       .addReg(AccReg);
12820     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12821     break;
12822   }
12823   case X86::ATOMMAX8:
12824   case X86::ATOMMAX16:
12825   case X86::ATOMMAX32:
12826   case X86::ATOMMAX64:
12827   case X86::ATOMMIN8:
12828   case X86::ATOMMIN16:
12829   case X86::ATOMMIN32:
12830   case X86::ATOMMIN64:
12831   case X86::ATOMUMAX8:
12832   case X86::ATOMUMAX16:
12833   case X86::ATOMUMAX32:
12834   case X86::ATOMUMAX64:
12835   case X86::ATOMUMIN8:
12836   case X86::ATOMUMIN16:
12837   case X86::ATOMUMIN32:
12838   case X86::ATOMUMIN64: {
12839     unsigned CMPOpc;
12840     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12841
12842     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12843       .addReg(SrcReg)
12844       .addReg(AccReg);
12845
12846     if (Subtarget->hasCMov()) {
12847       if (VT != MVT::i8) {
12848         // Native support
12849         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12850           .addReg(SrcReg)
12851           .addReg(AccReg);
12852       } else {
12853         // Promote i8 to i32 to use CMOV32
12854         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12855         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12856         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12857         unsigned t2 = MRI.createVirtualRegister(RC32);
12858
12859         unsigned Undef = MRI.createVirtualRegister(RC32);
12860         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12861
12862         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12863           .addReg(Undef)
12864           .addReg(SrcReg)
12865           .addImm(X86::sub_8bit);
12866         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12867           .addReg(Undef)
12868           .addReg(AccReg)
12869           .addImm(X86::sub_8bit);
12870
12871         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12872           .addReg(SrcReg32)
12873           .addReg(AccReg32);
12874
12875         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12876           .addReg(t2, 0, X86::sub_8bit);
12877       }
12878     } else {
12879       // Use pseudo select and lower them.
12880       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12881              "Invalid atomic-load-op transformation!");
12882       unsigned SelOpc = getPseudoCMOVOpc(VT);
12883       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12884       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12885       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12886               .addReg(SrcReg).addReg(AccReg)
12887               .addImm(CC);
12888       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12889     }
12890     break;
12891   }
12892   }
12893
12894   // Copy AccPhyReg back from virtual register.
12895   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12896     .addReg(AccReg);
12897
12898   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12899   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12900     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12901   MIB.addReg(t1);
12902   MIB.setMemRefs(MMOBegin, MMOEnd);
12903
12904   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12905
12906   mainMBB->addSuccessor(origMainMBB);
12907   mainMBB->addSuccessor(sinkMBB);
12908
12909   // sinkMBB:
12910   sinkMBB->addLiveIn(AccPhyReg);
12911
12912   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12913           TII->get(TargetOpcode::COPY), DstReg)
12914     .addReg(AccPhyReg);
12915
12916   MI->eraseFromParent();
12917   return sinkMBB;
12918 }
12919
12920 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12921 // instructions. They will be translated into a spin-loop or compare-exchange
12922 // loop from
12923 //
12924 //    ...
12925 //    dst = atomic-fetch-op MI.addr, MI.val
12926 //    ...
12927 //
12928 // to
12929 //
12930 //    ...
12931 //    EAX = LOAD [MI.addr + 0]
12932 //    EDX = LOAD [MI.addr + 4]
12933 // loop:
12934 //    EBX = OP MI.val.lo, EAX
12935 //    ECX = OP MI.val.hi, EDX
12936 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12937 //    JNE loop
12938 // sink:
12939 //    dst = EDX:EAX
12940 //    ...
12941 MachineBasicBlock *
12942 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12943                                            MachineBasicBlock *MBB) const {
12944   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12945   DebugLoc DL = MI->getDebugLoc();
12946
12947   MachineFunction *MF = MBB->getParent();
12948   MachineRegisterInfo &MRI = MF->getRegInfo();
12949
12950   const BasicBlock *BB = MBB->getBasicBlock();
12951   MachineFunction::iterator I = MBB;
12952   ++I;
12953
12954   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12955          "Unexpected number of operands");
12956
12957   assert(MI->hasOneMemOperand() &&
12958          "Expected atomic-load-op32 to have one memoperand");
12959
12960   // Memory Reference
12961   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12962   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12963
12964   unsigned DstLoReg, DstHiReg;
12965   unsigned SrcLoReg, SrcHiReg;
12966   unsigned MemOpndSlot;
12967
12968   unsigned CurOp = 0;
12969
12970   DstLoReg = MI->getOperand(CurOp++).getReg();
12971   DstHiReg = MI->getOperand(CurOp++).getReg();
12972   MemOpndSlot = CurOp;
12973   CurOp += X86::AddrNumOperands;
12974   SrcLoReg = MI->getOperand(CurOp++).getReg();
12975   SrcHiReg = MI->getOperand(CurOp++).getReg();
12976
12977   const TargetRegisterClass *RC = &X86::GR32RegClass;
12978   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12979
12980   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12981   unsigned LOADOpc = X86::MOV32rm;
12982
12983   // For the atomic load-arith operator, we generate
12984   //
12985   //  thisMBB:
12986   //    EAX = LOAD [MI.addr + 0]
12987   //    EDX = LOAD [MI.addr + 4]
12988   //  mainMBB:
12989   //    EBX = OP MI.vallo, EAX
12990   //    ECX = OP MI.valhi, EDX
12991   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12992   //    JNE mainMBB
12993   //  sinkMBB:
12994
12995   MachineBasicBlock *thisMBB = MBB;
12996   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12997   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12998   MF->insert(I, mainMBB);
12999   MF->insert(I, sinkMBB);
13000
13001   MachineInstrBuilder MIB;
13002
13003   // Transfer the remainder of BB and its successor edges to sinkMBB.
13004   sinkMBB->splice(sinkMBB->begin(), MBB,
13005                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13006   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13007
13008   // thisMBB:
13009   // Lo
13010   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13011   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13012     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13013   MIB.setMemRefs(MMOBegin, MMOEnd);
13014   // Hi
13015   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13016   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13017     if (i == X86::AddrDisp)
13018       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13019     else
13020       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13021   }
13022   MIB.setMemRefs(MMOBegin, MMOEnd);
13023
13024   thisMBB->addSuccessor(mainMBB);
13025
13026   // mainMBB:
13027   MachineBasicBlock *origMainMBB = mainMBB;
13028   mainMBB->addLiveIn(X86::EAX);
13029   mainMBB->addLiveIn(X86::EDX);
13030
13031   // Copy EDX:EAX as they are used more than once.
13032   unsigned LoReg = MRI.createVirtualRegister(RC);
13033   unsigned HiReg = MRI.createVirtualRegister(RC);
13034   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13035   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13036
13037   unsigned t1L = MRI.createVirtualRegister(RC);
13038   unsigned t1H = MRI.createVirtualRegister(RC);
13039
13040   unsigned Opc = MI->getOpcode();
13041   switch (Opc) {
13042   default:
13043     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13044   case X86::ATOMAND6432:
13045   case X86::ATOMOR6432:
13046   case X86::ATOMXOR6432:
13047   case X86::ATOMADD6432:
13048   case X86::ATOMSUB6432: {
13049     unsigned HiOpc;
13050     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13051     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13052     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13053     break;
13054   }
13055   case X86::ATOMNAND6432: {
13056     unsigned HiOpc, NOTOpc;
13057     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13058     unsigned t2L = MRI.createVirtualRegister(RC);
13059     unsigned t2H = MRI.createVirtualRegister(RC);
13060     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13061     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13062     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13063     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13064     break;
13065   }
13066   case X86::ATOMMAX6432:
13067   case X86::ATOMMIN6432:
13068   case X86::ATOMUMAX6432:
13069   case X86::ATOMUMIN6432: {
13070     unsigned HiOpc;
13071     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13072     unsigned cL = MRI.createVirtualRegister(RC8);
13073     unsigned cH = MRI.createVirtualRegister(RC8);
13074     unsigned cL32 = MRI.createVirtualRegister(RC);
13075     unsigned cH32 = MRI.createVirtualRegister(RC);
13076     unsigned cc = MRI.createVirtualRegister(RC);
13077     // cl := cmp src_lo, lo
13078     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13079       .addReg(SrcLoReg).addReg(LoReg);
13080     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13081     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13082     // ch := cmp src_hi, hi
13083     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13084       .addReg(SrcHiReg).addReg(HiReg);
13085     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13086     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13087     // cc := if (src_hi == hi) ? cl : ch;
13088     if (Subtarget->hasCMov()) {
13089       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13090         .addReg(cH32).addReg(cL32);
13091     } else {
13092       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13093               .addReg(cH32).addReg(cL32)
13094               .addImm(X86::COND_E);
13095       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13096     }
13097     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13098     if (Subtarget->hasCMov()) {
13099       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13100         .addReg(SrcLoReg).addReg(LoReg);
13101       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13102         .addReg(SrcHiReg).addReg(HiReg);
13103     } else {
13104       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13105               .addReg(SrcLoReg).addReg(LoReg)
13106               .addImm(X86::COND_NE);
13107       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13108       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13109               .addReg(SrcHiReg).addReg(HiReg)
13110               .addImm(X86::COND_NE);
13111       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13112     }
13113     break;
13114   }
13115   case X86::ATOMSWAP6432: {
13116     unsigned HiOpc;
13117     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13118     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13119     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13120     break;
13121   }
13122   }
13123
13124   // Copy EDX:EAX back from HiReg:LoReg
13125   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13126   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13127   // Copy ECX:EBX from t1H:t1L
13128   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13129   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13130
13131   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13132   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13133     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13134   MIB.setMemRefs(MMOBegin, MMOEnd);
13135
13136   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13137
13138   mainMBB->addSuccessor(origMainMBB);
13139   mainMBB->addSuccessor(sinkMBB);
13140
13141   // sinkMBB:
13142   sinkMBB->addLiveIn(X86::EAX);
13143   sinkMBB->addLiveIn(X86::EDX);
13144
13145   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13146           TII->get(TargetOpcode::COPY), DstLoReg)
13147     .addReg(X86::EAX);
13148   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13149           TII->get(TargetOpcode::COPY), DstHiReg)
13150     .addReg(X86::EDX);
13151
13152   MI->eraseFromParent();
13153   return sinkMBB;
13154 }
13155
13156 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13157 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13158 // in the .td file.
13159 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13160                                        const TargetInstrInfo *TII) {
13161   unsigned Opc;
13162   switch (MI->getOpcode()) {
13163   default: llvm_unreachable("illegal opcode!");
13164   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13165   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13166   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13167   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13168   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13169   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13170   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13171   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13172   }
13173
13174   DebugLoc dl = MI->getDebugLoc();
13175   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13176
13177   unsigned NumArgs = MI->getNumOperands();
13178   for (unsigned i = 1; i < NumArgs; ++i) {
13179     MachineOperand &Op = MI->getOperand(i);
13180     if (!(Op.isReg() && Op.isImplicit()))
13181       MIB.addOperand(Op);
13182   }
13183   if (MI->hasOneMemOperand())
13184     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13185
13186   BuildMI(*BB, MI, dl,
13187     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13188     .addReg(X86::XMM0);
13189
13190   MI->eraseFromParent();
13191   return BB;
13192 }
13193
13194 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13195 // defs in an instruction pattern
13196 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13197                                        const TargetInstrInfo *TII) {
13198   unsigned Opc;
13199   switch (MI->getOpcode()) {
13200   default: llvm_unreachable("illegal opcode!");
13201   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13202   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13203   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13204   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13205   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13206   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13207   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13208   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13209   }
13210
13211   DebugLoc dl = MI->getDebugLoc();
13212   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13213
13214   unsigned NumArgs = MI->getNumOperands(); // remove the results
13215   for (unsigned i = 1; i < NumArgs; ++i) {
13216     MachineOperand &Op = MI->getOperand(i);
13217     if (!(Op.isReg() && Op.isImplicit()))
13218       MIB.addOperand(Op);
13219   }
13220   if (MI->hasOneMemOperand())
13221     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13222
13223   BuildMI(*BB, MI, dl,
13224     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13225     .addReg(X86::ECX);
13226
13227   MI->eraseFromParent();
13228   return BB;
13229 }
13230
13231 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13232                                        const TargetInstrInfo *TII,
13233                                        const X86Subtarget* Subtarget) {
13234   DebugLoc dl = MI->getDebugLoc();
13235
13236   // Address into RAX/EAX, other two args into ECX, EDX.
13237   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13238   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13239   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13240   for (int i = 0; i < X86::AddrNumOperands; ++i)
13241     MIB.addOperand(MI->getOperand(i));
13242
13243   unsigned ValOps = X86::AddrNumOperands;
13244   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13245     .addReg(MI->getOperand(ValOps).getReg());
13246   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13247     .addReg(MI->getOperand(ValOps+1).getReg());
13248
13249   // The instruction doesn't actually take any operands though.
13250   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13251
13252   MI->eraseFromParent(); // The pseudo is gone now.
13253   return BB;
13254 }
13255
13256 MachineBasicBlock *
13257 X86TargetLowering::EmitVAARG64WithCustomInserter(
13258                    MachineInstr *MI,
13259                    MachineBasicBlock *MBB) const {
13260   // Emit va_arg instruction on X86-64.
13261
13262   // Operands to this pseudo-instruction:
13263   // 0  ) Output        : destination address (reg)
13264   // 1-5) Input         : va_list address (addr, i64mem)
13265   // 6  ) ArgSize       : Size (in bytes) of vararg type
13266   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13267   // 8  ) Align         : Alignment of type
13268   // 9  ) EFLAGS (implicit-def)
13269
13270   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13271   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13272
13273   unsigned DestReg = MI->getOperand(0).getReg();
13274   MachineOperand &Base = MI->getOperand(1);
13275   MachineOperand &Scale = MI->getOperand(2);
13276   MachineOperand &Index = MI->getOperand(3);
13277   MachineOperand &Disp = MI->getOperand(4);
13278   MachineOperand &Segment = MI->getOperand(5);
13279   unsigned ArgSize = MI->getOperand(6).getImm();
13280   unsigned ArgMode = MI->getOperand(7).getImm();
13281   unsigned Align = MI->getOperand(8).getImm();
13282
13283   // Memory Reference
13284   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13285   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13286   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13287
13288   // Machine Information
13289   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13290   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13291   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13292   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13293   DebugLoc DL = MI->getDebugLoc();
13294
13295   // struct va_list {
13296   //   i32   gp_offset
13297   //   i32   fp_offset
13298   //   i64   overflow_area (address)
13299   //   i64   reg_save_area (address)
13300   // }
13301   // sizeof(va_list) = 24
13302   // alignment(va_list) = 8
13303
13304   unsigned TotalNumIntRegs = 6;
13305   unsigned TotalNumXMMRegs = 8;
13306   bool UseGPOffset = (ArgMode == 1);
13307   bool UseFPOffset = (ArgMode == 2);
13308   unsigned MaxOffset = TotalNumIntRegs * 8 +
13309                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13310
13311   /* Align ArgSize to a multiple of 8 */
13312   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13313   bool NeedsAlign = (Align > 8);
13314
13315   MachineBasicBlock *thisMBB = MBB;
13316   MachineBasicBlock *overflowMBB;
13317   MachineBasicBlock *offsetMBB;
13318   MachineBasicBlock *endMBB;
13319
13320   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13321   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13322   unsigned OffsetReg = 0;
13323
13324   if (!UseGPOffset && !UseFPOffset) {
13325     // If we only pull from the overflow region, we don't create a branch.
13326     // We don't need to alter control flow.
13327     OffsetDestReg = 0; // unused
13328     OverflowDestReg = DestReg;
13329
13330     offsetMBB = NULL;
13331     overflowMBB = thisMBB;
13332     endMBB = thisMBB;
13333   } else {
13334     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13335     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13336     // If not, pull from overflow_area. (branch to overflowMBB)
13337     //
13338     //       thisMBB
13339     //         |     .
13340     //         |        .
13341     //     offsetMBB   overflowMBB
13342     //         |        .
13343     //         |     .
13344     //        endMBB
13345
13346     // Registers for the PHI in endMBB
13347     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13348     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13349
13350     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13351     MachineFunction *MF = MBB->getParent();
13352     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13353     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13354     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13355
13356     MachineFunction::iterator MBBIter = MBB;
13357     ++MBBIter;
13358
13359     // Insert the new basic blocks
13360     MF->insert(MBBIter, offsetMBB);
13361     MF->insert(MBBIter, overflowMBB);
13362     MF->insert(MBBIter, endMBB);
13363
13364     // Transfer the remainder of MBB and its successor edges to endMBB.
13365     endMBB->splice(endMBB->begin(), thisMBB,
13366                     llvm::next(MachineBasicBlock::iterator(MI)),
13367                     thisMBB->end());
13368     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13369
13370     // Make offsetMBB and overflowMBB successors of thisMBB
13371     thisMBB->addSuccessor(offsetMBB);
13372     thisMBB->addSuccessor(overflowMBB);
13373
13374     // endMBB is a successor of both offsetMBB and overflowMBB
13375     offsetMBB->addSuccessor(endMBB);
13376     overflowMBB->addSuccessor(endMBB);
13377
13378     // Load the offset value into a register
13379     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13380     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13381       .addOperand(Base)
13382       .addOperand(Scale)
13383       .addOperand(Index)
13384       .addDisp(Disp, UseFPOffset ? 4 : 0)
13385       .addOperand(Segment)
13386       .setMemRefs(MMOBegin, MMOEnd);
13387
13388     // Check if there is enough room left to pull this argument.
13389     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13390       .addReg(OffsetReg)
13391       .addImm(MaxOffset + 8 - ArgSizeA8);
13392
13393     // Branch to "overflowMBB" if offset >= max
13394     // Fall through to "offsetMBB" otherwise
13395     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13396       .addMBB(overflowMBB);
13397   }
13398
13399   // In offsetMBB, emit code to use the reg_save_area.
13400   if (offsetMBB) {
13401     assert(OffsetReg != 0);
13402
13403     // Read the reg_save_area address.
13404     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13405     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13406       .addOperand(Base)
13407       .addOperand(Scale)
13408       .addOperand(Index)
13409       .addDisp(Disp, 16)
13410       .addOperand(Segment)
13411       .setMemRefs(MMOBegin, MMOEnd);
13412
13413     // Zero-extend the offset
13414     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13415       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13416         .addImm(0)
13417         .addReg(OffsetReg)
13418         .addImm(X86::sub_32bit);
13419
13420     // Add the offset to the reg_save_area to get the final address.
13421     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13422       .addReg(OffsetReg64)
13423       .addReg(RegSaveReg);
13424
13425     // Compute the offset for the next argument
13426     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13427     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13428       .addReg(OffsetReg)
13429       .addImm(UseFPOffset ? 16 : 8);
13430
13431     // Store it back into the va_list.
13432     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13433       .addOperand(Base)
13434       .addOperand(Scale)
13435       .addOperand(Index)
13436       .addDisp(Disp, UseFPOffset ? 4 : 0)
13437       .addOperand(Segment)
13438       .addReg(NextOffsetReg)
13439       .setMemRefs(MMOBegin, MMOEnd);
13440
13441     // Jump to endMBB
13442     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13443       .addMBB(endMBB);
13444   }
13445
13446   //
13447   // Emit code to use overflow area
13448   //
13449
13450   // Load the overflow_area address into a register.
13451   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13452   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13453     .addOperand(Base)
13454     .addOperand(Scale)
13455     .addOperand(Index)
13456     .addDisp(Disp, 8)
13457     .addOperand(Segment)
13458     .setMemRefs(MMOBegin, MMOEnd);
13459
13460   // If we need to align it, do so. Otherwise, just copy the address
13461   // to OverflowDestReg.
13462   if (NeedsAlign) {
13463     // Align the overflow address
13464     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13465     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13466
13467     // aligned_addr = (addr + (align-1)) & ~(align-1)
13468     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13469       .addReg(OverflowAddrReg)
13470       .addImm(Align-1);
13471
13472     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13473       .addReg(TmpReg)
13474       .addImm(~(uint64_t)(Align-1));
13475   } else {
13476     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13477       .addReg(OverflowAddrReg);
13478   }
13479
13480   // Compute the next overflow address after this argument.
13481   // (the overflow address should be kept 8-byte aligned)
13482   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13483   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13484     .addReg(OverflowDestReg)
13485     .addImm(ArgSizeA8);
13486
13487   // Store the new overflow address.
13488   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13489     .addOperand(Base)
13490     .addOperand(Scale)
13491     .addOperand(Index)
13492     .addDisp(Disp, 8)
13493     .addOperand(Segment)
13494     .addReg(NextAddrReg)
13495     .setMemRefs(MMOBegin, MMOEnd);
13496
13497   // If we branched, emit the PHI to the front of endMBB.
13498   if (offsetMBB) {
13499     BuildMI(*endMBB, endMBB->begin(), DL,
13500             TII->get(X86::PHI), DestReg)
13501       .addReg(OffsetDestReg).addMBB(offsetMBB)
13502       .addReg(OverflowDestReg).addMBB(overflowMBB);
13503   }
13504
13505   // Erase the pseudo instruction
13506   MI->eraseFromParent();
13507
13508   return endMBB;
13509 }
13510
13511 MachineBasicBlock *
13512 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13513                                                  MachineInstr *MI,
13514                                                  MachineBasicBlock *MBB) const {
13515   // Emit code to save XMM registers to the stack. The ABI says that the
13516   // number of registers to save is given in %al, so it's theoretically
13517   // possible to do an indirect jump trick to avoid saving all of them,
13518   // however this code takes a simpler approach and just executes all
13519   // of the stores if %al is non-zero. It's less code, and it's probably
13520   // easier on the hardware branch predictor, and stores aren't all that
13521   // expensive anyway.
13522
13523   // Create the new basic blocks. One block contains all the XMM stores,
13524   // and one block is the final destination regardless of whether any
13525   // stores were performed.
13526   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13527   MachineFunction *F = MBB->getParent();
13528   MachineFunction::iterator MBBIter = MBB;
13529   ++MBBIter;
13530   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13531   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13532   F->insert(MBBIter, XMMSaveMBB);
13533   F->insert(MBBIter, EndMBB);
13534
13535   // Transfer the remainder of MBB and its successor edges to EndMBB.
13536   EndMBB->splice(EndMBB->begin(), MBB,
13537                  llvm::next(MachineBasicBlock::iterator(MI)),
13538                  MBB->end());
13539   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13540
13541   // The original block will now fall through to the XMM save block.
13542   MBB->addSuccessor(XMMSaveMBB);
13543   // The XMMSaveMBB will fall through to the end block.
13544   XMMSaveMBB->addSuccessor(EndMBB);
13545
13546   // Now add the instructions.
13547   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13548   DebugLoc DL = MI->getDebugLoc();
13549
13550   unsigned CountReg = MI->getOperand(0).getReg();
13551   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13552   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13553
13554   if (!Subtarget->isTargetWin64()) {
13555     // If %al is 0, branch around the XMM save block.
13556     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13557     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13558     MBB->addSuccessor(EndMBB);
13559   }
13560
13561   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13562   // In the XMM save block, save all the XMM argument registers.
13563   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13564     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13565     MachineMemOperand *MMO =
13566       F->getMachineMemOperand(
13567           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13568         MachineMemOperand::MOStore,
13569         /*Size=*/16, /*Align=*/16);
13570     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13571       .addFrameIndex(RegSaveFrameIndex)
13572       .addImm(/*Scale=*/1)
13573       .addReg(/*IndexReg=*/0)
13574       .addImm(/*Disp=*/Offset)
13575       .addReg(/*Segment=*/0)
13576       .addReg(MI->getOperand(i).getReg())
13577       .addMemOperand(MMO);
13578   }
13579
13580   MI->eraseFromParent();   // The pseudo instruction is gone now.
13581
13582   return EndMBB;
13583 }
13584
13585 // The EFLAGS operand of SelectItr might be missing a kill marker
13586 // because there were multiple uses of EFLAGS, and ISel didn't know
13587 // which to mark. Figure out whether SelectItr should have had a
13588 // kill marker, and set it if it should. Returns the correct kill
13589 // marker value.
13590 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13591                                      MachineBasicBlock* BB,
13592                                      const TargetRegisterInfo* TRI) {
13593   // Scan forward through BB for a use/def of EFLAGS.
13594   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13595   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13596     const MachineInstr& mi = *miI;
13597     if (mi.readsRegister(X86::EFLAGS))
13598       return false;
13599     if (mi.definesRegister(X86::EFLAGS))
13600       break; // Should have kill-flag - update below.
13601   }
13602
13603   // If we hit the end of the block, check whether EFLAGS is live into a
13604   // successor.
13605   if (miI == BB->end()) {
13606     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13607                                           sEnd = BB->succ_end();
13608          sItr != sEnd; ++sItr) {
13609       MachineBasicBlock* succ = *sItr;
13610       if (succ->isLiveIn(X86::EFLAGS))
13611         return false;
13612     }
13613   }
13614
13615   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13616   // out. SelectMI should have a kill flag on EFLAGS.
13617   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13618   return true;
13619 }
13620
13621 MachineBasicBlock *
13622 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13623                                      MachineBasicBlock *BB) const {
13624   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13625   DebugLoc DL = MI->getDebugLoc();
13626
13627   // To "insert" a SELECT_CC instruction, we actually have to insert the
13628   // diamond control-flow pattern.  The incoming instruction knows the
13629   // destination vreg to set, the condition code register to branch on, the
13630   // true/false values to select between, and a branch opcode to use.
13631   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13632   MachineFunction::iterator It = BB;
13633   ++It;
13634
13635   //  thisMBB:
13636   //  ...
13637   //   TrueVal = ...
13638   //   cmpTY ccX, r1, r2
13639   //   bCC copy1MBB
13640   //   fallthrough --> copy0MBB
13641   MachineBasicBlock *thisMBB = BB;
13642   MachineFunction *F = BB->getParent();
13643   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13644   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13645   F->insert(It, copy0MBB);
13646   F->insert(It, sinkMBB);
13647
13648   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13649   // live into the sink and copy blocks.
13650   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13651   if (!MI->killsRegister(X86::EFLAGS) &&
13652       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13653     copy0MBB->addLiveIn(X86::EFLAGS);
13654     sinkMBB->addLiveIn(X86::EFLAGS);
13655   }
13656
13657   // Transfer the remainder of BB and its successor edges to sinkMBB.
13658   sinkMBB->splice(sinkMBB->begin(), BB,
13659                   llvm::next(MachineBasicBlock::iterator(MI)),
13660                   BB->end());
13661   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13662
13663   // Add the true and fallthrough blocks as its successors.
13664   BB->addSuccessor(copy0MBB);
13665   BB->addSuccessor(sinkMBB);
13666
13667   // Create the conditional branch instruction.
13668   unsigned Opc =
13669     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13670   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13671
13672   //  copy0MBB:
13673   //   %FalseValue = ...
13674   //   # fallthrough to sinkMBB
13675   copy0MBB->addSuccessor(sinkMBB);
13676
13677   //  sinkMBB:
13678   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13679   //  ...
13680   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13681           TII->get(X86::PHI), MI->getOperand(0).getReg())
13682     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13683     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13684
13685   MI->eraseFromParent();   // The pseudo instruction is gone now.
13686   return sinkMBB;
13687 }
13688
13689 MachineBasicBlock *
13690 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13691                                         bool Is64Bit) const {
13692   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13693   DebugLoc DL = MI->getDebugLoc();
13694   MachineFunction *MF = BB->getParent();
13695   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13696
13697   assert(getTargetMachine().Options.EnableSegmentedStacks);
13698
13699   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13700   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13701
13702   // BB:
13703   //  ... [Till the alloca]
13704   // If stacklet is not large enough, jump to mallocMBB
13705   //
13706   // bumpMBB:
13707   //  Allocate by subtracting from RSP
13708   //  Jump to continueMBB
13709   //
13710   // mallocMBB:
13711   //  Allocate by call to runtime
13712   //
13713   // continueMBB:
13714   //  ...
13715   //  [rest of original BB]
13716   //
13717
13718   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13719   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13720   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13721
13722   MachineRegisterInfo &MRI = MF->getRegInfo();
13723   const TargetRegisterClass *AddrRegClass =
13724     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13725
13726   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13727     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13728     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13729     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13730     sizeVReg = MI->getOperand(1).getReg(),
13731     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13732
13733   MachineFunction::iterator MBBIter = BB;
13734   ++MBBIter;
13735
13736   MF->insert(MBBIter, bumpMBB);
13737   MF->insert(MBBIter, mallocMBB);
13738   MF->insert(MBBIter, continueMBB);
13739
13740   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13741                       (MachineBasicBlock::iterator(MI)), BB->end());
13742   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13743
13744   // Add code to the main basic block to check if the stack limit has been hit,
13745   // and if so, jump to mallocMBB otherwise to bumpMBB.
13746   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13747   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13748     .addReg(tmpSPVReg).addReg(sizeVReg);
13749   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13750     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13751     .addReg(SPLimitVReg);
13752   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13753
13754   // bumpMBB simply decreases the stack pointer, since we know the current
13755   // stacklet has enough space.
13756   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13757     .addReg(SPLimitVReg);
13758   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13759     .addReg(SPLimitVReg);
13760   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13761
13762   // Calls into a routine in libgcc to allocate more space from the heap.
13763   const uint32_t *RegMask =
13764     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13765   if (Is64Bit) {
13766     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13767       .addReg(sizeVReg);
13768     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13769       .addExternalSymbol("__morestack_allocate_stack_space")
13770       .addRegMask(RegMask)
13771       .addReg(X86::RDI, RegState::Implicit)
13772       .addReg(X86::RAX, RegState::ImplicitDefine);
13773   } else {
13774     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13775       .addImm(12);
13776     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13777     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13778       .addExternalSymbol("__morestack_allocate_stack_space")
13779       .addRegMask(RegMask)
13780       .addReg(X86::EAX, RegState::ImplicitDefine);
13781   }
13782
13783   if (!Is64Bit)
13784     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13785       .addImm(16);
13786
13787   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13788     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13789   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13790
13791   // Set up the CFG correctly.
13792   BB->addSuccessor(bumpMBB);
13793   BB->addSuccessor(mallocMBB);
13794   mallocMBB->addSuccessor(continueMBB);
13795   bumpMBB->addSuccessor(continueMBB);
13796
13797   // Take care of the PHI nodes.
13798   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13799           MI->getOperand(0).getReg())
13800     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13801     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13802
13803   // Delete the original pseudo instruction.
13804   MI->eraseFromParent();
13805
13806   // And we're done.
13807   return continueMBB;
13808 }
13809
13810 MachineBasicBlock *
13811 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13812                                           MachineBasicBlock *BB) const {
13813   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13814   DebugLoc DL = MI->getDebugLoc();
13815
13816   assert(!Subtarget->isTargetEnvMacho());
13817
13818   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13819   // non-trivial part is impdef of ESP.
13820
13821   if (Subtarget->isTargetWin64()) {
13822     if (Subtarget->isTargetCygMing()) {
13823       // ___chkstk(Mingw64):
13824       // Clobbers R10, R11, RAX and EFLAGS.
13825       // Updates RSP.
13826       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13827         .addExternalSymbol("___chkstk")
13828         .addReg(X86::RAX, RegState::Implicit)
13829         .addReg(X86::RSP, RegState::Implicit)
13830         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13831         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13832         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13833     } else {
13834       // __chkstk(MSVCRT): does not update stack pointer.
13835       // Clobbers R10, R11 and EFLAGS.
13836       // FIXME: RAX(allocated size) might be reused and not killed.
13837       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13838         .addExternalSymbol("__chkstk")
13839         .addReg(X86::RAX, RegState::Implicit)
13840         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13841       // RAX has the offset to subtracted from RSP.
13842       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13843         .addReg(X86::RSP)
13844         .addReg(X86::RAX);
13845     }
13846   } else {
13847     const char *StackProbeSymbol =
13848       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13849
13850     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13851       .addExternalSymbol(StackProbeSymbol)
13852       .addReg(X86::EAX, RegState::Implicit)
13853       .addReg(X86::ESP, RegState::Implicit)
13854       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13855       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13856       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13857   }
13858
13859   MI->eraseFromParent();   // The pseudo instruction is gone now.
13860   return BB;
13861 }
13862
13863 MachineBasicBlock *
13864 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13865                                       MachineBasicBlock *BB) const {
13866   // This is pretty easy.  We're taking the value that we received from
13867   // our load from the relocation, sticking it in either RDI (x86-64)
13868   // or EAX and doing an indirect call.  The return value will then
13869   // be in the normal return register.
13870   const X86InstrInfo *TII
13871     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13872   DebugLoc DL = MI->getDebugLoc();
13873   MachineFunction *F = BB->getParent();
13874
13875   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13876   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13877
13878   // Get a register mask for the lowered call.
13879   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13880   // proper register mask.
13881   const uint32_t *RegMask =
13882     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13883   if (Subtarget->is64Bit()) {
13884     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13885                                       TII->get(X86::MOV64rm), X86::RDI)
13886     .addReg(X86::RIP)
13887     .addImm(0).addReg(0)
13888     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13889                       MI->getOperand(3).getTargetFlags())
13890     .addReg(0);
13891     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13892     addDirectMem(MIB, X86::RDI);
13893     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13894   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13895     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13896                                       TII->get(X86::MOV32rm), X86::EAX)
13897     .addReg(0)
13898     .addImm(0).addReg(0)
13899     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13900                       MI->getOperand(3).getTargetFlags())
13901     .addReg(0);
13902     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13903     addDirectMem(MIB, X86::EAX);
13904     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13905   } else {
13906     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13907                                       TII->get(X86::MOV32rm), X86::EAX)
13908     .addReg(TII->getGlobalBaseReg(F))
13909     .addImm(0).addReg(0)
13910     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13911                       MI->getOperand(3).getTargetFlags())
13912     .addReg(0);
13913     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13914     addDirectMem(MIB, X86::EAX);
13915     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13916   }
13917
13918   MI->eraseFromParent(); // The pseudo instruction is gone now.
13919   return BB;
13920 }
13921
13922 MachineBasicBlock *
13923 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13924                                     MachineBasicBlock *MBB) const {
13925   DebugLoc DL = MI->getDebugLoc();
13926   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13927
13928   MachineFunction *MF = MBB->getParent();
13929   MachineRegisterInfo &MRI = MF->getRegInfo();
13930
13931   const BasicBlock *BB = MBB->getBasicBlock();
13932   MachineFunction::iterator I = MBB;
13933   ++I;
13934
13935   // Memory Reference
13936   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13937   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13938
13939   unsigned DstReg;
13940   unsigned MemOpndSlot = 0;
13941
13942   unsigned CurOp = 0;
13943
13944   DstReg = MI->getOperand(CurOp++).getReg();
13945   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13946   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13947   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13948   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13949
13950   MemOpndSlot = CurOp;
13951
13952   MVT PVT = getPointerTy();
13953   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13954          "Invalid Pointer Size!");
13955
13956   // For v = setjmp(buf), we generate
13957   //
13958   // thisMBB:
13959   //  buf[LabelOffset] = restoreMBB
13960   //  SjLjSetup restoreMBB
13961   //
13962   // mainMBB:
13963   //  v_main = 0
13964   //
13965   // sinkMBB:
13966   //  v = phi(main, restore)
13967   //
13968   // restoreMBB:
13969   //  v_restore = 1
13970
13971   MachineBasicBlock *thisMBB = MBB;
13972   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13973   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13974   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13975   MF->insert(I, mainMBB);
13976   MF->insert(I, sinkMBB);
13977   MF->push_back(restoreMBB);
13978
13979   MachineInstrBuilder MIB;
13980
13981   // Transfer the remainder of BB and its successor edges to sinkMBB.
13982   sinkMBB->splice(sinkMBB->begin(), MBB,
13983                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13984   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13985
13986   // thisMBB:
13987   unsigned PtrStoreOpc = 0;
13988   unsigned LabelReg = 0;
13989   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13990   Reloc::Model RM = getTargetMachine().getRelocationModel();
13991   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13992                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13993
13994   // Prepare IP either in reg or imm.
13995   if (!UseImmLabel) {
13996     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13997     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13998     LabelReg = MRI.createVirtualRegister(PtrRC);
13999     if (Subtarget->is64Bit()) {
14000       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14001               .addReg(X86::RIP)
14002               .addImm(0)
14003               .addReg(0)
14004               .addMBB(restoreMBB)
14005               .addReg(0);
14006     } else {
14007       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14008       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14009               .addReg(XII->getGlobalBaseReg(MF))
14010               .addImm(0)
14011               .addReg(0)
14012               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14013               .addReg(0);
14014     }
14015   } else
14016     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14017   // Store IP
14018   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14019   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14020     if (i == X86::AddrDisp)
14021       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14022     else
14023       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14024   }
14025   if (!UseImmLabel)
14026     MIB.addReg(LabelReg);
14027   else
14028     MIB.addMBB(restoreMBB);
14029   MIB.setMemRefs(MMOBegin, MMOEnd);
14030   // Setup
14031   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14032           .addMBB(restoreMBB);
14033   MIB.addRegMask(RegInfo->getNoPreservedMask());
14034   thisMBB->addSuccessor(mainMBB);
14035   thisMBB->addSuccessor(restoreMBB);
14036
14037   // mainMBB:
14038   //  EAX = 0
14039   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14040   mainMBB->addSuccessor(sinkMBB);
14041
14042   // sinkMBB:
14043   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14044           TII->get(X86::PHI), DstReg)
14045     .addReg(mainDstReg).addMBB(mainMBB)
14046     .addReg(restoreDstReg).addMBB(restoreMBB);
14047
14048   // restoreMBB:
14049   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14050   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14051   restoreMBB->addSuccessor(sinkMBB);
14052
14053   MI->eraseFromParent();
14054   return sinkMBB;
14055 }
14056
14057 MachineBasicBlock *
14058 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14059                                      MachineBasicBlock *MBB) const {
14060   DebugLoc DL = MI->getDebugLoc();
14061   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14062
14063   MachineFunction *MF = MBB->getParent();
14064   MachineRegisterInfo &MRI = MF->getRegInfo();
14065
14066   // Memory Reference
14067   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14068   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14069
14070   MVT PVT = getPointerTy();
14071   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14072          "Invalid Pointer Size!");
14073
14074   const TargetRegisterClass *RC =
14075     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14076   unsigned Tmp = MRI.createVirtualRegister(RC);
14077   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14078   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14079   unsigned SP = RegInfo->getStackRegister();
14080
14081   MachineInstrBuilder MIB;
14082
14083   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14084   const int64_t SPOffset = 2 * PVT.getStoreSize();
14085
14086   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14087   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14088
14089   // Reload FP
14090   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14091   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14092     MIB.addOperand(MI->getOperand(i));
14093   MIB.setMemRefs(MMOBegin, MMOEnd);
14094   // Reload IP
14095   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14096   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14097     if (i == X86::AddrDisp)
14098       MIB.addDisp(MI->getOperand(i), LabelOffset);
14099     else
14100       MIB.addOperand(MI->getOperand(i));
14101   }
14102   MIB.setMemRefs(MMOBegin, MMOEnd);
14103   // Reload SP
14104   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14105   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14106     if (i == X86::AddrDisp)
14107       MIB.addDisp(MI->getOperand(i), SPOffset);
14108     else
14109       MIB.addOperand(MI->getOperand(i));
14110   }
14111   MIB.setMemRefs(MMOBegin, MMOEnd);
14112   // Jump
14113   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14114
14115   MI->eraseFromParent();
14116   return MBB;
14117 }
14118
14119 MachineBasicBlock *
14120 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14121                                                MachineBasicBlock *BB) const {
14122   switch (MI->getOpcode()) {
14123   default: llvm_unreachable("Unexpected instr type to insert");
14124   case X86::TAILJMPd64:
14125   case X86::TAILJMPr64:
14126   case X86::TAILJMPm64:
14127     llvm_unreachable("TAILJMP64 would not be touched here.");
14128   case X86::TCRETURNdi64:
14129   case X86::TCRETURNri64:
14130   case X86::TCRETURNmi64:
14131     return BB;
14132   case X86::WIN_ALLOCA:
14133     return EmitLoweredWinAlloca(MI, BB);
14134   case X86::SEG_ALLOCA_32:
14135     return EmitLoweredSegAlloca(MI, BB, false);
14136   case X86::SEG_ALLOCA_64:
14137     return EmitLoweredSegAlloca(MI, BB, true);
14138   case X86::TLSCall_32:
14139   case X86::TLSCall_64:
14140     return EmitLoweredTLSCall(MI, BB);
14141   case X86::CMOV_GR8:
14142   case X86::CMOV_FR32:
14143   case X86::CMOV_FR64:
14144   case X86::CMOV_V4F32:
14145   case X86::CMOV_V2F64:
14146   case X86::CMOV_V2I64:
14147   case X86::CMOV_V8F32:
14148   case X86::CMOV_V4F64:
14149   case X86::CMOV_V4I64:
14150   case X86::CMOV_GR16:
14151   case X86::CMOV_GR32:
14152   case X86::CMOV_RFP32:
14153   case X86::CMOV_RFP64:
14154   case X86::CMOV_RFP80:
14155     return EmitLoweredSelect(MI, BB);
14156
14157   case X86::FP32_TO_INT16_IN_MEM:
14158   case X86::FP32_TO_INT32_IN_MEM:
14159   case X86::FP32_TO_INT64_IN_MEM:
14160   case X86::FP64_TO_INT16_IN_MEM:
14161   case X86::FP64_TO_INT32_IN_MEM:
14162   case X86::FP64_TO_INT64_IN_MEM:
14163   case X86::FP80_TO_INT16_IN_MEM:
14164   case X86::FP80_TO_INT32_IN_MEM:
14165   case X86::FP80_TO_INT64_IN_MEM: {
14166     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14167     DebugLoc DL = MI->getDebugLoc();
14168
14169     // Change the floating point control register to use "round towards zero"
14170     // mode when truncating to an integer value.
14171     MachineFunction *F = BB->getParent();
14172     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14173     addFrameReference(BuildMI(*BB, MI, DL,
14174                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14175
14176     // Load the old value of the high byte of the control word...
14177     unsigned OldCW =
14178       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14179     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14180                       CWFrameIdx);
14181
14182     // Set the high part to be round to zero...
14183     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14184       .addImm(0xC7F);
14185
14186     // Reload the modified control word now...
14187     addFrameReference(BuildMI(*BB, MI, DL,
14188                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14189
14190     // Restore the memory image of control word to original value
14191     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14192       .addReg(OldCW);
14193
14194     // Get the X86 opcode to use.
14195     unsigned Opc;
14196     switch (MI->getOpcode()) {
14197     default: llvm_unreachable("illegal opcode!");
14198     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14199     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14200     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14201     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14202     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14203     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14204     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14205     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14206     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14207     }
14208
14209     X86AddressMode AM;
14210     MachineOperand &Op = MI->getOperand(0);
14211     if (Op.isReg()) {
14212       AM.BaseType = X86AddressMode::RegBase;
14213       AM.Base.Reg = Op.getReg();
14214     } else {
14215       AM.BaseType = X86AddressMode::FrameIndexBase;
14216       AM.Base.FrameIndex = Op.getIndex();
14217     }
14218     Op = MI->getOperand(1);
14219     if (Op.isImm())
14220       AM.Scale = Op.getImm();
14221     Op = MI->getOperand(2);
14222     if (Op.isImm())
14223       AM.IndexReg = Op.getImm();
14224     Op = MI->getOperand(3);
14225     if (Op.isGlobal()) {
14226       AM.GV = Op.getGlobal();
14227     } else {
14228       AM.Disp = Op.getImm();
14229     }
14230     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14231                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14232
14233     // Reload the original control word now.
14234     addFrameReference(BuildMI(*BB, MI, DL,
14235                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14236
14237     MI->eraseFromParent();   // The pseudo instruction is gone now.
14238     return BB;
14239   }
14240     // String/text processing lowering.
14241   case X86::PCMPISTRM128REG:
14242   case X86::VPCMPISTRM128REG:
14243   case X86::PCMPISTRM128MEM:
14244   case X86::VPCMPISTRM128MEM:
14245   case X86::PCMPESTRM128REG:
14246   case X86::VPCMPESTRM128REG:
14247   case X86::PCMPESTRM128MEM:
14248   case X86::VPCMPESTRM128MEM:
14249     assert(Subtarget->hasSSE42() &&
14250            "Target must have SSE4.2 or AVX features enabled");
14251     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14252
14253   // String/text processing lowering.
14254   case X86::PCMPISTRIREG:
14255   case X86::VPCMPISTRIREG:
14256   case X86::PCMPISTRIMEM:
14257   case X86::VPCMPISTRIMEM:
14258   case X86::PCMPESTRIREG:
14259   case X86::VPCMPESTRIREG:
14260   case X86::PCMPESTRIMEM:
14261   case X86::VPCMPESTRIMEM:
14262     assert(Subtarget->hasSSE42() &&
14263            "Target must have SSE4.2 or AVX features enabled");
14264     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14265
14266   // Thread synchronization.
14267   case X86::MONITOR:
14268     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14269
14270   // xbegin
14271   case X86::XBEGIN:
14272     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14273
14274   // Atomic Lowering.
14275   case X86::ATOMAND8:
14276   case X86::ATOMAND16:
14277   case X86::ATOMAND32:
14278   case X86::ATOMAND64:
14279     // Fall through
14280   case X86::ATOMOR8:
14281   case X86::ATOMOR16:
14282   case X86::ATOMOR32:
14283   case X86::ATOMOR64:
14284     // Fall through
14285   case X86::ATOMXOR16:
14286   case X86::ATOMXOR8:
14287   case X86::ATOMXOR32:
14288   case X86::ATOMXOR64:
14289     // Fall through
14290   case X86::ATOMNAND8:
14291   case X86::ATOMNAND16:
14292   case X86::ATOMNAND32:
14293   case X86::ATOMNAND64:
14294     // Fall through
14295   case X86::ATOMMAX8:
14296   case X86::ATOMMAX16:
14297   case X86::ATOMMAX32:
14298   case X86::ATOMMAX64:
14299     // Fall through
14300   case X86::ATOMMIN8:
14301   case X86::ATOMMIN16:
14302   case X86::ATOMMIN32:
14303   case X86::ATOMMIN64:
14304     // Fall through
14305   case X86::ATOMUMAX8:
14306   case X86::ATOMUMAX16:
14307   case X86::ATOMUMAX32:
14308   case X86::ATOMUMAX64:
14309     // Fall through
14310   case X86::ATOMUMIN8:
14311   case X86::ATOMUMIN16:
14312   case X86::ATOMUMIN32:
14313   case X86::ATOMUMIN64:
14314     return EmitAtomicLoadArith(MI, BB);
14315
14316   // This group does 64-bit operations on a 32-bit host.
14317   case X86::ATOMAND6432:
14318   case X86::ATOMOR6432:
14319   case X86::ATOMXOR6432:
14320   case X86::ATOMNAND6432:
14321   case X86::ATOMADD6432:
14322   case X86::ATOMSUB6432:
14323   case X86::ATOMMAX6432:
14324   case X86::ATOMMIN6432:
14325   case X86::ATOMUMAX6432:
14326   case X86::ATOMUMIN6432:
14327   case X86::ATOMSWAP6432:
14328     return EmitAtomicLoadArith6432(MI, BB);
14329
14330   case X86::VASTART_SAVE_XMM_REGS:
14331     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14332
14333   case X86::VAARG_64:
14334     return EmitVAARG64WithCustomInserter(MI, BB);
14335
14336   case X86::EH_SjLj_SetJmp32:
14337   case X86::EH_SjLj_SetJmp64:
14338     return emitEHSjLjSetJmp(MI, BB);
14339
14340   case X86::EH_SjLj_LongJmp32:
14341   case X86::EH_SjLj_LongJmp64:
14342     return emitEHSjLjLongJmp(MI, BB);
14343   }
14344 }
14345
14346 //===----------------------------------------------------------------------===//
14347 //                           X86 Optimization Hooks
14348 //===----------------------------------------------------------------------===//
14349
14350 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14351                                                        APInt &KnownZero,
14352                                                        APInt &KnownOne,
14353                                                        const SelectionDAG &DAG,
14354                                                        unsigned Depth) const {
14355   unsigned BitWidth = KnownZero.getBitWidth();
14356   unsigned Opc = Op.getOpcode();
14357   assert((Opc >= ISD::BUILTIN_OP_END ||
14358           Opc == ISD::INTRINSIC_WO_CHAIN ||
14359           Opc == ISD::INTRINSIC_W_CHAIN ||
14360           Opc == ISD::INTRINSIC_VOID) &&
14361          "Should use MaskedValueIsZero if you don't know whether Op"
14362          " is a target node!");
14363
14364   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14365   switch (Opc) {
14366   default: break;
14367   case X86ISD::ADD:
14368   case X86ISD::SUB:
14369   case X86ISD::ADC:
14370   case X86ISD::SBB:
14371   case X86ISD::SMUL:
14372   case X86ISD::UMUL:
14373   case X86ISD::INC:
14374   case X86ISD::DEC:
14375   case X86ISD::OR:
14376   case X86ISD::XOR:
14377   case X86ISD::AND:
14378     // These nodes' second result is a boolean.
14379     if (Op.getResNo() == 0)
14380       break;
14381     // Fallthrough
14382   case X86ISD::SETCC:
14383     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14384     break;
14385   case ISD::INTRINSIC_WO_CHAIN: {
14386     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14387     unsigned NumLoBits = 0;
14388     switch (IntId) {
14389     default: break;
14390     case Intrinsic::x86_sse_movmsk_ps:
14391     case Intrinsic::x86_avx_movmsk_ps_256:
14392     case Intrinsic::x86_sse2_movmsk_pd:
14393     case Intrinsic::x86_avx_movmsk_pd_256:
14394     case Intrinsic::x86_mmx_pmovmskb:
14395     case Intrinsic::x86_sse2_pmovmskb_128:
14396     case Intrinsic::x86_avx2_pmovmskb: {
14397       // High bits of movmskp{s|d}, pmovmskb are known zero.
14398       switch (IntId) {
14399         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14400         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14401         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14402         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14403         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14404         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14405         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14406         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14407       }
14408       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14409       break;
14410     }
14411     }
14412     break;
14413   }
14414   }
14415 }
14416
14417 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14418                                                          unsigned Depth) const {
14419   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14420   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14421     return Op.getValueType().getScalarType().getSizeInBits();
14422
14423   // Fallback case.
14424   return 1;
14425 }
14426
14427 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14428 /// node is a GlobalAddress + offset.
14429 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14430                                        const GlobalValue* &GA,
14431                                        int64_t &Offset) const {
14432   if (N->getOpcode() == X86ISD::Wrapper) {
14433     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14434       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14435       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14436       return true;
14437     }
14438   }
14439   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14440 }
14441
14442 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14443 /// same as extracting the high 128-bit part of 256-bit vector and then
14444 /// inserting the result into the low part of a new 256-bit vector
14445 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14446   EVT VT = SVOp->getValueType(0);
14447   unsigned NumElems = VT.getVectorNumElements();
14448
14449   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14450   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14451     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14452         SVOp->getMaskElt(j) >= 0)
14453       return false;
14454
14455   return true;
14456 }
14457
14458 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14459 /// same as extracting the low 128-bit part of 256-bit vector and then
14460 /// inserting the result into the high part of a new 256-bit vector
14461 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14462   EVT VT = SVOp->getValueType(0);
14463   unsigned NumElems = VT.getVectorNumElements();
14464
14465   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14466   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14467     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14468         SVOp->getMaskElt(j) >= 0)
14469       return false;
14470
14471   return true;
14472 }
14473
14474 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14475 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14476                                         TargetLowering::DAGCombinerInfo &DCI,
14477                                         const X86Subtarget* Subtarget) {
14478   DebugLoc dl = N->getDebugLoc();
14479   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14480   SDValue V1 = SVOp->getOperand(0);
14481   SDValue V2 = SVOp->getOperand(1);
14482   EVT VT = SVOp->getValueType(0);
14483   unsigned NumElems = VT.getVectorNumElements();
14484
14485   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14486       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14487     //
14488     //                   0,0,0,...
14489     //                      |
14490     //    V      UNDEF    BUILD_VECTOR    UNDEF
14491     //     \      /           \           /
14492     //  CONCAT_VECTOR         CONCAT_VECTOR
14493     //         \                  /
14494     //          \                /
14495     //          RESULT: V + zero extended
14496     //
14497     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14498         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14499         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14500       return SDValue();
14501
14502     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14503       return SDValue();
14504
14505     // To match the shuffle mask, the first half of the mask should
14506     // be exactly the first vector, and all the rest a splat with the
14507     // first element of the second one.
14508     for (unsigned i = 0; i != NumElems/2; ++i)
14509       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14510           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14511         return SDValue();
14512
14513     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14514     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14515       if (Ld->hasNUsesOfValue(1, 0)) {
14516         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14517         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14518         SDValue ResNode =
14519           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14520                                   Ld->getMemoryVT(),
14521                                   Ld->getPointerInfo(),
14522                                   Ld->getAlignment(),
14523                                   false/*isVolatile*/, true/*ReadMem*/,
14524                                   false/*WriteMem*/);
14525
14526         // Make sure the newly-created LOAD is in the same position as Ld in
14527         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14528         // and update uses of Ld's output chain to use the TokenFactor.
14529         if (Ld->hasAnyUseOfValue(1)) {
14530           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14531                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14532           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14533           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14534                                  SDValue(ResNode.getNode(), 1));
14535         }
14536
14537         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14538       }
14539     }
14540
14541     // Emit a zeroed vector and insert the desired subvector on its
14542     // first half.
14543     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14544     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14545     return DCI.CombineTo(N, InsV);
14546   }
14547
14548   //===--------------------------------------------------------------------===//
14549   // Combine some shuffles into subvector extracts and inserts:
14550   //
14551
14552   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14553   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14554     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14555     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14556     return DCI.CombineTo(N, InsV);
14557   }
14558
14559   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14560   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14561     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14562     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14563     return DCI.CombineTo(N, InsV);
14564   }
14565
14566   return SDValue();
14567 }
14568
14569 /// PerformShuffleCombine - Performs several different shuffle combines.
14570 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14571                                      TargetLowering::DAGCombinerInfo &DCI,
14572                                      const X86Subtarget *Subtarget) {
14573   DebugLoc dl = N->getDebugLoc();
14574   EVT VT = N->getValueType(0);
14575
14576   // Don't create instructions with illegal types after legalize types has run.
14577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14578   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14579     return SDValue();
14580
14581   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14582   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14583       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14584     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14585
14586   // Only handle 128 wide vector from here on.
14587   if (!VT.is128BitVector())
14588     return SDValue();
14589
14590   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14591   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14592   // consecutive, non-overlapping, and in the right order.
14593   SmallVector<SDValue, 16> Elts;
14594   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14595     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14596
14597   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14598 }
14599
14600 /// PerformTruncateCombine - Converts truncate operation to
14601 /// a sequence of vector shuffle operations.
14602 /// It is possible when we truncate 256-bit vector to 128-bit vector
14603 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14604                                       TargetLowering::DAGCombinerInfo &DCI,
14605                                       const X86Subtarget *Subtarget)  {
14606   return SDValue();
14607 }
14608
14609 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14610 /// specific shuffle of a load can be folded into a single element load.
14611 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14612 /// shuffles have been customed lowered so we need to handle those here.
14613 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14614                                          TargetLowering::DAGCombinerInfo &DCI) {
14615   if (DCI.isBeforeLegalizeOps())
14616     return SDValue();
14617
14618   SDValue InVec = N->getOperand(0);
14619   SDValue EltNo = N->getOperand(1);
14620
14621   if (!isa<ConstantSDNode>(EltNo))
14622     return SDValue();
14623
14624   EVT VT = InVec.getValueType();
14625
14626   bool HasShuffleIntoBitcast = false;
14627   if (InVec.getOpcode() == ISD::BITCAST) {
14628     // Don't duplicate a load with other uses.
14629     if (!InVec.hasOneUse())
14630       return SDValue();
14631     EVT BCVT = InVec.getOperand(0).getValueType();
14632     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14633       return SDValue();
14634     InVec = InVec.getOperand(0);
14635     HasShuffleIntoBitcast = true;
14636   }
14637
14638   if (!isTargetShuffle(InVec.getOpcode()))
14639     return SDValue();
14640
14641   // Don't duplicate a load with other uses.
14642   if (!InVec.hasOneUse())
14643     return SDValue();
14644
14645   SmallVector<int, 16> ShuffleMask;
14646   bool UnaryShuffle;
14647   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14648                             UnaryShuffle))
14649     return SDValue();
14650
14651   // Select the input vector, guarding against out of range extract vector.
14652   unsigned NumElems = VT.getVectorNumElements();
14653   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14654   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14655   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14656                                          : InVec.getOperand(1);
14657
14658   // If inputs to shuffle are the same for both ops, then allow 2 uses
14659   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14660
14661   if (LdNode.getOpcode() == ISD::BITCAST) {
14662     // Don't duplicate a load with other uses.
14663     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14664       return SDValue();
14665
14666     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14667     LdNode = LdNode.getOperand(0);
14668   }
14669
14670   if (!ISD::isNormalLoad(LdNode.getNode()))
14671     return SDValue();
14672
14673   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14674
14675   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14676     return SDValue();
14677
14678   if (HasShuffleIntoBitcast) {
14679     // If there's a bitcast before the shuffle, check if the load type and
14680     // alignment is valid.
14681     unsigned Align = LN0->getAlignment();
14682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14683     unsigned NewAlign = TLI.getDataLayout()->
14684       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14685
14686     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14687       return SDValue();
14688   }
14689
14690   // All checks match so transform back to vector_shuffle so that DAG combiner
14691   // can finish the job
14692   DebugLoc dl = N->getDebugLoc();
14693
14694   // Create shuffle node taking into account the case that its a unary shuffle
14695   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14696   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14697                                  InVec.getOperand(0), Shuffle,
14698                                  &ShuffleMask[0]);
14699   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14700   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14701                      EltNo);
14702 }
14703
14704 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14705 /// generation and convert it from being a bunch of shuffles and extracts
14706 /// to a simple store and scalar loads to extract the elements.
14707 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14708                                          TargetLowering::DAGCombinerInfo &DCI) {
14709   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14710   if (NewOp.getNode())
14711     return NewOp;
14712
14713   SDValue InputVector = N->getOperand(0);
14714   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14715   // from mmx to v2i32 has a single usage.
14716   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14717       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14718       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14719     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14720                        N->getValueType(0),
14721                        InputVector.getNode()->getOperand(0));
14722
14723   // Only operate on vectors of 4 elements, where the alternative shuffling
14724   // gets to be more expensive.
14725   if (InputVector.getValueType() != MVT::v4i32)
14726     return SDValue();
14727
14728   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14729   // single use which is a sign-extend or zero-extend, and all elements are
14730   // used.
14731   SmallVector<SDNode *, 4> Uses;
14732   unsigned ExtractedElements = 0;
14733   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14734        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14735     if (UI.getUse().getResNo() != InputVector.getResNo())
14736       return SDValue();
14737
14738     SDNode *Extract = *UI;
14739     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14740       return SDValue();
14741
14742     if (Extract->getValueType(0) != MVT::i32)
14743       return SDValue();
14744     if (!Extract->hasOneUse())
14745       return SDValue();
14746     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14747         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14748       return SDValue();
14749     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14750       return SDValue();
14751
14752     // Record which element was extracted.
14753     ExtractedElements |=
14754       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14755
14756     Uses.push_back(Extract);
14757   }
14758
14759   // If not all the elements were used, this may not be worthwhile.
14760   if (ExtractedElements != 15)
14761     return SDValue();
14762
14763   // Ok, we've now decided to do the transformation.
14764   DebugLoc dl = InputVector.getDebugLoc();
14765
14766   // Store the value to a temporary stack slot.
14767   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14768   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14769                             MachinePointerInfo(), false, false, 0);
14770
14771   // Replace each use (extract) with a load of the appropriate element.
14772   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14773        UE = Uses.end(); UI != UE; ++UI) {
14774     SDNode *Extract = *UI;
14775
14776     // cOMpute the element's address.
14777     SDValue Idx = Extract->getOperand(1);
14778     unsigned EltSize =
14779         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14780     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14781     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14782     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14783
14784     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14785                                      StackPtr, OffsetVal);
14786
14787     // Load the scalar.
14788     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14789                                      ScalarAddr, MachinePointerInfo(),
14790                                      false, false, false, 0);
14791
14792     // Replace the exact with the load.
14793     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14794   }
14795
14796   // The replacement was made in place; don't return anything.
14797   return SDValue();
14798 }
14799
14800 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14801 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14802                                    SDValue RHS, SelectionDAG &DAG,
14803                                    const X86Subtarget *Subtarget) {
14804   if (!VT.isVector())
14805     return 0;
14806
14807   switch (VT.getSimpleVT().SimpleTy) {
14808   default: return 0;
14809   case MVT::v32i8:
14810   case MVT::v16i16:
14811   case MVT::v8i32:
14812     if (!Subtarget->hasAVX2())
14813       return 0;
14814   case MVT::v16i8:
14815   case MVT::v8i16:
14816   case MVT::v4i32:
14817     if (!Subtarget->hasSSE2())
14818       return 0;
14819   }
14820
14821   // SSE2 has only a small subset of the operations.
14822   bool hasUnsigned = Subtarget->hasSSE41() ||
14823                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
14824   bool hasSigned = Subtarget->hasSSE41() ||
14825                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
14826
14827   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14828
14829   // Check for x CC y ? x : y.
14830   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14831       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14832     switch (CC) {
14833     default: break;
14834     case ISD::SETULT:
14835     case ISD::SETULE:
14836       return hasUnsigned ? X86ISD::UMIN : 0;
14837     case ISD::SETUGT:
14838     case ISD::SETUGE:
14839       return hasUnsigned ? X86ISD::UMAX : 0;
14840     case ISD::SETLT:
14841     case ISD::SETLE:
14842       return hasSigned ? X86ISD::SMIN : 0;
14843     case ISD::SETGT:
14844     case ISD::SETGE:
14845       return hasSigned ? X86ISD::SMAX : 0;
14846     }
14847   // Check for x CC y ? y : x -- a min/max with reversed arms.
14848   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14849              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14850     switch (CC) {
14851     default: break;
14852     case ISD::SETULT:
14853     case ISD::SETULE:
14854       return hasUnsigned ? X86ISD::UMAX : 0;
14855     case ISD::SETUGT:
14856     case ISD::SETUGE:
14857       return hasUnsigned ? X86ISD::UMIN : 0;
14858     case ISD::SETLT:
14859     case ISD::SETLE:
14860       return hasSigned ? X86ISD::SMAX : 0;
14861     case ISD::SETGT:
14862     case ISD::SETGE:
14863       return hasSigned ? X86ISD::SMIN : 0;
14864     }
14865   }
14866
14867   return 0;
14868 }
14869
14870 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14871 /// nodes.
14872 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14873                                     TargetLowering::DAGCombinerInfo &DCI,
14874                                     const X86Subtarget *Subtarget) {
14875   DebugLoc DL = N->getDebugLoc();
14876   SDValue Cond = N->getOperand(0);
14877   // Get the LHS/RHS of the select.
14878   SDValue LHS = N->getOperand(1);
14879   SDValue RHS = N->getOperand(2);
14880   EVT VT = LHS.getValueType();
14881
14882   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14883   // instructions match the semantics of the common C idiom x<y?x:y but not
14884   // x<=y?x:y, because of how they handle negative zero (which can be
14885   // ignored in unsafe-math mode).
14886   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14887       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14888       (Subtarget->hasSSE2() ||
14889        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14890     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14891
14892     unsigned Opcode = 0;
14893     // Check for x CC y ? x : y.
14894     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14895         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14896       switch (CC) {
14897       default: break;
14898       case ISD::SETULT:
14899         // Converting this to a min would handle NaNs incorrectly, and swapping
14900         // the operands would cause it to handle comparisons between positive
14901         // and negative zero incorrectly.
14902         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14903           if (!DAG.getTarget().Options.UnsafeFPMath &&
14904               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14905             break;
14906           std::swap(LHS, RHS);
14907         }
14908         Opcode = X86ISD::FMIN;
14909         break;
14910       case ISD::SETOLE:
14911         // Converting this to a min would handle comparisons between positive
14912         // and negative zero incorrectly.
14913         if (!DAG.getTarget().Options.UnsafeFPMath &&
14914             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14915           break;
14916         Opcode = X86ISD::FMIN;
14917         break;
14918       case ISD::SETULE:
14919         // Converting this to a min would handle both negative zeros and NaNs
14920         // incorrectly, but we can swap the operands to fix both.
14921         std::swap(LHS, RHS);
14922       case ISD::SETOLT:
14923       case ISD::SETLT:
14924       case ISD::SETLE:
14925         Opcode = X86ISD::FMIN;
14926         break;
14927
14928       case ISD::SETOGE:
14929         // Converting this to a max would handle comparisons between positive
14930         // and negative zero incorrectly.
14931         if (!DAG.getTarget().Options.UnsafeFPMath &&
14932             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14933           break;
14934         Opcode = X86ISD::FMAX;
14935         break;
14936       case ISD::SETUGT:
14937         // Converting this to a max would handle NaNs incorrectly, and swapping
14938         // the operands would cause it to handle comparisons between positive
14939         // and negative zero incorrectly.
14940         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14941           if (!DAG.getTarget().Options.UnsafeFPMath &&
14942               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14943             break;
14944           std::swap(LHS, RHS);
14945         }
14946         Opcode = X86ISD::FMAX;
14947         break;
14948       case ISD::SETUGE:
14949         // Converting this to a max would handle both negative zeros and NaNs
14950         // incorrectly, but we can swap the operands to fix both.
14951         std::swap(LHS, RHS);
14952       case ISD::SETOGT:
14953       case ISD::SETGT:
14954       case ISD::SETGE:
14955         Opcode = X86ISD::FMAX;
14956         break;
14957       }
14958     // Check for x CC y ? y : x -- a min/max with reversed arms.
14959     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14960                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14961       switch (CC) {
14962       default: break;
14963       case ISD::SETOGE:
14964         // Converting this to a min would handle comparisons between positive
14965         // and negative zero incorrectly, and swapping the operands would
14966         // cause it to handle NaNs incorrectly.
14967         if (!DAG.getTarget().Options.UnsafeFPMath &&
14968             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14969           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14970             break;
14971           std::swap(LHS, RHS);
14972         }
14973         Opcode = X86ISD::FMIN;
14974         break;
14975       case ISD::SETUGT:
14976         // Converting this to a min would handle NaNs incorrectly.
14977         if (!DAG.getTarget().Options.UnsafeFPMath &&
14978             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14979           break;
14980         Opcode = X86ISD::FMIN;
14981         break;
14982       case ISD::SETUGE:
14983         // Converting this to a min would handle both negative zeros and NaNs
14984         // incorrectly, but we can swap the operands to fix both.
14985         std::swap(LHS, RHS);
14986       case ISD::SETOGT:
14987       case ISD::SETGT:
14988       case ISD::SETGE:
14989         Opcode = X86ISD::FMIN;
14990         break;
14991
14992       case ISD::SETULT:
14993         // Converting this to a max would handle NaNs incorrectly.
14994         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14995           break;
14996         Opcode = X86ISD::FMAX;
14997         break;
14998       case ISD::SETOLE:
14999         // Converting this to a max would handle comparisons between positive
15000         // and negative zero incorrectly, and swapping the operands would
15001         // cause it to handle NaNs incorrectly.
15002         if (!DAG.getTarget().Options.UnsafeFPMath &&
15003             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15004           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15005             break;
15006           std::swap(LHS, RHS);
15007         }
15008         Opcode = X86ISD::FMAX;
15009         break;
15010       case ISD::SETULE:
15011         // Converting this to a max would handle both negative zeros and NaNs
15012         // incorrectly, but we can swap the operands to fix both.
15013         std::swap(LHS, RHS);
15014       case ISD::SETOLT:
15015       case ISD::SETLT:
15016       case ISD::SETLE:
15017         Opcode = X86ISD::FMAX;
15018         break;
15019       }
15020     }
15021
15022     if (Opcode)
15023       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15024   }
15025
15026   // If this is a select between two integer constants, try to do some
15027   // optimizations.
15028   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15029     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15030       // Don't do this for crazy integer types.
15031       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15032         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15033         // so that TrueC (the true value) is larger than FalseC.
15034         bool NeedsCondInvert = false;
15035
15036         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15037             // Efficiently invertible.
15038             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15039              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15040               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15041           NeedsCondInvert = true;
15042           std::swap(TrueC, FalseC);
15043         }
15044
15045         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15046         if (FalseC->getAPIntValue() == 0 &&
15047             TrueC->getAPIntValue().isPowerOf2()) {
15048           if (NeedsCondInvert) // Invert the condition if needed.
15049             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15050                                DAG.getConstant(1, Cond.getValueType()));
15051
15052           // Zero extend the condition if needed.
15053           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15054
15055           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15056           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15057                              DAG.getConstant(ShAmt, MVT::i8));
15058         }
15059
15060         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15061         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15062           if (NeedsCondInvert) // Invert the condition if needed.
15063             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15064                                DAG.getConstant(1, Cond.getValueType()));
15065
15066           // Zero extend the condition if needed.
15067           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15068                              FalseC->getValueType(0), Cond);
15069           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15070                              SDValue(FalseC, 0));
15071         }
15072
15073         // Optimize cases that will turn into an LEA instruction.  This requires
15074         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15075         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15076           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15077           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15078
15079           bool isFastMultiplier = false;
15080           if (Diff < 10) {
15081             switch ((unsigned char)Diff) {
15082               default: break;
15083               case 1:  // result = add base, cond
15084               case 2:  // result = lea base(    , cond*2)
15085               case 3:  // result = lea base(cond, cond*2)
15086               case 4:  // result = lea base(    , cond*4)
15087               case 5:  // result = lea base(cond, cond*4)
15088               case 8:  // result = lea base(    , cond*8)
15089               case 9:  // result = lea base(cond, cond*8)
15090                 isFastMultiplier = true;
15091                 break;
15092             }
15093           }
15094
15095           if (isFastMultiplier) {
15096             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15097             if (NeedsCondInvert) // Invert the condition if needed.
15098               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15099                                  DAG.getConstant(1, Cond.getValueType()));
15100
15101             // Zero extend the condition if needed.
15102             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15103                                Cond);
15104             // Scale the condition by the difference.
15105             if (Diff != 1)
15106               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15107                                  DAG.getConstant(Diff, Cond.getValueType()));
15108
15109             // Add the base if non-zero.
15110             if (FalseC->getAPIntValue() != 0)
15111               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15112                                  SDValue(FalseC, 0));
15113             return Cond;
15114           }
15115         }
15116       }
15117   }
15118
15119   // Canonicalize max and min:
15120   // (x > y) ? x : y -> (x >= y) ? x : y
15121   // (x < y) ? x : y -> (x <= y) ? x : y
15122   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15123   // the need for an extra compare
15124   // against zero. e.g.
15125   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15126   // subl   %esi, %edi
15127   // testl  %edi, %edi
15128   // movl   $0, %eax
15129   // cmovgl %edi, %eax
15130   // =>
15131   // xorl   %eax, %eax
15132   // subl   %esi, $edi
15133   // cmovsl %eax, %edi
15134   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15135       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15136       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15137     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15138     switch (CC) {
15139     default: break;
15140     case ISD::SETLT:
15141     case ISD::SETGT: {
15142       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15143       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15144                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15145       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15146     }
15147     }
15148   }
15149
15150   // Match VSELECTs into subs with unsigned saturation.
15151   if (!DCI.isBeforeLegalize() &&
15152       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15153       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15154       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15155        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15156     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15157
15158     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15159     // left side invert the predicate to simplify logic below.
15160     SDValue Other;
15161     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15162       Other = RHS;
15163       CC = ISD::getSetCCInverse(CC, true);
15164     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15165       Other = LHS;
15166     }
15167
15168     if (Other.getNode() && Other->getNumOperands() == 2 &&
15169         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15170       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15171       SDValue CondRHS = Cond->getOperand(1);
15172
15173       // Look for a general sub with unsigned saturation first.
15174       // x >= y ? x-y : 0 --> subus x, y
15175       // x >  y ? x-y : 0 --> subus x, y
15176       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15177           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15178         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15179
15180       // If the RHS is a constant we have to reverse the const canonicalization.
15181       // x > C-1 ? x+-C : 0 --> subus x, C
15182       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15183           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15184         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15185         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15186           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15187                                      DAG.getConstant(-A, VT.getScalarType()));
15188           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15189                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15190                                          V.data(), V.size()));
15191         }
15192       }
15193
15194       // Another special case: If C was a sign bit, the sub has been
15195       // canonicalized into a xor.
15196       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15197       //        it's safe to decanonicalize the xor?
15198       // x s< 0 ? x^C : 0 --> subus x, C
15199       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15200           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15201           isSplatVector(OpRHS.getNode())) {
15202         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15203         if (A.isSignBit())
15204           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15205       }
15206     }
15207   }
15208
15209   // Try to match a min/max vector operation.
15210   if (!DCI.isBeforeLegalize() &&
15211       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15212     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15213       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15214
15215   // If we know that this node is legal then we know that it is going to be
15216   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15217   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15218   // to simplify previous instructions.
15219   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15220   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15221       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15222     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15223
15224     // Don't optimize vector selects that map to mask-registers.
15225     if (BitWidth == 1)
15226       return SDValue();
15227
15228     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15229     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15230
15231     APInt KnownZero, KnownOne;
15232     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15233                                           DCI.isBeforeLegalizeOps());
15234     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15235         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15236       DCI.CommitTargetLoweringOpt(TLO);
15237   }
15238
15239   return SDValue();
15240 }
15241
15242 // Check whether a boolean test is testing a boolean value generated by
15243 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15244 // code.
15245 //
15246 // Simplify the following patterns:
15247 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15248 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15249 // to (Op EFLAGS Cond)
15250 //
15251 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15252 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15253 // to (Op EFLAGS !Cond)
15254 //
15255 // where Op could be BRCOND or CMOV.
15256 //
15257 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15258   // Quit if not CMP and SUB with its value result used.
15259   if (Cmp.getOpcode() != X86ISD::CMP &&
15260       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15261       return SDValue();
15262
15263   // Quit if not used as a boolean value.
15264   if (CC != X86::COND_E && CC != X86::COND_NE)
15265     return SDValue();
15266
15267   // Check CMP operands. One of them should be 0 or 1 and the other should be
15268   // an SetCC or extended from it.
15269   SDValue Op1 = Cmp.getOperand(0);
15270   SDValue Op2 = Cmp.getOperand(1);
15271
15272   SDValue SetCC;
15273   const ConstantSDNode* C = 0;
15274   bool needOppositeCond = (CC == X86::COND_E);
15275
15276   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15277     SetCC = Op2;
15278   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15279     SetCC = Op1;
15280   else // Quit if all operands are not constants.
15281     return SDValue();
15282
15283   if (C->getZExtValue() == 1)
15284     needOppositeCond = !needOppositeCond;
15285   else if (C->getZExtValue() != 0)
15286     // Quit if the constant is neither 0 or 1.
15287     return SDValue();
15288
15289   // Skip 'zext' node.
15290   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15291     SetCC = SetCC.getOperand(0);
15292
15293   switch (SetCC.getOpcode()) {
15294   case X86ISD::SETCC:
15295     // Set the condition code or opposite one if necessary.
15296     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15297     if (needOppositeCond)
15298       CC = X86::GetOppositeBranchCondition(CC);
15299     return SetCC.getOperand(1);
15300   case X86ISD::CMOV: {
15301     // Check whether false/true value has canonical one, i.e. 0 or 1.
15302     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15303     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15304     // Quit if true value is not a constant.
15305     if (!TVal)
15306       return SDValue();
15307     // Quit if false value is not a constant.
15308     if (!FVal) {
15309       // A special case for rdrand, where 0 is set if false cond is found.
15310       SDValue Op = SetCC.getOperand(0);
15311       if (Op.getOpcode() != X86ISD::RDRAND)
15312         return SDValue();
15313     }
15314     // Quit if false value is not the constant 0 or 1.
15315     bool FValIsFalse = true;
15316     if (FVal && FVal->getZExtValue() != 0) {
15317       if (FVal->getZExtValue() != 1)
15318         return SDValue();
15319       // If FVal is 1, opposite cond is needed.
15320       needOppositeCond = !needOppositeCond;
15321       FValIsFalse = false;
15322     }
15323     // Quit if TVal is not the constant opposite of FVal.
15324     if (FValIsFalse && TVal->getZExtValue() != 1)
15325       return SDValue();
15326     if (!FValIsFalse && TVal->getZExtValue() != 0)
15327       return SDValue();
15328     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15329     if (needOppositeCond)
15330       CC = X86::GetOppositeBranchCondition(CC);
15331     return SetCC.getOperand(3);
15332   }
15333   }
15334
15335   return SDValue();
15336 }
15337
15338 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15339 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15340                                   TargetLowering::DAGCombinerInfo &DCI,
15341                                   const X86Subtarget *Subtarget) {
15342   DebugLoc DL = N->getDebugLoc();
15343
15344   // If the flag operand isn't dead, don't touch this CMOV.
15345   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15346     return SDValue();
15347
15348   SDValue FalseOp = N->getOperand(0);
15349   SDValue TrueOp = N->getOperand(1);
15350   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15351   SDValue Cond = N->getOperand(3);
15352
15353   if (CC == X86::COND_E || CC == X86::COND_NE) {
15354     switch (Cond.getOpcode()) {
15355     default: break;
15356     case X86ISD::BSR:
15357     case X86ISD::BSF:
15358       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15359       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15360         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15361     }
15362   }
15363
15364   SDValue Flags;
15365
15366   Flags = checkBoolTestSetCCCombine(Cond, CC);
15367   if (Flags.getNode() &&
15368       // Extra check as FCMOV only supports a subset of X86 cond.
15369       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15370     SDValue Ops[] = { FalseOp, TrueOp,
15371                       DAG.getConstant(CC, MVT::i8), Flags };
15372     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15373                        Ops, array_lengthof(Ops));
15374   }
15375
15376   // If this is a select between two integer constants, try to do some
15377   // optimizations.  Note that the operands are ordered the opposite of SELECT
15378   // operands.
15379   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15380     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15381       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15382       // larger than FalseC (the false value).
15383       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15384         CC = X86::GetOppositeBranchCondition(CC);
15385         std::swap(TrueC, FalseC);
15386         std::swap(TrueOp, FalseOp);
15387       }
15388
15389       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15390       // This is efficient for any integer data type (including i8/i16) and
15391       // shift amount.
15392       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15393         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15394                            DAG.getConstant(CC, MVT::i8), Cond);
15395
15396         // Zero extend the condition if needed.
15397         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15398
15399         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15400         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15401                            DAG.getConstant(ShAmt, MVT::i8));
15402         if (N->getNumValues() == 2)  // Dead flag value?
15403           return DCI.CombineTo(N, Cond, SDValue());
15404         return Cond;
15405       }
15406
15407       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15408       // for any integer data type, including i8/i16.
15409       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15410         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15411                            DAG.getConstant(CC, MVT::i8), Cond);
15412
15413         // Zero extend the condition if needed.
15414         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15415                            FalseC->getValueType(0), Cond);
15416         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15417                            SDValue(FalseC, 0));
15418
15419         if (N->getNumValues() == 2)  // Dead flag value?
15420           return DCI.CombineTo(N, Cond, SDValue());
15421         return Cond;
15422       }
15423
15424       // Optimize cases that will turn into an LEA instruction.  This requires
15425       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15426       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15427         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15428         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15429
15430         bool isFastMultiplier = false;
15431         if (Diff < 10) {
15432           switch ((unsigned char)Diff) {
15433           default: break;
15434           case 1:  // result = add base, cond
15435           case 2:  // result = lea base(    , cond*2)
15436           case 3:  // result = lea base(cond, cond*2)
15437           case 4:  // result = lea base(    , cond*4)
15438           case 5:  // result = lea base(cond, cond*4)
15439           case 8:  // result = lea base(    , cond*8)
15440           case 9:  // result = lea base(cond, cond*8)
15441             isFastMultiplier = true;
15442             break;
15443           }
15444         }
15445
15446         if (isFastMultiplier) {
15447           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15448           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15449                              DAG.getConstant(CC, MVT::i8), Cond);
15450           // Zero extend the condition if needed.
15451           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15452                              Cond);
15453           // Scale the condition by the difference.
15454           if (Diff != 1)
15455             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15456                                DAG.getConstant(Diff, Cond.getValueType()));
15457
15458           // Add the base if non-zero.
15459           if (FalseC->getAPIntValue() != 0)
15460             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15461                                SDValue(FalseC, 0));
15462           if (N->getNumValues() == 2)  // Dead flag value?
15463             return DCI.CombineTo(N, Cond, SDValue());
15464           return Cond;
15465         }
15466       }
15467     }
15468   }
15469
15470   // Handle these cases:
15471   //   (select (x != c), e, c) -> select (x != c), e, x),
15472   //   (select (x == c), c, e) -> select (x == c), x, e)
15473   // where the c is an integer constant, and the "select" is the combination
15474   // of CMOV and CMP.
15475   //
15476   // The rationale for this change is that the conditional-move from a constant
15477   // needs two instructions, however, conditional-move from a register needs
15478   // only one instruction.
15479   //
15480   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15481   //  some instruction-combining opportunities. This opt needs to be
15482   //  postponed as late as possible.
15483   //
15484   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15485     // the DCI.xxxx conditions are provided to postpone the optimization as
15486     // late as possible.
15487
15488     ConstantSDNode *CmpAgainst = 0;
15489     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15490         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15491         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15492
15493       if (CC == X86::COND_NE &&
15494           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15495         CC = X86::GetOppositeBranchCondition(CC);
15496         std::swap(TrueOp, FalseOp);
15497       }
15498
15499       if (CC == X86::COND_E &&
15500           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15501         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15502                           DAG.getConstant(CC, MVT::i8), Cond };
15503         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15504                            array_lengthof(Ops));
15505       }
15506     }
15507   }
15508
15509   return SDValue();
15510 }
15511
15512 /// PerformMulCombine - Optimize a single multiply with constant into two
15513 /// in order to implement it with two cheaper instructions, e.g.
15514 /// LEA + SHL, LEA + LEA.
15515 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15516                                  TargetLowering::DAGCombinerInfo &DCI) {
15517   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15518     return SDValue();
15519
15520   EVT VT = N->getValueType(0);
15521   if (VT != MVT::i64)
15522     return SDValue();
15523
15524   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15525   if (!C)
15526     return SDValue();
15527   uint64_t MulAmt = C->getZExtValue();
15528   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15529     return SDValue();
15530
15531   uint64_t MulAmt1 = 0;
15532   uint64_t MulAmt2 = 0;
15533   if ((MulAmt % 9) == 0) {
15534     MulAmt1 = 9;
15535     MulAmt2 = MulAmt / 9;
15536   } else if ((MulAmt % 5) == 0) {
15537     MulAmt1 = 5;
15538     MulAmt2 = MulAmt / 5;
15539   } else if ((MulAmt % 3) == 0) {
15540     MulAmt1 = 3;
15541     MulAmt2 = MulAmt / 3;
15542   }
15543   if (MulAmt2 &&
15544       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15545     DebugLoc DL = N->getDebugLoc();
15546
15547     if (isPowerOf2_64(MulAmt2) &&
15548         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15549       // If second multiplifer is pow2, issue it first. We want the multiply by
15550       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15551       // is an add.
15552       std::swap(MulAmt1, MulAmt2);
15553
15554     SDValue NewMul;
15555     if (isPowerOf2_64(MulAmt1))
15556       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15557                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15558     else
15559       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15560                            DAG.getConstant(MulAmt1, VT));
15561
15562     if (isPowerOf2_64(MulAmt2))
15563       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15564                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15565     else
15566       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15567                            DAG.getConstant(MulAmt2, VT));
15568
15569     // Do not add new nodes to DAG combiner worklist.
15570     DCI.CombineTo(N, NewMul, false);
15571   }
15572   return SDValue();
15573 }
15574
15575 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15576   SDValue N0 = N->getOperand(0);
15577   SDValue N1 = N->getOperand(1);
15578   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15579   EVT VT = N0.getValueType();
15580
15581   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15582   // since the result of setcc_c is all zero's or all ones.
15583   if (VT.isInteger() && !VT.isVector() &&
15584       N1C && N0.getOpcode() == ISD::AND &&
15585       N0.getOperand(1).getOpcode() == ISD::Constant) {
15586     SDValue N00 = N0.getOperand(0);
15587     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15588         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15589           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15590          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15591       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15592       APInt ShAmt = N1C->getAPIntValue();
15593       Mask = Mask.shl(ShAmt);
15594       if (Mask != 0)
15595         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15596                            N00, DAG.getConstant(Mask, VT));
15597     }
15598   }
15599
15600   // Hardware support for vector shifts is sparse which makes us scalarize the
15601   // vector operations in many cases. Also, on sandybridge ADD is faster than
15602   // shl.
15603   // (shl V, 1) -> add V,V
15604   if (isSplatVector(N1.getNode())) {
15605     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15606     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15607     // We shift all of the values by one. In many cases we do not have
15608     // hardware support for this operation. This is better expressed as an ADD
15609     // of two values.
15610     if (N1C && (1 == N1C->getZExtValue())) {
15611       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15612     }
15613   }
15614
15615   return SDValue();
15616 }
15617
15618 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15619 ///                       when possible.
15620 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15621                                    TargetLowering::DAGCombinerInfo &DCI,
15622                                    const X86Subtarget *Subtarget) {
15623   EVT VT = N->getValueType(0);
15624   if (N->getOpcode() == ISD::SHL) {
15625     SDValue V = PerformSHLCombine(N, DAG);
15626     if (V.getNode()) return V;
15627   }
15628
15629   // On X86 with SSE2 support, we can transform this to a vector shift if
15630   // all elements are shifted by the same amount.  We can't do this in legalize
15631   // because the a constant vector is typically transformed to a constant pool
15632   // so we have no knowledge of the shift amount.
15633   if (!Subtarget->hasSSE2())
15634     return SDValue();
15635
15636   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15637       (!Subtarget->hasInt256() ||
15638        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15639     return SDValue();
15640
15641   SDValue ShAmtOp = N->getOperand(1);
15642   EVT EltVT = VT.getVectorElementType();
15643   DebugLoc DL = N->getDebugLoc();
15644   SDValue BaseShAmt = SDValue();
15645   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15646     unsigned NumElts = VT.getVectorNumElements();
15647     unsigned i = 0;
15648     for (; i != NumElts; ++i) {
15649       SDValue Arg = ShAmtOp.getOperand(i);
15650       if (Arg.getOpcode() == ISD::UNDEF) continue;
15651       BaseShAmt = Arg;
15652       break;
15653     }
15654     // Handle the case where the build_vector is all undef
15655     // FIXME: Should DAG allow this?
15656     if (i == NumElts)
15657       return SDValue();
15658
15659     for (; i != NumElts; ++i) {
15660       SDValue Arg = ShAmtOp.getOperand(i);
15661       if (Arg.getOpcode() == ISD::UNDEF) continue;
15662       if (Arg != BaseShAmt) {
15663         return SDValue();
15664       }
15665     }
15666   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15667              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15668     SDValue InVec = ShAmtOp.getOperand(0);
15669     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15670       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15671       unsigned i = 0;
15672       for (; i != NumElts; ++i) {
15673         SDValue Arg = InVec.getOperand(i);
15674         if (Arg.getOpcode() == ISD::UNDEF) continue;
15675         BaseShAmt = Arg;
15676         break;
15677       }
15678     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15679        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15680          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15681          if (C->getZExtValue() == SplatIdx)
15682            BaseShAmt = InVec.getOperand(1);
15683        }
15684     }
15685     if (BaseShAmt.getNode() == 0) {
15686       // Don't create instructions with illegal types after legalize
15687       // types has run.
15688       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15689           !DCI.isBeforeLegalize())
15690         return SDValue();
15691
15692       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15693                               DAG.getIntPtrConstant(0));
15694     }
15695   } else
15696     return SDValue();
15697
15698   // The shift amount is an i32.
15699   if (EltVT.bitsGT(MVT::i32))
15700     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15701   else if (EltVT.bitsLT(MVT::i32))
15702     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15703
15704   // The shift amount is identical so we can do a vector shift.
15705   SDValue  ValOp = N->getOperand(0);
15706   switch (N->getOpcode()) {
15707   default:
15708     llvm_unreachable("Unknown shift opcode!");
15709   case ISD::SHL:
15710     switch (VT.getSimpleVT().SimpleTy) {
15711     default: return SDValue();
15712     case MVT::v2i64:
15713     case MVT::v4i32:
15714     case MVT::v8i16:
15715     case MVT::v4i64:
15716     case MVT::v8i32:
15717     case MVT::v16i16:
15718       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15719     }
15720   case ISD::SRA:
15721     switch (VT.getSimpleVT().SimpleTy) {
15722     default: return SDValue();
15723     case MVT::v4i32:
15724     case MVT::v8i16:
15725     case MVT::v8i32:
15726     case MVT::v16i16:
15727       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15728     }
15729   case ISD::SRL:
15730     switch (VT.getSimpleVT().SimpleTy) {
15731     default: return SDValue();
15732     case MVT::v2i64:
15733     case MVT::v4i32:
15734     case MVT::v8i16:
15735     case MVT::v4i64:
15736     case MVT::v8i32:
15737     case MVT::v16i16:
15738       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15739     }
15740   }
15741 }
15742
15743 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15744 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15745 // and friends.  Likewise for OR -> CMPNEQSS.
15746 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15747                             TargetLowering::DAGCombinerInfo &DCI,
15748                             const X86Subtarget *Subtarget) {
15749   unsigned opcode;
15750
15751   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15752   // we're requiring SSE2 for both.
15753   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15754     SDValue N0 = N->getOperand(0);
15755     SDValue N1 = N->getOperand(1);
15756     SDValue CMP0 = N0->getOperand(1);
15757     SDValue CMP1 = N1->getOperand(1);
15758     DebugLoc DL = N->getDebugLoc();
15759
15760     // The SETCCs should both refer to the same CMP.
15761     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15762       return SDValue();
15763
15764     SDValue CMP00 = CMP0->getOperand(0);
15765     SDValue CMP01 = CMP0->getOperand(1);
15766     EVT     VT    = CMP00.getValueType();
15767
15768     if (VT == MVT::f32 || VT == MVT::f64) {
15769       bool ExpectingFlags = false;
15770       // Check for any users that want flags:
15771       for (SDNode::use_iterator UI = N->use_begin(),
15772              UE = N->use_end();
15773            !ExpectingFlags && UI != UE; ++UI)
15774         switch (UI->getOpcode()) {
15775         default:
15776         case ISD::BR_CC:
15777         case ISD::BRCOND:
15778         case ISD::SELECT:
15779           ExpectingFlags = true;
15780           break;
15781         case ISD::CopyToReg:
15782         case ISD::SIGN_EXTEND:
15783         case ISD::ZERO_EXTEND:
15784         case ISD::ANY_EXTEND:
15785           break;
15786         }
15787
15788       if (!ExpectingFlags) {
15789         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15790         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15791
15792         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15793           X86::CondCode tmp = cc0;
15794           cc0 = cc1;
15795           cc1 = tmp;
15796         }
15797
15798         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15799             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15800           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15801           X86ISD::NodeType NTOperator = is64BitFP ?
15802             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15803           // FIXME: need symbolic constants for these magic numbers.
15804           // See X86ATTInstPrinter.cpp:printSSECC().
15805           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15806           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15807                                               DAG.getConstant(x86cc, MVT::i8));
15808           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15809                                               OnesOrZeroesF);
15810           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15811                                       DAG.getConstant(1, MVT::i32));
15812           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15813           return OneBitOfTruth;
15814         }
15815       }
15816     }
15817   }
15818   return SDValue();
15819 }
15820
15821 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15822 /// so it can be folded inside ANDNP.
15823 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15824   EVT VT = N->getValueType(0);
15825
15826   // Match direct AllOnes for 128 and 256-bit vectors
15827   if (ISD::isBuildVectorAllOnes(N))
15828     return true;
15829
15830   // Look through a bit convert.
15831   if (N->getOpcode() == ISD::BITCAST)
15832     N = N->getOperand(0).getNode();
15833
15834   // Sometimes the operand may come from a insert_subvector building a 256-bit
15835   // allones vector
15836   if (VT.is256BitVector() &&
15837       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15838     SDValue V1 = N->getOperand(0);
15839     SDValue V2 = N->getOperand(1);
15840
15841     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15842         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15843         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15844         ISD::isBuildVectorAllOnes(V2.getNode()))
15845       return true;
15846   }
15847
15848   return false;
15849 }
15850
15851 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15852 // register. In most cases we actually compare or select YMM-sized registers
15853 // and mixing the two types creates horrible code. This method optimizes
15854 // some of the transition sequences.
15855 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15856                                  TargetLowering::DAGCombinerInfo &DCI,
15857                                  const X86Subtarget *Subtarget) {
15858   EVT VT = N->getValueType(0);
15859   if (VT.getSizeInBits() != 256)
15860     return SDValue();
15861
15862   assert((N->getOpcode() == ISD::ANY_EXTEND ||
15863           N->getOpcode() == ISD::ZERO_EXTEND ||
15864           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15865
15866   SDValue Narrow = N->getOperand(0);
15867   EVT NarrowVT = Narrow->getValueType(0);
15868   if (NarrowVT.getSizeInBits() != 128)
15869     return SDValue();
15870
15871   if (Narrow->getOpcode() != ISD::XOR &&
15872       Narrow->getOpcode() != ISD::AND &&
15873       Narrow->getOpcode() != ISD::OR)
15874     return SDValue();
15875
15876   SDValue N0  = Narrow->getOperand(0);
15877   SDValue N1  = Narrow->getOperand(1);
15878   DebugLoc DL = Narrow->getDebugLoc();
15879
15880   // The Left side has to be a trunc.
15881   if (N0.getOpcode() != ISD::TRUNCATE)
15882     return SDValue();
15883
15884   // The type of the truncated inputs.
15885   EVT WideVT = N0->getOperand(0)->getValueType(0);
15886   if (WideVT != VT)
15887     return SDValue();
15888
15889   // The right side has to be a 'trunc' or a constant vector.
15890   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
15891   bool RHSConst = (isSplatVector(N1.getNode()) &&
15892                    isa<ConstantSDNode>(N1->getOperand(0)));
15893   if (!RHSTrunc && !RHSConst)
15894     return SDValue();
15895
15896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15897
15898   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
15899     return SDValue();
15900
15901   // Set N0 and N1 to hold the inputs to the new wide operation.
15902   N0 = N0->getOperand(0);
15903   if (RHSConst) {
15904     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
15905                      N1->getOperand(0));
15906     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
15907     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
15908   } else if (RHSTrunc) {
15909     N1 = N1->getOperand(0);
15910   }
15911
15912   // Generate the wide operation.
15913   SDValue Op = DAG.getNode(N->getOpcode(), DL, WideVT, N0, N1);
15914   unsigned Opcode = N->getOpcode();
15915   switch (Opcode) {
15916   case ISD::ANY_EXTEND:
15917     return Op;
15918   case ISD::ZERO_EXTEND: {
15919     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
15920     APInt Mask = APInt::getAllOnesValue(InBits);
15921     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
15922     return DAG.getNode(ISD::AND, DL, VT,
15923                        Op, DAG.getConstant(Mask, VT));
15924   }
15925   case ISD::SIGN_EXTEND:
15926     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
15927                        Op, DAG.getValueType(NarrowVT));
15928   default:
15929     llvm_unreachable("Unexpected opcode");
15930   }
15931 }
15932
15933 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15934                                  TargetLowering::DAGCombinerInfo &DCI,
15935                                  const X86Subtarget *Subtarget) {
15936   EVT VT = N->getValueType(0);
15937   if (DCI.isBeforeLegalizeOps())
15938     return SDValue();
15939
15940   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15941   if (R.getNode())
15942     return R;
15943
15944   // Create BLSI, and BLSR instructions
15945   // BLSI is X & (-X)
15946   // BLSR is X & (X-1)
15947   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15948     SDValue N0 = N->getOperand(0);
15949     SDValue N1 = N->getOperand(1);
15950     DebugLoc DL = N->getDebugLoc();
15951
15952     // Check LHS for neg
15953     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15954         isZero(N0.getOperand(0)))
15955       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15956
15957     // Check RHS for neg
15958     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15959         isZero(N1.getOperand(0)))
15960       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15961
15962     // Check LHS for X-1
15963     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15964         isAllOnes(N0.getOperand(1)))
15965       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15966
15967     // Check RHS for X-1
15968     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15969         isAllOnes(N1.getOperand(1)))
15970       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15971
15972     return SDValue();
15973   }
15974
15975   // Want to form ANDNP nodes:
15976   // 1) In the hopes of then easily combining them with OR and AND nodes
15977   //    to form PBLEND/PSIGN.
15978   // 2) To match ANDN packed intrinsics
15979   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15980     return SDValue();
15981
15982   SDValue N0 = N->getOperand(0);
15983   SDValue N1 = N->getOperand(1);
15984   DebugLoc DL = N->getDebugLoc();
15985
15986   // Check LHS for vnot
15987   if (N0.getOpcode() == ISD::XOR &&
15988       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15989       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15990     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15991
15992   // Check RHS for vnot
15993   if (N1.getOpcode() == ISD::XOR &&
15994       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15995       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15996     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15997
15998   return SDValue();
15999 }
16000
16001 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16002                                 TargetLowering::DAGCombinerInfo &DCI,
16003                                 const X86Subtarget *Subtarget) {
16004   EVT VT = N->getValueType(0);
16005   if (DCI.isBeforeLegalizeOps())
16006     return SDValue();
16007
16008   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16009   if (R.getNode())
16010     return R;
16011
16012   SDValue N0 = N->getOperand(0);
16013   SDValue N1 = N->getOperand(1);
16014
16015   // look for psign/blend
16016   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16017     if (!Subtarget->hasSSSE3() ||
16018         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16019       return SDValue();
16020
16021     // Canonicalize pandn to RHS
16022     if (N0.getOpcode() == X86ISD::ANDNP)
16023       std::swap(N0, N1);
16024     // or (and (m, y), (pandn m, x))
16025     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16026       SDValue Mask = N1.getOperand(0);
16027       SDValue X    = N1.getOperand(1);
16028       SDValue Y;
16029       if (N0.getOperand(0) == Mask)
16030         Y = N0.getOperand(1);
16031       if (N0.getOperand(1) == Mask)
16032         Y = N0.getOperand(0);
16033
16034       // Check to see if the mask appeared in both the AND and ANDNP and
16035       if (!Y.getNode())
16036         return SDValue();
16037
16038       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16039       // Look through mask bitcast.
16040       if (Mask.getOpcode() == ISD::BITCAST)
16041         Mask = Mask.getOperand(0);
16042       if (X.getOpcode() == ISD::BITCAST)
16043         X = X.getOperand(0);
16044       if (Y.getOpcode() == ISD::BITCAST)
16045         Y = Y.getOperand(0);
16046
16047       EVT MaskVT = Mask.getValueType();
16048
16049       // Validate that the Mask operand is a vector sra node.
16050       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16051       // there is no psrai.b
16052       if (Mask.getOpcode() != X86ISD::VSRAI)
16053         return SDValue();
16054
16055       // Check that the SRA is all signbits.
16056       SDValue SraC = Mask.getOperand(1);
16057       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16058       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16059       if ((SraAmt + 1) != EltBits)
16060         return SDValue();
16061
16062       DebugLoc DL = N->getDebugLoc();
16063
16064       // We are going to replace the AND, OR, NAND with either BLEND
16065       // or PSIGN, which only look at the MSB. The VSRAI instruction
16066       // does not affect the highest bit, so we can get rid of it.
16067       Mask = Mask.getOperand(0);
16068
16069       // Now we know we at least have a plendvb with the mask val.  See if
16070       // we can form a psignb/w/d.
16071       // psign = x.type == y.type == mask.type && y = sub(0, x);
16072       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16073           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16074           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16075         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16076                "Unsupported VT for PSIGN");
16077         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16078         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16079       }
16080       // PBLENDVB only available on SSE 4.1
16081       if (!Subtarget->hasSSE41())
16082         return SDValue();
16083
16084       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16085
16086       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16087       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16088       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16089       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16090       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16091     }
16092   }
16093
16094   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16095     return SDValue();
16096
16097   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16098   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16099     std::swap(N0, N1);
16100   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16101     return SDValue();
16102   if (!N0.hasOneUse() || !N1.hasOneUse())
16103     return SDValue();
16104
16105   SDValue ShAmt0 = N0.getOperand(1);
16106   if (ShAmt0.getValueType() != MVT::i8)
16107     return SDValue();
16108   SDValue ShAmt1 = N1.getOperand(1);
16109   if (ShAmt1.getValueType() != MVT::i8)
16110     return SDValue();
16111   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16112     ShAmt0 = ShAmt0.getOperand(0);
16113   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16114     ShAmt1 = ShAmt1.getOperand(0);
16115
16116   DebugLoc DL = N->getDebugLoc();
16117   unsigned Opc = X86ISD::SHLD;
16118   SDValue Op0 = N0.getOperand(0);
16119   SDValue Op1 = N1.getOperand(0);
16120   if (ShAmt0.getOpcode() == ISD::SUB) {
16121     Opc = X86ISD::SHRD;
16122     std::swap(Op0, Op1);
16123     std::swap(ShAmt0, ShAmt1);
16124   }
16125
16126   unsigned Bits = VT.getSizeInBits();
16127   if (ShAmt1.getOpcode() == ISD::SUB) {
16128     SDValue Sum = ShAmt1.getOperand(0);
16129     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16130       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16131       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16132         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16133       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16134         return DAG.getNode(Opc, DL, VT,
16135                            Op0, Op1,
16136                            DAG.getNode(ISD::TRUNCATE, DL,
16137                                        MVT::i8, ShAmt0));
16138     }
16139   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16140     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16141     if (ShAmt0C &&
16142         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16143       return DAG.getNode(Opc, DL, VT,
16144                          N0.getOperand(0), N1.getOperand(0),
16145                          DAG.getNode(ISD::TRUNCATE, DL,
16146                                        MVT::i8, ShAmt0));
16147   }
16148
16149   return SDValue();
16150 }
16151
16152 // Generate NEG and CMOV for integer abs.
16153 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16154   EVT VT = N->getValueType(0);
16155
16156   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16157   // 8-bit integer abs to NEG and CMOV.
16158   if (VT.isInteger() && VT.getSizeInBits() == 8)
16159     return SDValue();
16160
16161   SDValue N0 = N->getOperand(0);
16162   SDValue N1 = N->getOperand(1);
16163   DebugLoc DL = N->getDebugLoc();
16164
16165   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16166   // and change it to SUB and CMOV.
16167   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16168       N0.getOpcode() == ISD::ADD &&
16169       N0.getOperand(1) == N1 &&
16170       N1.getOpcode() == ISD::SRA &&
16171       N1.getOperand(0) == N0.getOperand(0))
16172     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16173       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16174         // Generate SUB & CMOV.
16175         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16176                                   DAG.getConstant(0, VT), N0.getOperand(0));
16177
16178         SDValue Ops[] = { N0.getOperand(0), Neg,
16179                           DAG.getConstant(X86::COND_GE, MVT::i8),
16180                           SDValue(Neg.getNode(), 1) };
16181         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16182                            Ops, array_lengthof(Ops));
16183       }
16184   return SDValue();
16185 }
16186
16187 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16188 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16189                                  TargetLowering::DAGCombinerInfo &DCI,
16190                                  const X86Subtarget *Subtarget) {
16191   EVT VT = N->getValueType(0);
16192   if (DCI.isBeforeLegalizeOps())
16193     return SDValue();
16194
16195   if (Subtarget->hasCMov()) {
16196     SDValue RV = performIntegerAbsCombine(N, DAG);
16197     if (RV.getNode())
16198       return RV;
16199   }
16200
16201   // Try forming BMI if it is available.
16202   if (!Subtarget->hasBMI())
16203     return SDValue();
16204
16205   if (VT != MVT::i32 && VT != MVT::i64)
16206     return SDValue();
16207
16208   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16209
16210   // Create BLSMSK instructions by finding X ^ (X-1)
16211   SDValue N0 = N->getOperand(0);
16212   SDValue N1 = N->getOperand(1);
16213   DebugLoc DL = N->getDebugLoc();
16214
16215   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16216       isAllOnes(N0.getOperand(1)))
16217     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16218
16219   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16220       isAllOnes(N1.getOperand(1)))
16221     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16222
16223   return SDValue();
16224 }
16225
16226 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16227 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16228                                   TargetLowering::DAGCombinerInfo &DCI,
16229                                   const X86Subtarget *Subtarget) {
16230   LoadSDNode *Ld = cast<LoadSDNode>(N);
16231   EVT RegVT = Ld->getValueType(0);
16232   EVT MemVT = Ld->getMemoryVT();
16233   DebugLoc dl = Ld->getDebugLoc();
16234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16235
16236   ISD::LoadExtType Ext = Ld->getExtensionType();
16237
16238   // If this is a vector EXT Load then attempt to optimize it using a
16239   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16240   // expansion is still better than scalar code.
16241   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16242   // emit a shuffle and a arithmetic shift.
16243   // TODO: It is possible to support ZExt by zeroing the undef values
16244   // during the shuffle phase or after the shuffle.
16245   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16246       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16247     assert(MemVT != RegVT && "Cannot extend to the same type");
16248     assert(MemVT.isVector() && "Must load a vector from memory");
16249
16250     unsigned NumElems = RegVT.getVectorNumElements();
16251     unsigned RegSz = RegVT.getSizeInBits();
16252     unsigned MemSz = MemVT.getSizeInBits();
16253     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16254
16255     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16256       return SDValue();
16257
16258     // All sizes must be a power of two.
16259     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16260       return SDValue();
16261
16262     // Attempt to load the original value using scalar loads.
16263     // Find the largest scalar type that divides the total loaded size.
16264     MVT SclrLoadTy = MVT::i8;
16265     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16266          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16267       MVT Tp = (MVT::SimpleValueType)tp;
16268       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16269         SclrLoadTy = Tp;
16270       }
16271     }
16272
16273     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16274     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16275         (64 <= MemSz))
16276       SclrLoadTy = MVT::f64;
16277
16278     // Calculate the number of scalar loads that we need to perform
16279     // in order to load our vector from memory.
16280     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16281     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16282       return SDValue();
16283
16284     unsigned loadRegZize = RegSz;
16285     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16286       loadRegZize /= 2;
16287
16288     // Represent our vector as a sequence of elements which are the
16289     // largest scalar that we can load.
16290     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16291       loadRegZize/SclrLoadTy.getSizeInBits());
16292
16293     // Represent the data using the same element type that is stored in
16294     // memory. In practice, we ''widen'' MemVT.
16295     EVT WideVecVT = 
16296           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16297                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16298
16299     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16300       "Invalid vector type");
16301
16302     // We can't shuffle using an illegal type.
16303     if (!TLI.isTypeLegal(WideVecVT))
16304       return SDValue();
16305
16306     SmallVector<SDValue, 8> Chains;
16307     SDValue Ptr = Ld->getBasePtr();
16308     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16309                                         TLI.getPointerTy());
16310     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16311
16312     for (unsigned i = 0; i < NumLoads; ++i) {
16313       // Perform a single load.
16314       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16315                                        Ptr, Ld->getPointerInfo(),
16316                                        Ld->isVolatile(), Ld->isNonTemporal(),
16317                                        Ld->isInvariant(), Ld->getAlignment());
16318       Chains.push_back(ScalarLoad.getValue(1));
16319       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16320       // another round of DAGCombining.
16321       if (i == 0)
16322         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16323       else
16324         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16325                           ScalarLoad, DAG.getIntPtrConstant(i));
16326
16327       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16328     }
16329
16330     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16331                                Chains.size());
16332
16333     // Bitcast the loaded value to a vector of the original element type, in
16334     // the size of the target vector type.
16335     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16336     unsigned SizeRatio = RegSz/MemSz;
16337
16338     if (Ext == ISD::SEXTLOAD) {
16339       // If we have SSE4.1 we can directly emit a VSEXT node.
16340       if (Subtarget->hasSSE41()) {
16341         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16342         return DCI.CombineTo(N, Sext, TF, true);
16343       }
16344
16345       // Otherwise we'll shuffle the small elements in the high bits of the
16346       // larger type and perform an arithmetic shift. If the shift is not legal
16347       // it's better to scalarize.
16348       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16349         return SDValue();
16350
16351       // Redistribute the loaded elements into the different locations.
16352       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16353       for (unsigned i = 0; i != NumElems; ++i)
16354         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16355
16356       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16357                                            DAG.getUNDEF(WideVecVT),
16358                                            &ShuffleVec[0]);
16359
16360       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16361
16362       // Build the arithmetic shift.
16363       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16364                      MemVT.getVectorElementType().getSizeInBits();
16365       SmallVector<SDValue, 8> C(NumElems,
16366                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16367       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16368       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16369
16370       return DCI.CombineTo(N, Shuff, TF, true);
16371     }
16372
16373     // Redistribute the loaded elements into the different locations.
16374     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16375     for (unsigned i = 0; i != NumElems; ++i)
16376       ShuffleVec[i*SizeRatio] = i;
16377
16378     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16379                                          DAG.getUNDEF(WideVecVT),
16380                                          &ShuffleVec[0]);
16381
16382     // Bitcast to the requested type.
16383     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16384     // Replace the original load with the new sequence
16385     // and return the new chain.
16386     return DCI.CombineTo(N, Shuff, TF, true);
16387   }
16388
16389   return SDValue();
16390 }
16391
16392 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16393 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16394                                    const X86Subtarget *Subtarget) {
16395   StoreSDNode *St = cast<StoreSDNode>(N);
16396   EVT VT = St->getValue().getValueType();
16397   EVT StVT = St->getMemoryVT();
16398   DebugLoc dl = St->getDebugLoc();
16399   SDValue StoredVal = St->getOperand(1);
16400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16401
16402   // If we are saving a concatenation of two XMM registers, perform two stores.
16403   // On Sandy Bridge, 256-bit memory operations are executed by two
16404   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16405   // memory  operation.
16406   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16407       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16408       StoredVal.getNumOperands() == 2) {
16409     SDValue Value0 = StoredVal.getOperand(0);
16410     SDValue Value1 = StoredVal.getOperand(1);
16411
16412     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16413     SDValue Ptr0 = St->getBasePtr();
16414     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16415
16416     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16417                                 St->getPointerInfo(), St->isVolatile(),
16418                                 St->isNonTemporal(), St->getAlignment());
16419     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16420                                 St->getPointerInfo(), St->isVolatile(),
16421                                 St->isNonTemporal(), St->getAlignment());
16422     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16423   }
16424
16425   // Optimize trunc store (of multiple scalars) to shuffle and store.
16426   // First, pack all of the elements in one place. Next, store to memory
16427   // in fewer chunks.
16428   if (St->isTruncatingStore() && VT.isVector()) {
16429     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16430     unsigned NumElems = VT.getVectorNumElements();
16431     assert(StVT != VT && "Cannot truncate to the same type");
16432     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16433     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16434
16435     // From, To sizes and ElemCount must be pow of two
16436     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16437     // We are going to use the original vector elt for storing.
16438     // Accumulated smaller vector elements must be a multiple of the store size.
16439     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16440
16441     unsigned SizeRatio  = FromSz / ToSz;
16442
16443     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16444
16445     // Create a type on which we perform the shuffle
16446     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16447             StVT.getScalarType(), NumElems*SizeRatio);
16448
16449     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16450
16451     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16452     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16453     for (unsigned i = 0; i != NumElems; ++i)
16454       ShuffleVec[i] = i * SizeRatio;
16455
16456     // Can't shuffle using an illegal type.
16457     if (!TLI.isTypeLegal(WideVecVT))
16458       return SDValue();
16459
16460     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16461                                          DAG.getUNDEF(WideVecVT),
16462                                          &ShuffleVec[0]);
16463     // At this point all of the data is stored at the bottom of the
16464     // register. We now need to save it to mem.
16465
16466     // Find the largest store unit
16467     MVT StoreType = MVT::i8;
16468     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16469          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16470       MVT Tp = (MVT::SimpleValueType)tp;
16471       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16472         StoreType = Tp;
16473     }
16474
16475     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16476     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16477         (64 <= NumElems * ToSz))
16478       StoreType = MVT::f64;
16479
16480     // Bitcast the original vector into a vector of store-size units
16481     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16482             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16483     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16484     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16485     SmallVector<SDValue, 8> Chains;
16486     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16487                                         TLI.getPointerTy());
16488     SDValue Ptr = St->getBasePtr();
16489
16490     // Perform one or more big stores into memory.
16491     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16492       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16493                                    StoreType, ShuffWide,
16494                                    DAG.getIntPtrConstant(i));
16495       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16496                                 St->getPointerInfo(), St->isVolatile(),
16497                                 St->isNonTemporal(), St->getAlignment());
16498       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16499       Chains.push_back(Ch);
16500     }
16501
16502     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16503                                Chains.size());
16504   }
16505
16506   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16507   // the FP state in cases where an emms may be missing.
16508   // A preferable solution to the general problem is to figure out the right
16509   // places to insert EMMS.  This qualifies as a quick hack.
16510
16511   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16512   if (VT.getSizeInBits() != 64)
16513     return SDValue();
16514
16515   const Function *F = DAG.getMachineFunction().getFunction();
16516   bool NoImplicitFloatOps = F->getFnAttributes().
16517     hasAttribute(Attribute::NoImplicitFloat);
16518   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16519                      && Subtarget->hasSSE2();
16520   if ((VT.isVector() ||
16521        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16522       isa<LoadSDNode>(St->getValue()) &&
16523       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16524       St->getChain().hasOneUse() && !St->isVolatile()) {
16525     SDNode* LdVal = St->getValue().getNode();
16526     LoadSDNode *Ld = 0;
16527     int TokenFactorIndex = -1;
16528     SmallVector<SDValue, 8> Ops;
16529     SDNode* ChainVal = St->getChain().getNode();
16530     // Must be a store of a load.  We currently handle two cases:  the load
16531     // is a direct child, and it's under an intervening TokenFactor.  It is
16532     // possible to dig deeper under nested TokenFactors.
16533     if (ChainVal == LdVal)
16534       Ld = cast<LoadSDNode>(St->getChain());
16535     else if (St->getValue().hasOneUse() &&
16536              ChainVal->getOpcode() == ISD::TokenFactor) {
16537       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16538         if (ChainVal->getOperand(i).getNode() == LdVal) {
16539           TokenFactorIndex = i;
16540           Ld = cast<LoadSDNode>(St->getValue());
16541         } else
16542           Ops.push_back(ChainVal->getOperand(i));
16543       }
16544     }
16545
16546     if (!Ld || !ISD::isNormalLoad(Ld))
16547       return SDValue();
16548
16549     // If this is not the MMX case, i.e. we are just turning i64 load/store
16550     // into f64 load/store, avoid the transformation if there are multiple
16551     // uses of the loaded value.
16552     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16553       return SDValue();
16554
16555     DebugLoc LdDL = Ld->getDebugLoc();
16556     DebugLoc StDL = N->getDebugLoc();
16557     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16558     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16559     // pair instead.
16560     if (Subtarget->is64Bit() || F64IsLegal) {
16561       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16562       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16563                                   Ld->getPointerInfo(), Ld->isVolatile(),
16564                                   Ld->isNonTemporal(), Ld->isInvariant(),
16565                                   Ld->getAlignment());
16566       SDValue NewChain = NewLd.getValue(1);
16567       if (TokenFactorIndex != -1) {
16568         Ops.push_back(NewChain);
16569         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16570                                Ops.size());
16571       }
16572       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16573                           St->getPointerInfo(),
16574                           St->isVolatile(), St->isNonTemporal(),
16575                           St->getAlignment());
16576     }
16577
16578     // Otherwise, lower to two pairs of 32-bit loads / stores.
16579     SDValue LoAddr = Ld->getBasePtr();
16580     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16581                                  DAG.getConstant(4, MVT::i32));
16582
16583     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16584                                Ld->getPointerInfo(),
16585                                Ld->isVolatile(), Ld->isNonTemporal(),
16586                                Ld->isInvariant(), Ld->getAlignment());
16587     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16588                                Ld->getPointerInfo().getWithOffset(4),
16589                                Ld->isVolatile(), Ld->isNonTemporal(),
16590                                Ld->isInvariant(),
16591                                MinAlign(Ld->getAlignment(), 4));
16592
16593     SDValue NewChain = LoLd.getValue(1);
16594     if (TokenFactorIndex != -1) {
16595       Ops.push_back(LoLd);
16596       Ops.push_back(HiLd);
16597       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16598                              Ops.size());
16599     }
16600
16601     LoAddr = St->getBasePtr();
16602     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16603                          DAG.getConstant(4, MVT::i32));
16604
16605     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16606                                 St->getPointerInfo(),
16607                                 St->isVolatile(), St->isNonTemporal(),
16608                                 St->getAlignment());
16609     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16610                                 St->getPointerInfo().getWithOffset(4),
16611                                 St->isVolatile(),
16612                                 St->isNonTemporal(),
16613                                 MinAlign(St->getAlignment(), 4));
16614     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16615   }
16616   return SDValue();
16617 }
16618
16619 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16620 /// and return the operands for the horizontal operation in LHS and RHS.  A
16621 /// horizontal operation performs the binary operation on successive elements
16622 /// of its first operand, then on successive elements of its second operand,
16623 /// returning the resulting values in a vector.  For example, if
16624 ///   A = < float a0, float a1, float a2, float a3 >
16625 /// and
16626 ///   B = < float b0, float b1, float b2, float b3 >
16627 /// then the result of doing a horizontal operation on A and B is
16628 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16629 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16630 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16631 /// set to A, RHS to B, and the routine returns 'true'.
16632 /// Note that the binary operation should have the property that if one of the
16633 /// operands is UNDEF then the result is UNDEF.
16634 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16635   // Look for the following pattern: if
16636   //   A = < float a0, float a1, float a2, float a3 >
16637   //   B = < float b0, float b1, float b2, float b3 >
16638   // and
16639   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16640   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16641   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16642   // which is A horizontal-op B.
16643
16644   // At least one of the operands should be a vector shuffle.
16645   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16646       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16647     return false;
16648
16649   EVT VT = LHS.getValueType();
16650
16651   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16652          "Unsupported vector type for horizontal add/sub");
16653
16654   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16655   // operate independently on 128-bit lanes.
16656   unsigned NumElts = VT.getVectorNumElements();
16657   unsigned NumLanes = VT.getSizeInBits()/128;
16658   unsigned NumLaneElts = NumElts / NumLanes;
16659   assert((NumLaneElts % 2 == 0) &&
16660          "Vector type should have an even number of elements in each lane");
16661   unsigned HalfLaneElts = NumLaneElts/2;
16662
16663   // View LHS in the form
16664   //   LHS = VECTOR_SHUFFLE A, B, LMask
16665   // If LHS is not a shuffle then pretend it is the shuffle
16666   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16667   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16668   // type VT.
16669   SDValue A, B;
16670   SmallVector<int, 16> LMask(NumElts);
16671   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16672     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16673       A = LHS.getOperand(0);
16674     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16675       B = LHS.getOperand(1);
16676     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16677     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16678   } else {
16679     if (LHS.getOpcode() != ISD::UNDEF)
16680       A = LHS;
16681     for (unsigned i = 0; i != NumElts; ++i)
16682       LMask[i] = i;
16683   }
16684
16685   // Likewise, view RHS in the form
16686   //   RHS = VECTOR_SHUFFLE C, D, RMask
16687   SDValue C, D;
16688   SmallVector<int, 16> RMask(NumElts);
16689   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16690     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16691       C = RHS.getOperand(0);
16692     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16693       D = RHS.getOperand(1);
16694     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16695     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16696   } else {
16697     if (RHS.getOpcode() != ISD::UNDEF)
16698       C = RHS;
16699     for (unsigned i = 0; i != NumElts; ++i)
16700       RMask[i] = i;
16701   }
16702
16703   // Check that the shuffles are both shuffling the same vectors.
16704   if (!(A == C && B == D) && !(A == D && B == C))
16705     return false;
16706
16707   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16708   if (!A.getNode() && !B.getNode())
16709     return false;
16710
16711   // If A and B occur in reverse order in RHS, then "swap" them (which means
16712   // rewriting the mask).
16713   if (A != C)
16714     CommuteVectorShuffleMask(RMask, NumElts);
16715
16716   // At this point LHS and RHS are equivalent to
16717   //   LHS = VECTOR_SHUFFLE A, B, LMask
16718   //   RHS = VECTOR_SHUFFLE A, B, RMask
16719   // Check that the masks correspond to performing a horizontal operation.
16720   for (unsigned i = 0; i != NumElts; ++i) {
16721     int LIdx = LMask[i], RIdx = RMask[i];
16722
16723     // Ignore any UNDEF components.
16724     if (LIdx < 0 || RIdx < 0 ||
16725         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16726         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16727       continue;
16728
16729     // Check that successive elements are being operated on.  If not, this is
16730     // not a horizontal operation.
16731     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16732     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16733     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16734     if (!(LIdx == Index && RIdx == Index + 1) &&
16735         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16736       return false;
16737   }
16738
16739   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16740   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16741   return true;
16742 }
16743
16744 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16745 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16746                                   const X86Subtarget *Subtarget) {
16747   EVT VT = N->getValueType(0);
16748   SDValue LHS = N->getOperand(0);
16749   SDValue RHS = N->getOperand(1);
16750
16751   // Try to synthesize horizontal adds from adds of shuffles.
16752   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16753        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16754       isHorizontalBinOp(LHS, RHS, true))
16755     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16756   return SDValue();
16757 }
16758
16759 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16760 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16761                                   const X86Subtarget *Subtarget) {
16762   EVT VT = N->getValueType(0);
16763   SDValue LHS = N->getOperand(0);
16764   SDValue RHS = N->getOperand(1);
16765
16766   // Try to synthesize horizontal subs from subs of shuffles.
16767   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16768        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16769       isHorizontalBinOp(LHS, RHS, false))
16770     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16771   return SDValue();
16772 }
16773
16774 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16775 /// X86ISD::FXOR nodes.
16776 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16777   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16778   // F[X]OR(0.0, x) -> x
16779   // F[X]OR(x, 0.0) -> x
16780   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16781     if (C->getValueAPF().isPosZero())
16782       return N->getOperand(1);
16783   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16784     if (C->getValueAPF().isPosZero())
16785       return N->getOperand(0);
16786   return SDValue();
16787 }
16788
16789 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16790 /// X86ISD::FMAX nodes.
16791 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16792   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16793
16794   // Only perform optimizations if UnsafeMath is used.
16795   if (!DAG.getTarget().Options.UnsafeFPMath)
16796     return SDValue();
16797
16798   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16799   // into FMINC and FMAXC, which are Commutative operations.
16800   unsigned NewOp = 0;
16801   switch (N->getOpcode()) {
16802     default: llvm_unreachable("unknown opcode");
16803     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16804     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16805   }
16806
16807   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16808                      N->getOperand(0), N->getOperand(1));
16809 }
16810
16811 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16812 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16813   // FAND(0.0, x) -> 0.0
16814   // FAND(x, 0.0) -> 0.0
16815   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16816     if (C->getValueAPF().isPosZero())
16817       return N->getOperand(0);
16818   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16819     if (C->getValueAPF().isPosZero())
16820       return N->getOperand(1);
16821   return SDValue();
16822 }
16823
16824 static SDValue PerformBTCombine(SDNode *N,
16825                                 SelectionDAG &DAG,
16826                                 TargetLowering::DAGCombinerInfo &DCI) {
16827   // BT ignores high bits in the bit index operand.
16828   SDValue Op1 = N->getOperand(1);
16829   if (Op1.hasOneUse()) {
16830     unsigned BitWidth = Op1.getValueSizeInBits();
16831     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16832     APInt KnownZero, KnownOne;
16833     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16834                                           !DCI.isBeforeLegalizeOps());
16835     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16836     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16837         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16838       DCI.CommitTargetLoweringOpt(TLO);
16839   }
16840   return SDValue();
16841 }
16842
16843 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16844   SDValue Op = N->getOperand(0);
16845   if (Op.getOpcode() == ISD::BITCAST)
16846     Op = Op.getOperand(0);
16847   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16848   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16849       VT.getVectorElementType().getSizeInBits() ==
16850       OpVT.getVectorElementType().getSizeInBits()) {
16851     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16852   }
16853   return SDValue();
16854 }
16855
16856 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16857                                   TargetLowering::DAGCombinerInfo &DCI,
16858                                   const X86Subtarget *Subtarget) {
16859   if (!DCI.isBeforeLegalizeOps())
16860     return SDValue();
16861
16862   if (!Subtarget->hasFp256())
16863     return SDValue();
16864
16865   EVT VT = N->getValueType(0);
16866   if (VT.isVector() && VT.getSizeInBits() == 256) {
16867     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
16868     if (R.getNode())
16869       return R;
16870   }
16871
16872   return SDValue();
16873 }
16874
16875 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16876                                  const X86Subtarget* Subtarget) {
16877   DebugLoc dl = N->getDebugLoc();
16878   EVT VT = N->getValueType(0);
16879
16880   // Let legalize expand this if it isn't a legal type yet.
16881   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16882     return SDValue();
16883
16884   EVT ScalarVT = VT.getScalarType();
16885   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16886       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16887     return SDValue();
16888
16889   SDValue A = N->getOperand(0);
16890   SDValue B = N->getOperand(1);
16891   SDValue C = N->getOperand(2);
16892
16893   bool NegA = (A.getOpcode() == ISD::FNEG);
16894   bool NegB = (B.getOpcode() == ISD::FNEG);
16895   bool NegC = (C.getOpcode() == ISD::FNEG);
16896
16897   // Negative multiplication when NegA xor NegB
16898   bool NegMul = (NegA != NegB);
16899   if (NegA)
16900     A = A.getOperand(0);
16901   if (NegB)
16902     B = B.getOperand(0);
16903   if (NegC)
16904     C = C.getOperand(0);
16905
16906   unsigned Opcode;
16907   if (!NegMul)
16908     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16909   else
16910     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16911
16912   return DAG.getNode(Opcode, dl, VT, A, B, C);
16913 }
16914
16915 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16916                                   TargetLowering::DAGCombinerInfo &DCI,
16917                                   const X86Subtarget *Subtarget) {
16918   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16919   //           (and (i32 x86isd::setcc_carry), 1)
16920   // This eliminates the zext. This transformation is necessary because
16921   // ISD::SETCC is always legalized to i8.
16922   DebugLoc dl = N->getDebugLoc();
16923   SDValue N0 = N->getOperand(0);
16924   EVT VT = N->getValueType(0);
16925
16926   if (N0.getOpcode() == ISD::AND &&
16927       N0.hasOneUse() &&
16928       N0.getOperand(0).hasOneUse()) {
16929     SDValue N00 = N0.getOperand(0);
16930     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
16931       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16932       if (!C || C->getZExtValue() != 1)
16933         return SDValue();
16934       return DAG.getNode(ISD::AND, dl, VT,
16935                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16936                                      N00.getOperand(0), N00.getOperand(1)),
16937                          DAG.getConstant(1, VT));
16938     }
16939   }
16940
16941   if (VT.isVector() && VT.getSizeInBits() == 256) {
16942     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
16943     if (R.getNode())
16944       return R;
16945   }
16946
16947   return SDValue();
16948 }
16949
16950 // Optimize x == -y --> x+y == 0
16951 //          x != -y --> x+y != 0
16952 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16953   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16954   SDValue LHS = N->getOperand(0);
16955   SDValue RHS = N->getOperand(1);
16956
16957   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16958     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16959       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16960         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16961                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16962         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16963                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16964       }
16965   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16966     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16967       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16968         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16969                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16970         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16971                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16972       }
16973   return SDValue();
16974 }
16975
16976 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
16977 // as "sbb reg,reg", since it can be extended without zext and produces 
16978 // an all-ones bit which is more useful than 0/1 in some cases.
16979 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16980   return DAG.getNode(ISD::AND, DL, MVT::i8,
16981                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16982                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16983                      DAG.getConstant(1, MVT::i8));
16984 }
16985
16986 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16987 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16988                                    TargetLowering::DAGCombinerInfo &DCI,
16989                                    const X86Subtarget *Subtarget) {
16990   DebugLoc DL = N->getDebugLoc();
16991   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16992   SDValue EFLAGS = N->getOperand(1);
16993
16994   if (CC == X86::COND_A) {
16995     // Try to convert COND_A into COND_B in an attempt to facilitate 
16996     // materializing "setb reg".
16997     //
16998     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16999     // cannot take an immediate as its first operand.
17000     //
17001     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
17002         EFLAGS.getValueType().isInteger() &&
17003         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17004       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17005                                    EFLAGS.getNode()->getVTList(),
17006                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17007       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17008       return MaterializeSETB(DL, NewEFLAGS, DAG);
17009     }
17010   }
17011
17012   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17013   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17014   // cases.
17015   if (CC == X86::COND_B)
17016     return MaterializeSETB(DL, EFLAGS, DAG);
17017
17018   SDValue Flags;
17019
17020   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17021   if (Flags.getNode()) {
17022     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17023     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17024   }
17025
17026   return SDValue();
17027 }
17028
17029 // Optimize branch condition evaluation.
17030 //
17031 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17032                                     TargetLowering::DAGCombinerInfo &DCI,
17033                                     const X86Subtarget *Subtarget) {
17034   DebugLoc DL = N->getDebugLoc();
17035   SDValue Chain = N->getOperand(0);
17036   SDValue Dest = N->getOperand(1);
17037   SDValue EFLAGS = N->getOperand(3);
17038   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17039
17040   SDValue Flags;
17041
17042   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17043   if (Flags.getNode()) {
17044     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17045     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17046                        Flags);
17047   }
17048
17049   return SDValue();
17050 }
17051
17052 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17053                                         const X86TargetLowering *XTLI) {
17054   SDValue Op0 = N->getOperand(0);
17055   EVT InVT = Op0->getValueType(0);
17056
17057   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17058   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17059     DebugLoc dl = N->getDebugLoc();
17060     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17061     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17062     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17063   }
17064
17065   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17066   // a 32-bit target where SSE doesn't support i64->FP operations.
17067   if (Op0.getOpcode() == ISD::LOAD) {
17068     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17069     EVT VT = Ld->getValueType(0);
17070     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17071         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17072         !XTLI->getSubtarget()->is64Bit() &&
17073         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17074       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17075                                           Ld->getChain(), Op0, DAG);
17076       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17077       return FILDChain;
17078     }
17079   }
17080   return SDValue();
17081 }
17082
17083 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17084 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17085                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17086   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17087   // the result is either zero or one (depending on the input carry bit).
17088   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17089   if (X86::isZeroNode(N->getOperand(0)) &&
17090       X86::isZeroNode(N->getOperand(1)) &&
17091       // We don't have a good way to replace an EFLAGS use, so only do this when
17092       // dead right now.
17093       SDValue(N, 1).use_empty()) {
17094     DebugLoc DL = N->getDebugLoc();
17095     EVT VT = N->getValueType(0);
17096     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17097     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17098                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17099                                            DAG.getConstant(X86::COND_B,MVT::i8),
17100                                            N->getOperand(2)),
17101                                DAG.getConstant(1, VT));
17102     return DCI.CombineTo(N, Res1, CarryOut);
17103   }
17104
17105   return SDValue();
17106 }
17107
17108 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17109 //      (add Y, (setne X, 0)) -> sbb -1, Y
17110 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17111 //      (sub (setne X, 0), Y) -> adc -1, Y
17112 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17113   DebugLoc DL = N->getDebugLoc();
17114
17115   // Look through ZExts.
17116   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17117   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17118     return SDValue();
17119
17120   SDValue SetCC = Ext.getOperand(0);
17121   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17122     return SDValue();
17123
17124   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17125   if (CC != X86::COND_E && CC != X86::COND_NE)
17126     return SDValue();
17127
17128   SDValue Cmp = SetCC.getOperand(1);
17129   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17130       !X86::isZeroNode(Cmp.getOperand(1)) ||
17131       !Cmp.getOperand(0).getValueType().isInteger())
17132     return SDValue();
17133
17134   SDValue CmpOp0 = Cmp.getOperand(0);
17135   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17136                                DAG.getConstant(1, CmpOp0.getValueType()));
17137
17138   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17139   if (CC == X86::COND_NE)
17140     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17141                        DL, OtherVal.getValueType(), OtherVal,
17142                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17143   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17144                      DL, OtherVal.getValueType(), OtherVal,
17145                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17146 }
17147
17148 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17149 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17150                                  const X86Subtarget *Subtarget) {
17151   EVT VT = N->getValueType(0);
17152   SDValue Op0 = N->getOperand(0);
17153   SDValue Op1 = N->getOperand(1);
17154
17155   // Try to synthesize horizontal adds from adds of shuffles.
17156   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17157        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17158       isHorizontalBinOp(Op0, Op1, true))
17159     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17160
17161   return OptimizeConditionalInDecrement(N, DAG);
17162 }
17163
17164 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17165                                  const X86Subtarget *Subtarget) {
17166   SDValue Op0 = N->getOperand(0);
17167   SDValue Op1 = N->getOperand(1);
17168
17169   // X86 can't encode an immediate LHS of a sub. See if we can push the
17170   // negation into a preceding instruction.
17171   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17172     // If the RHS of the sub is a XOR with one use and a constant, invert the
17173     // immediate. Then add one to the LHS of the sub so we can turn
17174     // X-Y -> X+~Y+1, saving one register.
17175     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17176         isa<ConstantSDNode>(Op1.getOperand(1))) {
17177       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17178       EVT VT = Op0.getValueType();
17179       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17180                                    Op1.getOperand(0),
17181                                    DAG.getConstant(~XorC, VT));
17182       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17183                          DAG.getConstant(C->getAPIntValue()+1, VT));
17184     }
17185   }
17186
17187   // Try to synthesize horizontal adds from adds of shuffles.
17188   EVT VT = N->getValueType(0);
17189   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17190        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17191       isHorizontalBinOp(Op0, Op1, true))
17192     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17193
17194   return OptimizeConditionalInDecrement(N, DAG);
17195 }
17196
17197 /// performVZEXTCombine - Performs build vector combines
17198 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17199                                         TargetLowering::DAGCombinerInfo &DCI,
17200                                         const X86Subtarget *Subtarget) {
17201   // (vzext (bitcast (vzext (x)) -> (vzext x)
17202   SDValue In = N->getOperand(0);
17203   while (In.getOpcode() == ISD::BITCAST)
17204     In = In.getOperand(0);
17205
17206   if (In.getOpcode() != X86ISD::VZEXT)
17207     return SDValue();
17208
17209   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17210 }
17211
17212 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17213                                              DAGCombinerInfo &DCI) const {
17214   SelectionDAG &DAG = DCI.DAG;
17215   switch (N->getOpcode()) {
17216   default: break;
17217   case ISD::EXTRACT_VECTOR_ELT:
17218     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17219   case ISD::VSELECT:
17220   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17221   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17222   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17223   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17224   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17225   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17226   case ISD::SHL:
17227   case ISD::SRA:
17228   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17229   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17230   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17231   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17232   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17233   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17234   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17235   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17236   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17237   case X86ISD::FXOR:
17238   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17239   case X86ISD::FMIN:
17240   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17241   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17242   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17243   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17244   case ISD::ANY_EXTEND:
17245   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17246   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17247   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17248   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17249   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17250   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17251   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17252   case X86ISD::SHUFP:       // Handle all target specific shuffles
17253   case X86ISD::PALIGN:
17254   case X86ISD::UNPCKH:
17255   case X86ISD::UNPCKL:
17256   case X86ISD::MOVHLPS:
17257   case X86ISD::MOVLHPS:
17258   case X86ISD::PSHUFD:
17259   case X86ISD::PSHUFHW:
17260   case X86ISD::PSHUFLW:
17261   case X86ISD::MOVSS:
17262   case X86ISD::MOVSD:
17263   case X86ISD::VPERMILP:
17264   case X86ISD::VPERM2X128:
17265   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17266   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17267   }
17268
17269   return SDValue();
17270 }
17271
17272 /// isTypeDesirableForOp - Return true if the target has native support for
17273 /// the specified value type and it is 'desirable' to use the type for the
17274 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17275 /// instruction encodings are longer and some i16 instructions are slow.
17276 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17277   if (!isTypeLegal(VT))
17278     return false;
17279   if (VT != MVT::i16)
17280     return true;
17281
17282   switch (Opc) {
17283   default:
17284     return true;
17285   case ISD::LOAD:
17286   case ISD::SIGN_EXTEND:
17287   case ISD::ZERO_EXTEND:
17288   case ISD::ANY_EXTEND:
17289   case ISD::SHL:
17290   case ISD::SRL:
17291   case ISD::SUB:
17292   case ISD::ADD:
17293   case ISD::MUL:
17294   case ISD::AND:
17295   case ISD::OR:
17296   case ISD::XOR:
17297     return false;
17298   }
17299 }
17300
17301 /// IsDesirableToPromoteOp - This method query the target whether it is
17302 /// beneficial for dag combiner to promote the specified node. If true, it
17303 /// should return the desired promotion type by reference.
17304 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17305   EVT VT = Op.getValueType();
17306   if (VT != MVT::i16)
17307     return false;
17308
17309   bool Promote = false;
17310   bool Commute = false;
17311   switch (Op.getOpcode()) {
17312   default: break;
17313   case ISD::LOAD: {
17314     LoadSDNode *LD = cast<LoadSDNode>(Op);
17315     // If the non-extending load has a single use and it's not live out, then it
17316     // might be folded.
17317     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17318                                                      Op.hasOneUse()*/) {
17319       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17320              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17321         // The only case where we'd want to promote LOAD (rather then it being
17322         // promoted as an operand is when it's only use is liveout.
17323         if (UI->getOpcode() != ISD::CopyToReg)
17324           return false;
17325       }
17326     }
17327     Promote = true;
17328     break;
17329   }
17330   case ISD::SIGN_EXTEND:
17331   case ISD::ZERO_EXTEND:
17332   case ISD::ANY_EXTEND:
17333     Promote = true;
17334     break;
17335   case ISD::SHL:
17336   case ISD::SRL: {
17337     SDValue N0 = Op.getOperand(0);
17338     // Look out for (store (shl (load), x)).
17339     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17340       return false;
17341     Promote = true;
17342     break;
17343   }
17344   case ISD::ADD:
17345   case ISD::MUL:
17346   case ISD::AND:
17347   case ISD::OR:
17348   case ISD::XOR:
17349     Commute = true;
17350     // fallthrough
17351   case ISD::SUB: {
17352     SDValue N0 = Op.getOperand(0);
17353     SDValue N1 = Op.getOperand(1);
17354     if (!Commute && MayFoldLoad(N1))
17355       return false;
17356     // Avoid disabling potential load folding opportunities.
17357     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17358       return false;
17359     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17360       return false;
17361     Promote = true;
17362   }
17363   }
17364
17365   PVT = MVT::i32;
17366   return Promote;
17367 }
17368
17369 //===----------------------------------------------------------------------===//
17370 //                           X86 Inline Assembly Support
17371 //===----------------------------------------------------------------------===//
17372
17373 namespace {
17374   // Helper to match a string separated by whitespace.
17375   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17376     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17377
17378     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17379       StringRef piece(*args[i]);
17380       if (!s.startswith(piece)) // Check if the piece matches.
17381         return false;
17382
17383       s = s.substr(piece.size());
17384       StringRef::size_type pos = s.find_first_not_of(" \t");
17385       if (pos == 0) // We matched a prefix.
17386         return false;
17387
17388       s = s.substr(pos);
17389     }
17390
17391     return s.empty();
17392   }
17393   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17394 }
17395
17396 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17397   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17398
17399   std::string AsmStr = IA->getAsmString();
17400
17401   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17402   if (!Ty || Ty->getBitWidth() % 16 != 0)
17403     return false;
17404
17405   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17406   SmallVector<StringRef, 4> AsmPieces;
17407   SplitString(AsmStr, AsmPieces, ";\n");
17408
17409   switch (AsmPieces.size()) {
17410   default: return false;
17411   case 1:
17412     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17413     // we will turn this bswap into something that will be lowered to logical
17414     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17415     // lower so don't worry about this.
17416     // bswap $0
17417     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17418         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17419         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17420         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17421         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17422         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17423       // No need to check constraints, nothing other than the equivalent of
17424       // "=r,0" would be valid here.
17425       return IntrinsicLowering::LowerToByteSwap(CI);
17426     }
17427
17428     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17429     if (CI->getType()->isIntegerTy(16) &&
17430         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17431         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17432          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17433       AsmPieces.clear();
17434       const std::string &ConstraintsStr = IA->getConstraintString();
17435       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17436       std::sort(AsmPieces.begin(), AsmPieces.end());
17437       if (AsmPieces.size() == 4 &&
17438           AsmPieces[0] == "~{cc}" &&
17439           AsmPieces[1] == "~{dirflag}" &&
17440           AsmPieces[2] == "~{flags}" &&
17441           AsmPieces[3] == "~{fpsr}")
17442       return IntrinsicLowering::LowerToByteSwap(CI);
17443     }
17444     break;
17445   case 3:
17446     if (CI->getType()->isIntegerTy(32) &&
17447         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17448         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17449         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17450         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17451       AsmPieces.clear();
17452       const std::string &ConstraintsStr = IA->getConstraintString();
17453       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17454       std::sort(AsmPieces.begin(), AsmPieces.end());
17455       if (AsmPieces.size() == 4 &&
17456           AsmPieces[0] == "~{cc}" &&
17457           AsmPieces[1] == "~{dirflag}" &&
17458           AsmPieces[2] == "~{flags}" &&
17459           AsmPieces[3] == "~{fpsr}")
17460         return IntrinsicLowering::LowerToByteSwap(CI);
17461     }
17462
17463     if (CI->getType()->isIntegerTy(64)) {
17464       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17465       if (Constraints.size() >= 2 &&
17466           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17467           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17468         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17469         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17470             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17471             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17472           return IntrinsicLowering::LowerToByteSwap(CI);
17473       }
17474     }
17475     break;
17476   }
17477   return false;
17478 }
17479
17480 /// getConstraintType - Given a constraint letter, return the type of
17481 /// constraint it is for this target.
17482 X86TargetLowering::ConstraintType
17483 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17484   if (Constraint.size() == 1) {
17485     switch (Constraint[0]) {
17486     case 'R':
17487     case 'q':
17488     case 'Q':
17489     case 'f':
17490     case 't':
17491     case 'u':
17492     case 'y':
17493     case 'x':
17494     case 'Y':
17495     case 'l':
17496       return C_RegisterClass;
17497     case 'a':
17498     case 'b':
17499     case 'c':
17500     case 'd':
17501     case 'S':
17502     case 'D':
17503     case 'A':
17504       return C_Register;
17505     case 'I':
17506     case 'J':
17507     case 'K':
17508     case 'L':
17509     case 'M':
17510     case 'N':
17511     case 'G':
17512     case 'C':
17513     case 'e':
17514     case 'Z':
17515       return C_Other;
17516     default:
17517       break;
17518     }
17519   }
17520   return TargetLowering::getConstraintType(Constraint);
17521 }
17522
17523 /// Examine constraint type and operand type and determine a weight value.
17524 /// This object must already have been set up with the operand type
17525 /// and the current alternative constraint selected.
17526 TargetLowering::ConstraintWeight
17527   X86TargetLowering::getSingleConstraintMatchWeight(
17528     AsmOperandInfo &info, const char *constraint) const {
17529   ConstraintWeight weight = CW_Invalid;
17530   Value *CallOperandVal = info.CallOperandVal;
17531     // If we don't have a value, we can't do a match,
17532     // but allow it at the lowest weight.
17533   if (CallOperandVal == NULL)
17534     return CW_Default;
17535   Type *type = CallOperandVal->getType();
17536   // Look at the constraint type.
17537   switch (*constraint) {
17538   default:
17539     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17540   case 'R':
17541   case 'q':
17542   case 'Q':
17543   case 'a':
17544   case 'b':
17545   case 'c':
17546   case 'd':
17547   case 'S':
17548   case 'D':
17549   case 'A':
17550     if (CallOperandVal->getType()->isIntegerTy())
17551       weight = CW_SpecificReg;
17552     break;
17553   case 'f':
17554   case 't':
17555   case 'u':
17556       if (type->isFloatingPointTy())
17557         weight = CW_SpecificReg;
17558       break;
17559   case 'y':
17560       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17561         weight = CW_SpecificReg;
17562       break;
17563   case 'x':
17564   case 'Y':
17565     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17566         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17567       weight = CW_Register;
17568     break;
17569   case 'I':
17570     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17571       if (C->getZExtValue() <= 31)
17572         weight = CW_Constant;
17573     }
17574     break;
17575   case 'J':
17576     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17577       if (C->getZExtValue() <= 63)
17578         weight = CW_Constant;
17579     }
17580     break;
17581   case 'K':
17582     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17583       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17584         weight = CW_Constant;
17585     }
17586     break;
17587   case 'L':
17588     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17589       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17590         weight = CW_Constant;
17591     }
17592     break;
17593   case 'M':
17594     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17595       if (C->getZExtValue() <= 3)
17596         weight = CW_Constant;
17597     }
17598     break;
17599   case 'N':
17600     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17601       if (C->getZExtValue() <= 0xff)
17602         weight = CW_Constant;
17603     }
17604     break;
17605   case 'G':
17606   case 'C':
17607     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17608       weight = CW_Constant;
17609     }
17610     break;
17611   case 'e':
17612     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17613       if ((C->getSExtValue() >= -0x80000000LL) &&
17614           (C->getSExtValue() <= 0x7fffffffLL))
17615         weight = CW_Constant;
17616     }
17617     break;
17618   case 'Z':
17619     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17620       if (C->getZExtValue() <= 0xffffffff)
17621         weight = CW_Constant;
17622     }
17623     break;
17624   }
17625   return weight;
17626 }
17627
17628 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17629 /// with another that has more specific requirements based on the type of the
17630 /// corresponding operand.
17631 const char *X86TargetLowering::
17632 LowerXConstraint(EVT ConstraintVT) const {
17633   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17634   // 'f' like normal targets.
17635   if (ConstraintVT.isFloatingPoint()) {
17636     if (Subtarget->hasSSE2())
17637       return "Y";
17638     if (Subtarget->hasSSE1())
17639       return "x";
17640   }
17641
17642   return TargetLowering::LowerXConstraint(ConstraintVT);
17643 }
17644
17645 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17646 /// vector.  If it is invalid, don't add anything to Ops.
17647 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17648                                                      std::string &Constraint,
17649                                                      std::vector<SDValue>&Ops,
17650                                                      SelectionDAG &DAG) const {
17651   SDValue Result(0, 0);
17652
17653   // Only support length 1 constraints for now.
17654   if (Constraint.length() > 1) return;
17655
17656   char ConstraintLetter = Constraint[0];
17657   switch (ConstraintLetter) {
17658   default: break;
17659   case 'I':
17660     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17661       if (C->getZExtValue() <= 31) {
17662         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17663         break;
17664       }
17665     }
17666     return;
17667   case 'J':
17668     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17669       if (C->getZExtValue() <= 63) {
17670         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17671         break;
17672       }
17673     }
17674     return;
17675   case 'K':
17676     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17677       if (isInt<8>(C->getSExtValue())) {
17678         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17679         break;
17680       }
17681     }
17682     return;
17683   case 'N':
17684     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17685       if (C->getZExtValue() <= 255) {
17686         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17687         break;
17688       }
17689     }
17690     return;
17691   case 'e': {
17692     // 32-bit signed value
17693     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17694       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17695                                            C->getSExtValue())) {
17696         // Widen to 64 bits here to get it sign extended.
17697         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17698         break;
17699       }
17700     // FIXME gcc accepts some relocatable values here too, but only in certain
17701     // memory models; it's complicated.
17702     }
17703     return;
17704   }
17705   case 'Z': {
17706     // 32-bit unsigned value
17707     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17708       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17709                                            C->getZExtValue())) {
17710         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17711         break;
17712       }
17713     }
17714     // FIXME gcc accepts some relocatable values here too, but only in certain
17715     // memory models; it's complicated.
17716     return;
17717   }
17718   case 'i': {
17719     // Literal immediates are always ok.
17720     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17721       // Widen to 64 bits here to get it sign extended.
17722       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17723       break;
17724     }
17725
17726     // In any sort of PIC mode addresses need to be computed at runtime by
17727     // adding in a register or some sort of table lookup.  These can't
17728     // be used as immediates.
17729     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17730       return;
17731
17732     // If we are in non-pic codegen mode, we allow the address of a global (with
17733     // an optional displacement) to be used with 'i'.
17734     GlobalAddressSDNode *GA = 0;
17735     int64_t Offset = 0;
17736
17737     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17738     while (1) {
17739       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17740         Offset += GA->getOffset();
17741         break;
17742       } else if (Op.getOpcode() == ISD::ADD) {
17743         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17744           Offset += C->getZExtValue();
17745           Op = Op.getOperand(0);
17746           continue;
17747         }
17748       } else if (Op.getOpcode() == ISD::SUB) {
17749         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17750           Offset += -C->getZExtValue();
17751           Op = Op.getOperand(0);
17752           continue;
17753         }
17754       }
17755
17756       // Otherwise, this isn't something we can handle, reject it.
17757       return;
17758     }
17759
17760     const GlobalValue *GV = GA->getGlobal();
17761     // If we require an extra load to get this address, as in PIC mode, we
17762     // can't accept it.
17763     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17764                                                         getTargetMachine())))
17765       return;
17766
17767     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17768                                         GA->getValueType(0), Offset);
17769     break;
17770   }
17771   }
17772
17773   if (Result.getNode()) {
17774     Ops.push_back(Result);
17775     return;
17776   }
17777   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17778 }
17779
17780 std::pair<unsigned, const TargetRegisterClass*>
17781 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17782                                                 EVT VT) const {
17783   // First, see if this is a constraint that directly corresponds to an LLVM
17784   // register class.
17785   if (Constraint.size() == 1) {
17786     // GCC Constraint Letters
17787     switch (Constraint[0]) {
17788     default: break;
17789       // TODO: Slight differences here in allocation order and leaving
17790       // RIP in the class. Do they matter any more here than they do
17791       // in the normal allocation?
17792     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17793       if (Subtarget->is64Bit()) {
17794         if (VT == MVT::i32 || VT == MVT::f32)
17795           return std::make_pair(0U, &X86::GR32RegClass);
17796         if (VT == MVT::i16)
17797           return std::make_pair(0U, &X86::GR16RegClass);
17798         if (VT == MVT::i8 || VT == MVT::i1)
17799           return std::make_pair(0U, &X86::GR8RegClass);
17800         if (VT == MVT::i64 || VT == MVT::f64)
17801           return std::make_pair(0U, &X86::GR64RegClass);
17802         break;
17803       }
17804       // 32-bit fallthrough
17805     case 'Q':   // Q_REGS
17806       if (VT == MVT::i32 || VT == MVT::f32)
17807         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17808       if (VT == MVT::i16)
17809         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17810       if (VT == MVT::i8 || VT == MVT::i1)
17811         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17812       if (VT == MVT::i64)
17813         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17814       break;
17815     case 'r':   // GENERAL_REGS
17816     case 'l':   // INDEX_REGS
17817       if (VT == MVT::i8 || VT == MVT::i1)
17818         return std::make_pair(0U, &X86::GR8RegClass);
17819       if (VT == MVT::i16)
17820         return std::make_pair(0U, &X86::GR16RegClass);
17821       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17822         return std::make_pair(0U, &X86::GR32RegClass);
17823       return std::make_pair(0U, &X86::GR64RegClass);
17824     case 'R':   // LEGACY_REGS
17825       if (VT == MVT::i8 || VT == MVT::i1)
17826         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17827       if (VT == MVT::i16)
17828         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17829       if (VT == MVT::i32 || !Subtarget->is64Bit())
17830         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17831       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17832     case 'f':  // FP Stack registers.
17833       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17834       // value to the correct fpstack register class.
17835       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17836         return std::make_pair(0U, &X86::RFP32RegClass);
17837       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17838         return std::make_pair(0U, &X86::RFP64RegClass);
17839       return std::make_pair(0U, &X86::RFP80RegClass);
17840     case 'y':   // MMX_REGS if MMX allowed.
17841       if (!Subtarget->hasMMX()) break;
17842       return std::make_pair(0U, &X86::VR64RegClass);
17843     case 'Y':   // SSE_REGS if SSE2 allowed
17844       if (!Subtarget->hasSSE2()) break;
17845       // FALL THROUGH.
17846     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17847       if (!Subtarget->hasSSE1()) break;
17848
17849       switch (VT.getSimpleVT().SimpleTy) {
17850       default: break;
17851       // Scalar SSE types.
17852       case MVT::f32:
17853       case MVT::i32:
17854         return std::make_pair(0U, &X86::FR32RegClass);
17855       case MVT::f64:
17856       case MVT::i64:
17857         return std::make_pair(0U, &X86::FR64RegClass);
17858       // Vector types.
17859       case MVT::v16i8:
17860       case MVT::v8i16:
17861       case MVT::v4i32:
17862       case MVT::v2i64:
17863       case MVT::v4f32:
17864       case MVT::v2f64:
17865         return std::make_pair(0U, &X86::VR128RegClass);
17866       // AVX types.
17867       case MVT::v32i8:
17868       case MVT::v16i16:
17869       case MVT::v8i32:
17870       case MVT::v4i64:
17871       case MVT::v8f32:
17872       case MVT::v4f64:
17873         return std::make_pair(0U, &X86::VR256RegClass);
17874       }
17875       break;
17876     }
17877   }
17878
17879   // Use the default implementation in TargetLowering to convert the register
17880   // constraint into a member of a register class.
17881   std::pair<unsigned, const TargetRegisterClass*> Res;
17882   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17883
17884   // Not found as a standard register?
17885   if (Res.second == 0) {
17886     // Map st(0) -> st(7) -> ST0
17887     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17888         tolower(Constraint[1]) == 's' &&
17889         tolower(Constraint[2]) == 't' &&
17890         Constraint[3] == '(' &&
17891         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17892         Constraint[5] == ')' &&
17893         Constraint[6] == '}') {
17894
17895       Res.first = X86::ST0+Constraint[4]-'0';
17896       Res.second = &X86::RFP80RegClass;
17897       return Res;
17898     }
17899
17900     // GCC allows "st(0)" to be called just plain "st".
17901     if (StringRef("{st}").equals_lower(Constraint)) {
17902       Res.first = X86::ST0;
17903       Res.second = &X86::RFP80RegClass;
17904       return Res;
17905     }
17906
17907     // flags -> EFLAGS
17908     if (StringRef("{flags}").equals_lower(Constraint)) {
17909       Res.first = X86::EFLAGS;
17910       Res.second = &X86::CCRRegClass;
17911       return Res;
17912     }
17913
17914     // 'A' means EAX + EDX.
17915     if (Constraint == "A") {
17916       Res.first = X86::EAX;
17917       Res.second = &X86::GR32_ADRegClass;
17918       return Res;
17919     }
17920     return Res;
17921   }
17922
17923   // Otherwise, check to see if this is a register class of the wrong value
17924   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17925   // turn into {ax},{dx}.
17926   if (Res.second->hasType(VT))
17927     return Res;   // Correct type already, nothing to do.
17928
17929   // All of the single-register GCC register classes map their values onto
17930   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17931   // really want an 8-bit or 32-bit register, map to the appropriate register
17932   // class and return the appropriate register.
17933   if (Res.second == &X86::GR16RegClass) {
17934     if (VT == MVT::i8) {
17935       unsigned DestReg = 0;
17936       switch (Res.first) {
17937       default: break;
17938       case X86::AX: DestReg = X86::AL; break;
17939       case X86::DX: DestReg = X86::DL; break;
17940       case X86::CX: DestReg = X86::CL; break;
17941       case X86::BX: DestReg = X86::BL; break;
17942       }
17943       if (DestReg) {
17944         Res.first = DestReg;
17945         Res.second = &X86::GR8RegClass;
17946       }
17947     } else if (VT == MVT::i32) {
17948       unsigned DestReg = 0;
17949       switch (Res.first) {
17950       default: break;
17951       case X86::AX: DestReg = X86::EAX; break;
17952       case X86::DX: DestReg = X86::EDX; break;
17953       case X86::CX: DestReg = X86::ECX; break;
17954       case X86::BX: DestReg = X86::EBX; break;
17955       case X86::SI: DestReg = X86::ESI; break;
17956       case X86::DI: DestReg = X86::EDI; break;
17957       case X86::BP: DestReg = X86::EBP; break;
17958       case X86::SP: DestReg = X86::ESP; break;
17959       }
17960       if (DestReg) {
17961         Res.first = DestReg;
17962         Res.second = &X86::GR32RegClass;
17963       }
17964     } else if (VT == MVT::i64) {
17965       unsigned DestReg = 0;
17966       switch (Res.first) {
17967       default: break;
17968       case X86::AX: DestReg = X86::RAX; break;
17969       case X86::DX: DestReg = X86::RDX; break;
17970       case X86::CX: DestReg = X86::RCX; break;
17971       case X86::BX: DestReg = X86::RBX; break;
17972       case X86::SI: DestReg = X86::RSI; break;
17973       case X86::DI: DestReg = X86::RDI; break;
17974       case X86::BP: DestReg = X86::RBP; break;
17975       case X86::SP: DestReg = X86::RSP; break;
17976       }
17977       if (DestReg) {
17978         Res.first = DestReg;
17979         Res.second = &X86::GR64RegClass;
17980       }
17981     }
17982   } else if (Res.second == &X86::FR32RegClass ||
17983              Res.second == &X86::FR64RegClass ||
17984              Res.second == &X86::VR128RegClass) {
17985     // Handle references to XMM physical registers that got mapped into the
17986     // wrong class.  This can happen with constraints like {xmm0} where the
17987     // target independent register mapper will just pick the first match it can
17988     // find, ignoring the required type.
17989
17990     if (VT == MVT::f32 || VT == MVT::i32)
17991       Res.second = &X86::FR32RegClass;
17992     else if (VT == MVT::f64 || VT == MVT::i64)
17993       Res.second = &X86::FR64RegClass;
17994     else if (X86::VR128RegClass.hasType(VT))
17995       Res.second = &X86::VR128RegClass;
17996     else if (X86::VR256RegClass.hasType(VT))
17997       Res.second = &X86::VR256RegClass;
17998   }
17999
18000   return Res;
18001 }
18002
18003 //===----------------------------------------------------------------------===//
18004 //
18005 // X86 cost model.
18006 //
18007 //===----------------------------------------------------------------------===//
18008
18009 struct X86CostTblEntry {
18010   int ISD;
18011   MVT Type;
18012   unsigned Cost;
18013 };
18014
18015 static int
18016 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
18017   for (unsigned int i = 0; i < len; ++i)
18018     if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
18019       return i;
18020
18021   // Could not find an entry.
18022   return -1;
18023 }
18024
18025 struct X86TypeConversionCostTblEntry {
18026   int ISD;
18027   MVT Dst;
18028   MVT Src;
18029   unsigned Cost;
18030 };
18031
18032 static int
18033 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
18034                    int ISD, MVT Dst, MVT Src) {
18035   for (unsigned int i = 0; i < len; ++i)
18036     if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
18037       return i;
18038
18039   // Could not find an entry.
18040   return -1;
18041 }
18042
18043 ScalarTargetTransformInfo::PopcntHwSupport
18044 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
18045   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
18046   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18047
18048   // TODO: Currently the __builtin_popcount() implementation using SSE3
18049   //   instructions is inefficient. Once the problem is fixed, we should
18050   //   call ST.hasSSE3() instead of ST.hasSSE4().
18051   return ST.hasSSE41() ? Fast : None;
18052 }
18053
18054 unsigned
18055 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
18056                                                      Type *Ty) const {
18057   // Legalize the type.
18058   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
18059
18060   int ISD = InstructionOpcodeToISD(Opcode);
18061   assert(ISD && "Invalid opcode");
18062
18063   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18064
18065   static const X86CostTblEntry AVX1CostTable[] = {
18066     // We don't have to scalarize unsupported ops. We can issue two half-sized
18067     // operations and we only need to extract the upper YMM half.
18068     // Two ops + 1 extract + 1 insert = 4.
18069     { ISD::MUL,     MVT::v8i32,    4 },
18070     { ISD::SUB,     MVT::v8i32,    4 },
18071     { ISD::ADD,     MVT::v8i32,    4 },
18072     { ISD::MUL,     MVT::v4i64,    4 },
18073     { ISD::SUB,     MVT::v4i64,    4 },
18074     { ISD::ADD,     MVT::v4i64,    4 },
18075     };
18076
18077   // Look for AVX1 lowering tricks.
18078   if (ST.hasAVX()) {
18079     int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
18080                           LT.second);
18081     if (Idx != -1)
18082       return LT.first * AVX1CostTable[Idx].Cost;
18083   }
18084   // Fallback to the default implementation.
18085   return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
18086 }
18087
18088 unsigned
18089 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
18090                                               unsigned Alignment,
18091                                               unsigned AddressSpace) const {
18092   // Legalize the type.
18093   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
18094   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
18095          "Invalid Opcode");
18096
18097   const X86Subtarget &ST =
18098   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18099
18100   // Each load/store unit costs 1.
18101   unsigned Cost = LT.first * 1;
18102
18103   // On Sandybridge 256bit load/stores are double pumped
18104   // (but not on Haswell).
18105   if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
18106     Cost*=2;
18107
18108   return Cost;
18109 }
18110
18111 unsigned
18112 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
18113                                                  unsigned Index) const {
18114   assert(Val->isVectorTy() && "This must be a vector type");
18115
18116   if (Index != -1U) {
18117     // Legalize the type.
18118     std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
18119
18120     // This type is legalized to a scalar type.
18121     if (!LT.second.isVector())
18122       return 0;
18123
18124     // The type may be split. Normalize the index to the new type.
18125     unsigned Width = LT.second.getVectorNumElements();
18126     Index = Index % Width;
18127
18128     // Floating point scalars are already located in index #0.
18129     if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18130       return 0;
18131   }
18132
18133   return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18134 }
18135
18136 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18137                                                           Type *ValTy,
18138                                                           Type *CondTy) const {
18139   // Legalize the type.
18140   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18141
18142   MVT MTy = LT.second;
18143
18144   int ISD = InstructionOpcodeToISD(Opcode);
18145   assert(ISD && "Invalid opcode");
18146
18147   const X86Subtarget &ST =
18148   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18149
18150   static const X86CostTblEntry SSE42CostTbl[] = {
18151     { ISD::SETCC,   MVT::v2f64,   1 },
18152     { ISD::SETCC,   MVT::v4f32,   1 },
18153     { ISD::SETCC,   MVT::v2i64,   1 },
18154     { ISD::SETCC,   MVT::v4i32,   1 },
18155     { ISD::SETCC,   MVT::v8i16,   1 },
18156     { ISD::SETCC,   MVT::v16i8,   1 },
18157   };
18158
18159   static const X86CostTblEntry AVX1CostTbl[] = {
18160     { ISD::SETCC,   MVT::v4f64,   1 },
18161     { ISD::SETCC,   MVT::v8f32,   1 },
18162     // AVX1 does not support 8-wide integer compare.
18163     { ISD::SETCC,   MVT::v4i64,   4 },
18164     { ISD::SETCC,   MVT::v8i32,   4 },
18165     { ISD::SETCC,   MVT::v16i16,  4 },
18166     { ISD::SETCC,   MVT::v32i8,   4 },
18167   };
18168
18169   static const X86CostTblEntry AVX2CostTbl[] = {
18170     { ISD::SETCC,   MVT::v4i64,   1 },
18171     { ISD::SETCC,   MVT::v8i32,   1 },
18172     { ISD::SETCC,   MVT::v16i16,  1 },
18173     { ISD::SETCC,   MVT::v32i8,   1 },
18174   };
18175
18176   if (ST.hasAVX2()) {
18177     int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18178     if (Idx != -1)
18179       return LT.first * AVX2CostTbl[Idx].Cost;
18180   }
18181
18182   if (ST.hasAVX()) {
18183     int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18184     if (Idx != -1)
18185       return LT.first * AVX1CostTbl[Idx].Cost;
18186   }
18187
18188   if (ST.hasSSE42()) {
18189     int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18190     if (Idx != -1)
18191       return LT.first * SSE42CostTbl[Idx].Cost;
18192   }
18193
18194   return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18195 }
18196
18197 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18198                                                         Type *Dst,
18199                                                         Type *Src) const {
18200   int ISD = InstructionOpcodeToISD(Opcode);
18201   assert(ISD && "Invalid opcode");
18202
18203   EVT SrcTy = TLI->getValueType(Src);
18204   EVT DstTy = TLI->getValueType(Dst);
18205
18206   if (!SrcTy.isSimple() || !DstTy.isSimple())
18207     return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18208
18209   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18210
18211   static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18212     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18213     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18214     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18215     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18216     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 1 },
18217     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32, 1 },
18218     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18219     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18220     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18221     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18222     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 1 },
18223     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
18224     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1,  6 },
18225     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1,  9 },
18226     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64, 3 },
18227   };
18228
18229   if (ST.hasAVX()) {
18230     int Idx = FindInConvertTable(AVXConversionTbl,
18231                                  array_lengthof(AVXConversionTbl),
18232                                  ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18233     if (Idx != -1)
18234       return AVXConversionTbl[Idx].Cost;
18235   }
18236
18237   return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18238 }
18239
18240
18241 unsigned X86VectorTargetTransformInfo::getShuffleCost(ShuffleKind Kind, Type *Tp,
18242                                                       int Index) const {
18243   // We only estimate the cost of reverse shuffles.
18244   if (Kind != Reverse)
18245     return VectorTargetTransformImpl::getShuffleCost(Kind, Tp, Index);
18246
18247   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Tp);
18248   unsigned Cost = 1;
18249   if (LT.second.getSizeInBits() > 128)
18250     Cost = 3; // Extract + insert + copy.
18251
18252   // Multiple by the number of parts.
18253   return Cost * LT.first;
18254 }
18255