dc942461444403ec251e9621d247a1626417da54
[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 "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.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 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   int Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   EVT VT = Vec.getValueType();
103   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
104
105   EVT ElVT = VT.getVectorElementType();
106   EVT ResultVT = Result.getValueType();
107
108   // Insert the relevant 128 bits.
109   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
110
111   // This is the index of the first element of the 128-bit chunk
112   // we want.
113   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
114                                * ElemsPerChunk);
115
116   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
117   Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
118                        VecIdx);
119   return Result;
120 }
121
122 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
123 /// instructions. This is used because creating CONCAT_VECTOR nodes of
124 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
125 /// large BUILD_VECTORS.
126 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
127                                    unsigned NumElems, SelectionDAG &DAG,
128                                    DebugLoc dl) {
129   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
130   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
131 }
132
133 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
134   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
135   bool is64Bit = Subtarget->is64Bit();
136
137   if (Subtarget->isTargetEnvMacho()) {
138     if (is64Bit)
139       return new X8664_MachoTargetObjectFile();
140     return new TargetLoweringObjectFileMachO();
141   }
142
143   if (Subtarget->isTargetELF())
144     return new TargetLoweringObjectFileELF();
145   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
146     return new TargetLoweringObjectFileCOFF();
147   llvm_unreachable("unknown subtarget type");
148 }
149
150 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
151   : TargetLowering(TM, createTLOF(TM)) {
152   Subtarget = &TM.getSubtarget<X86Subtarget>();
153   X86ScalarSSEf64 = Subtarget->hasSSE2();
154   X86ScalarSSEf32 = Subtarget->hasSSE1();
155   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
156
157   RegInfo = TM.getRegisterInfo();
158   TD = getTargetData();
159
160   // Set up the TargetLowering object.
161   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
162
163   // X86 is weird, it always uses i8 for shift amounts and setcc results.
164   setBooleanContents(ZeroOrOneBooleanContent);
165   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
166   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167
168   // For 64-bit since we have so many registers use the ILP scheduler, for
169   // 32-bit code use the register pressure specific scheduling.
170   // For 32 bit Atom, use Hybrid (register pressure + latency) scheduling.
171   if (Subtarget->is64Bit())
172     setSchedulingPreference(Sched::ILP);
173   else if (Subtarget->isAtom()) 
174     setSchedulingPreference(Sched::Hybrid);
175   else
176     setSchedulingPreference(Sched::RegPressure);
177   setStackPointerRegisterToSaveRestore(X86StackPtr);
178
179   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
180     // Setup Windows compiler runtime calls.
181     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
182     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
183     setLibcallName(RTLIB::SREM_I64, "_allrem");
184     setLibcallName(RTLIB::UREM_I64, "_aullrem");
185     setLibcallName(RTLIB::MUL_I64, "_allmul");
186     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
187     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
188     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
189     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
190     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
191
192     // The _ftol2 runtime function has an unusual calling conv, which
193     // is modeled by a special pseudo-instruction.
194     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
195     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
196     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
197     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
198   }
199
200   if (Subtarget->isTargetDarwin()) {
201     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
202     setUseUnderscoreSetJmp(false);
203     setUseUnderscoreLongJmp(false);
204   } else if (Subtarget->isTargetMingw()) {
205     // MS runtime is weird: it exports _setjmp, but longjmp!
206     setUseUnderscoreSetJmp(true);
207     setUseUnderscoreLongJmp(false);
208   } else {
209     setUseUnderscoreSetJmp(true);
210     setUseUnderscoreLongJmp(true);
211   }
212
213   // Set up the register classes.
214   addRegisterClass(MVT::i8, &X86::GR8RegClass);
215   addRegisterClass(MVT::i16, &X86::GR16RegClass);
216   addRegisterClass(MVT::i32, &X86::GR32RegClass);
217   if (Subtarget->is64Bit())
218     addRegisterClass(MVT::i64, &X86::GR64RegClass);
219
220   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
221
222   // We don't accept any truncstore of integer registers.
223   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
224   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
225   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
226   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
227   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
228   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
229
230   // SETOEQ and SETUNE require checking two conditions.
231   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
232   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
233   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
234   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
235   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
236   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
237
238   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
239   // operation.
240   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
241   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
242   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
243
244   if (Subtarget->is64Bit()) {
245     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
246     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
247   } else if (!TM.Options.UseSoftFloat) {
248     // We have an algorithm for SSE2->double, and we turn this into a
249     // 64-bit FILD followed by conditional FADD for other targets.
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
251     // We have an algorithm for SSE2, and we turn this into a 64-bit
252     // FILD for other targets.
253     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
254   }
255
256   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
257   // this operation.
258   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
259   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
260
261   if (!TM.Options.UseSoftFloat) {
262     // SSE has no i16 to fp conversion, only i32
263     if (X86ScalarSSEf32) {
264       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
265       // f32 and f64 cases are Legal, f80 case is not
266       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
267     } else {
268       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
270     }
271   } else {
272     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
273     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
274   }
275
276   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
277   // are Legal, f80 is custom lowered.
278   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
279   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
280
281   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
282   // this operation.
283   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
284   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
285
286   if (X86ScalarSSEf32) {
287     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
288     // f32 and f64 cases are Legal, f80 case is not
289     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
290   } else {
291     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
293   }
294
295   // Handle FP_TO_UINT by promoting the destination to a larger signed
296   // conversion.
297   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
298   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
299   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
300
301   if (Subtarget->is64Bit()) {
302     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
303     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
304   } else if (!TM.Options.UseSoftFloat) {
305     // Since AVX is a superset of SSE3, only check for SSE here.
306     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
307       // Expand FP_TO_UINT into a select.
308       // FIXME: We would like to use a Custom expander here eventually to do
309       // the optimal thing for SSE vs. the default expansion in the legalizer.
310       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
311     else
312       // With SSE3 we can use fisttpll to convert to a signed i64; without
313       // SSE, we're stuck with a fistpll.
314       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
315   }
316
317   if (isTargetFTOL()) {
318     // Use the _ftol2 runtime function, which has a pseudo-instruction
319     // to handle its weird calling convention.
320     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
321   }
322
323   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
324   if (!X86ScalarSSEf64) {
325     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
326     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
327     if (Subtarget->is64Bit()) {
328       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
329       // Without SSE, i64->f64 goes through memory.
330       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
331     }
332   }
333
334   // Scalar integer divide and remainder are lowered to use operations that
335   // produce two results, to match the available instructions. This exposes
336   // the two-result form to trivial CSE, which is able to combine x/y and x%y
337   // into a single instruction.
338   //
339   // Scalar integer multiply-high is also lowered to use two-result
340   // operations, to match the available instructions. However, plain multiply
341   // (low) operations are left as Legal, as there are single-result
342   // instructions for this in x86. Using the two-result multiply instructions
343   // when both high and low results are needed must be arranged by dagcombine.
344   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
345     MVT VT = IntVTs[i];
346     setOperationAction(ISD::MULHS, VT, Expand);
347     setOperationAction(ISD::MULHU, VT, Expand);
348     setOperationAction(ISD::SDIV, VT, Expand);
349     setOperationAction(ISD::UDIV, VT, Expand);
350     setOperationAction(ISD::SREM, VT, Expand);
351     setOperationAction(ISD::UREM, VT, Expand);
352
353     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
354     setOperationAction(ISD::ADDC, VT, Custom);
355     setOperationAction(ISD::ADDE, VT, Custom);
356     setOperationAction(ISD::SUBC, VT, Custom);
357     setOperationAction(ISD::SUBE, VT, Custom);
358   }
359
360   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
361   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
362   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
363   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
364   if (Subtarget->is64Bit())
365     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
366   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
367   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
368   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
369   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
370   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
371   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
372   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
373   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
374
375   // Promote the i8 variants and force them on up to i32 which has a shorter
376   // encoding.
377   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
378   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
379   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
380   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
383     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
384     if (Subtarget->is64Bit())
385       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
386   } else {
387     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
388     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
391   }
392
393   if (Subtarget->hasLZCNT()) {
394     // When promoting the i8 variants, force them to i32 for a shorter
395     // encoding.
396     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
397     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
398     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
399     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
400     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
401     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
402     if (Subtarget->is64Bit())
403       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
404   } else {
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
406     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
407     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
411     if (Subtarget->is64Bit()) {
412       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
414     }
415   }
416
417   if (Subtarget->hasPOPCNT()) {
418     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
419   } else {
420     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
421     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
422     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
423     if (Subtarget->is64Bit())
424       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
425   }
426
427   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
428   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
429
430   // These should be promoted to a larger select which is supported.
431   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
432   // X86 wants to expand cmov itself.
433   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
434   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
435   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
439   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
440   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
447     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
448   }
449   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
450
451   // Darwin ABI issue.
452   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
453   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
454   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
455   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
456   if (Subtarget->is64Bit())
457     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
458   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
459   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
460   if (Subtarget->is64Bit()) {
461     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
462     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
463     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
464     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
465     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
466   }
467   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
468   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
469   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
470   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
471   if (Subtarget->is64Bit()) {
472     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
473     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
474     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
475   }
476
477   if (Subtarget->hasSSE1())
478     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
479
480   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
481   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
482
483   // On X86 and X86-64, atomic operations are lowered to locked instructions.
484   // Locked instructions, in turn, have implicit fence semantics (all memory
485   // operations are flushed before issuing the locked instruction, and they
486   // are not buffered), so we can fold away the common pattern of
487   // fence-atomic-fence.
488   setShouldFoldAtomicFences(true);
489
490   // Expand certain atomics
491   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
492     MVT VT = IntVTs[i];
493     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
494     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
495     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
496   }
497
498   if (!Subtarget->is64Bit()) {
499     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
507   }
508
509   if (Subtarget->hasCmpxchg16b()) {
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
511   }
512
513   // FIXME - use subtarget debug flags
514   if (!Subtarget->isTargetDarwin() &&
515       !Subtarget->isTargetELF() &&
516       !Subtarget->isTargetCygMing()) {
517     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
518   }
519
520   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
521   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
524   if (Subtarget->is64Bit()) {
525     setExceptionPointerRegister(X86::RAX);
526     setExceptionSelectorRegister(X86::RDX);
527   } else {
528     setExceptionPointerRegister(X86::EAX);
529     setExceptionSelectorRegister(X86::EDX);
530   }
531   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
533
534   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
535   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552
553   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
554     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
555                        MVT::i64 : MVT::i32, Custom);
556   else if (TM.Options.EnableSegmentedStacks)
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
558                        MVT::i64 : MVT::i32, Custom);
559   else
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Expand);
562
563   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
564     // f32 and f64 use SSE.
565     // Set up the FP register classes.
566     addRegisterClass(MVT::f32, &X86::FR32RegClass);
567     addRegisterClass(MVT::f64, &X86::FR64RegClass);
568
569     // Use ANDPD to simulate FABS.
570     setOperationAction(ISD::FABS , MVT::f64, Custom);
571     setOperationAction(ISD::FABS , MVT::f32, Custom);
572
573     // Use XORP to simulate FNEG.
574     setOperationAction(ISD::FNEG , MVT::f64, Custom);
575     setOperationAction(ISD::FNEG , MVT::f32, Custom);
576
577     // Use ANDPD and ORPD to simulate FCOPYSIGN.
578     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
579     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
580
581     // Lower this to FGETSIGNx86 plus an AND.
582     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
583     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
584
585     // We don't support sin/cos/fmod
586     setOperationAction(ISD::FSIN , MVT::f64, Expand);
587     setOperationAction(ISD::FCOS , MVT::f64, Expand);
588     setOperationAction(ISD::FSIN , MVT::f32, Expand);
589     setOperationAction(ISD::FCOS , MVT::f32, Expand);
590
591     // Expand FP immediates into loads from the stack, except for the special
592     // cases we handle.
593     addLegalFPImmediate(APFloat(+0.0)); // xorpd
594     addLegalFPImmediate(APFloat(+0.0f)); // xorps
595   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
596     // Use SSE for f32, x87 for f64.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f32, &X86::FR32RegClass);
599     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
600
601     // Use ANDPS to simulate FABS.
602     setOperationAction(ISD::FABS , MVT::f32, Custom);
603
604     // Use XORP to simulate FNEG.
605     setOperationAction(ISD::FNEG , MVT::f32, Custom);
606
607     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
608
609     // Use ANDPS and ORPS to simulate FCOPYSIGN.
610     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
611     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
612
613     // We don't support sin/cos/fmod
614     setOperationAction(ISD::FSIN , MVT::f32, Expand);
615     setOperationAction(ISD::FCOS , MVT::f32, Expand);
616
617     // Special cases we handle for FP constants.
618     addLegalFPImmediate(APFloat(+0.0f)); // xorps
619     addLegalFPImmediate(APFloat(+0.0)); // FLD0
620     addLegalFPImmediate(APFloat(+1.0)); // FLD1
621     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623
624     if (!TM.Options.UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628   } else if (!TM.Options.UseSoftFloat) {
629     // f32 and f64 in x87.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
632     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
633
634     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
635     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
636     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
637     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
638
639     if (!TM.Options.UnsafeFPMath) {
640       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
641       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
642     }
643     addLegalFPImmediate(APFloat(+0.0)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
648     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
649     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
650     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
651   }
652
653   // We don't support FMA.
654   setOperationAction(ISD::FMA, MVT::f64, Expand);
655   setOperationAction(ISD::FMA, MVT::f32, Expand);
656
657   // Long double always uses X87.
658   if (!TM.Options.UseSoftFloat) {
659     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
660     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
661     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
662     {
663       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
664       addLegalFPImmediate(TmpFlt);  // FLD0
665       TmpFlt.changeSign();
666       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
667
668       bool ignored;
669       APFloat TmpFlt2(+1.0);
670       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
671                       &ignored);
672       addLegalFPImmediate(TmpFlt2);  // FLD1
673       TmpFlt2.changeSign();
674       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
675     }
676
677     if (!TM.Options.UnsafeFPMath) {
678       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
679       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
680     }
681
682     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
683     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
684     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
685     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
686     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
687     setOperationAction(ISD::FMA, MVT::f80, Expand);
688   }
689
690   // Always use a library call for pow.
691   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
692   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
693   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
694
695   setOperationAction(ISD::FLOG, MVT::f80, Expand);
696   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
697   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
698   setOperationAction(ISD::FEXP, MVT::f80, Expand);
699   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
700
701   // First set operation action for all vector types to either promote
702   // (for widening) or expand (for scalarization). Then we will selectively
703   // turn on ones that can be effectively codegen'd.
704   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
705        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
706     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
721     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
724     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
758     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
763     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
764          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
765       setTruncStoreAction((MVT::SimpleValueType)VT,
766                           (MVT::SimpleValueType)InnerVT, Expand);
767     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
768     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
769     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
770   }
771
772   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
773   // with -msoft-float, disable use of MMX as well.
774   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
775     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
776     // No operations on x86mmx supported, everything uses intrinsics.
777   }
778
779   // MMX-sized vectors (other than x86mmx) are expected to be expanded
780   // into smaller operations.
781   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
782   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
783   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
784   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
785   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
786   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
787   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
788   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
789   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
790   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
791   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
792   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
793   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
794   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
795   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
796   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
797   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
798   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
799   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
800   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
801   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
802   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
803   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
804   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
805   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
806   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
807   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
808   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
809   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
810
811   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
812     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
813
814     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
815     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
816     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
817     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
818     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
819     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
820     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
821     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
822     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
823     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
826   }
827
828   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
829     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
830
831     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
832     // registers cannot be used even for integer operations.
833     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
834     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
835     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
836     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
837
838     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
839     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
840     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
841     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
842     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
843     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
844     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
845     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
846     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
848     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
849     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
850     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
851     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
852     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
853     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
854
855     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
857     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
858     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
859
860     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
861     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
863     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
865
866     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
867     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
868     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
869     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
870     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
871
872     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
874       EVT VT = (MVT::SimpleValueType)i;
875       // Do not attempt to custom lower non-power-of-2 vectors
876       if (!isPowerOf2_32(VT.getVectorNumElements()))
877         continue;
878       // Do not attempt to custom lower non-128-bit vectors
879       if (!VT.is128BitVector())
880         continue;
881       setOperationAction(ISD::BUILD_VECTOR,
882                          VT.getSimpleVT().SimpleTy, Custom);
883       setOperationAction(ISD::VECTOR_SHUFFLE,
884                          VT.getSimpleVT().SimpleTy, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
886                          VT.getSimpleVT().SimpleTy, Custom);
887     }
888
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
893     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
899     }
900
901     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
902     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
903       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
904       EVT VT = SVT;
905
906       // Do not attempt to promote non-128-bit vectors
907       if (!VT.is128BitVector())
908         continue;
909
910       setOperationAction(ISD::AND,    SVT, Promote);
911       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
912       setOperationAction(ISD::OR,     SVT, Promote);
913       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
914       setOperationAction(ISD::XOR,    SVT, Promote);
915       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
916       setOperationAction(ISD::LOAD,   SVT, Promote);
917       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
918       setOperationAction(ISD::SELECT, SVT, Promote);
919       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
920     }
921
922     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
923
924     // Custom lower v2i64 and v2f64 selects.
925     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
926     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
927     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
929
930     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
931     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
932   }
933
934   if (Subtarget->hasSSE41()) {
935     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
936     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
937     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
938     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
939     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
940     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
945
946     // FIXME: Do we need to handle scalar-to-vector here?
947     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
948
949     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
950     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
951     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
954
955     // i8 and i16 vectors are custom , because the source register and source
956     // source memory operand types are not the same width.  f32 vectors are
957     // custom since the immediate controlling the insert encodes additional
958     // information.
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
960     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
963
964     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
965     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
968
969     // FIXME: these should be Legal but thats only for the case where
970     // the index is constant.  For now custom expand to deal with that.
971     if (Subtarget->is64Bit()) {
972       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
973       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
974     }
975   }
976
977   if (Subtarget->hasSSE2()) {
978     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
979     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
980
981     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
982     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
983
984     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
986
987     if (Subtarget->hasAVX2()) {
988       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
989       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
990
991       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
992       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
993
994       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
995     } else {
996       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
997       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
998
999       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1000       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1001
1002       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE42())
1007     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1008
1009   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1011     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1013     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1015     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1016
1017     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1020
1021     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1027
1028     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1033     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1034
1035     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1036     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1037     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1038
1039     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1040     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1041     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1042     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1043     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1045
1046     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1047     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1048
1049     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1050     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1051
1052     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1053     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1054
1055     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1056     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1057     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1058     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1059
1060     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1061     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1062     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1065     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1066     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1067     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1068
1069     if (Subtarget->hasAVX2()) {
1070       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1071       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1073       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1074
1075       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1081       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1083       // Don't lower v32i8 because there is no 128-bit byte mul
1084
1085       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1094     } else {
1095       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1098       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1099
1100       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1108       // Don't lower v32i8 because there is no 128-bit byte mul
1109
1110       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1112
1113       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1114       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1115
1116       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1117     }
1118
1119     // Custom lower several nodes for 256-bit types.
1120     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1121                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1122       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1123       EVT VT = SVT;
1124
1125       // Extract subvector is special because the value type
1126       // (result) is 128-bit but the source is 256-bit wide.
1127       if (VT.is128BitVector())
1128         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1129
1130       // Do not attempt to custom lower other non-256-bit vectors
1131       if (!VT.is256BitVector())
1132         continue;
1133
1134       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1135       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1138       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1139       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1140     }
1141
1142     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1143     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1144       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1145       EVT VT = SVT;
1146
1147       // Do not attempt to promote non-256-bit vectors
1148       if (!VT.is256BitVector())
1149         continue;
1150
1151       setOperationAction(ISD::AND,    SVT, Promote);
1152       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1153       setOperationAction(ISD::OR,     SVT, Promote);
1154       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1155       setOperationAction(ISD::XOR,    SVT, Promote);
1156       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1157       setOperationAction(ISD::LOAD,   SVT, Promote);
1158       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1159       setOperationAction(ISD::SELECT, SVT, Promote);
1160       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1161     }
1162   }
1163
1164   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1165   // of this type with custom code.
1166   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1167          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1168     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1169                        Custom);
1170   }
1171
1172   // We want to custom lower some of our intrinsics.
1173   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1174
1175
1176   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1177   // handle type legalization for these operations here.
1178   //
1179   // FIXME: We really should do custom legalization for addition and
1180   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1181   // than generic legalization for 64-bit multiplication-with-overflow, though.
1182   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1183     // Add/Sub/Mul with overflow operations are custom lowered.
1184     MVT VT = IntVTs[i];
1185     setOperationAction(ISD::SADDO, VT, Custom);
1186     setOperationAction(ISD::UADDO, VT, Custom);
1187     setOperationAction(ISD::SSUBO, VT, Custom);
1188     setOperationAction(ISD::USUBO, VT, Custom);
1189     setOperationAction(ISD::SMULO, VT, Custom);
1190     setOperationAction(ISD::UMULO, VT, Custom);
1191   }
1192
1193   // There are no 8-bit 3-address imul/mul instructions
1194   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1195   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1196
1197   if (!Subtarget->is64Bit()) {
1198     // These libcalls are not available in 32-bit.
1199     setLibcallName(RTLIB::SHL_I128, 0);
1200     setLibcallName(RTLIB::SRL_I128, 0);
1201     setLibcallName(RTLIB::SRA_I128, 0);
1202   }
1203
1204   // We have target-specific dag combine patterns for the following nodes:
1205   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1206   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1207   setTargetDAGCombine(ISD::VSELECT);
1208   setTargetDAGCombine(ISD::SELECT);
1209   setTargetDAGCombine(ISD::SHL);
1210   setTargetDAGCombine(ISD::SRA);
1211   setTargetDAGCombine(ISD::SRL);
1212   setTargetDAGCombine(ISD::OR);
1213   setTargetDAGCombine(ISD::AND);
1214   setTargetDAGCombine(ISD::ADD);
1215   setTargetDAGCombine(ISD::FADD);
1216   setTargetDAGCombine(ISD::FSUB);
1217   setTargetDAGCombine(ISD::SUB);
1218   setTargetDAGCombine(ISD::LOAD);
1219   setTargetDAGCombine(ISD::STORE);
1220   setTargetDAGCombine(ISD::ZERO_EXTEND);
1221   setTargetDAGCombine(ISD::ANY_EXTEND);
1222   setTargetDAGCombine(ISD::SIGN_EXTEND);
1223   setTargetDAGCombine(ISD::TRUNCATE);
1224   setTargetDAGCombine(ISD::SINT_TO_FP);
1225   if (Subtarget->is64Bit())
1226     setTargetDAGCombine(ISD::MUL);
1227   if (Subtarget->hasBMI())
1228     setTargetDAGCombine(ISD::XOR);
1229
1230   computeRegisterProperties();
1231
1232   // On Darwin, -Os means optimize for size without hurting performance,
1233   // do not reduce the limit.
1234   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1235   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1236   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1237   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1239   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1240   setPrefLoopAlignment(4); // 2^4 bytes.
1241   benefitFromCodePlacementOpt = true;
1242
1243   setPrefFunctionAlignment(4); // 2^4 bytes.
1244 }
1245
1246
1247 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1248   if (!VT.isVector()) return MVT::i8;
1249   return VT.changeVectorElementTypeToInteger();
1250 }
1251
1252
1253 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1254 /// the desired ByVal argument alignment.
1255 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1256   if (MaxAlign == 16)
1257     return;
1258   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1259     if (VTy->getBitWidth() == 128)
1260       MaxAlign = 16;
1261   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1262     unsigned EltAlign = 0;
1263     getMaxByValAlign(ATy->getElementType(), EltAlign);
1264     if (EltAlign > MaxAlign)
1265       MaxAlign = EltAlign;
1266   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1267     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1268       unsigned EltAlign = 0;
1269       getMaxByValAlign(STy->getElementType(i), EltAlign);
1270       if (EltAlign > MaxAlign)
1271         MaxAlign = EltAlign;
1272       if (MaxAlign == 16)
1273         break;
1274     }
1275   }
1276 }
1277
1278 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1279 /// function arguments in the caller parameter area. For X86, aggregates
1280 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1281 /// are at 4-byte boundaries.
1282 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1283   if (Subtarget->is64Bit()) {
1284     // Max of 8 and alignment of type.
1285     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1286     if (TyAlign > 8)
1287       return TyAlign;
1288     return 8;
1289   }
1290
1291   unsigned Align = 4;
1292   if (Subtarget->hasSSE1())
1293     getMaxByValAlign(Ty, Align);
1294   return Align;
1295 }
1296
1297 /// getOptimalMemOpType - Returns the target specific optimal type for load
1298 /// and store operations as a result of memset, memcpy, and memmove
1299 /// lowering. If DstAlign is zero that means it's safe to destination
1300 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1301 /// means there isn't a need to check it against alignment requirement,
1302 /// probably because the source does not need to be loaded. If
1303 /// 'IsZeroVal' is true, that means it's safe to return a
1304 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1305 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1306 /// constant so it does not need to be loaded.
1307 /// It returns EVT::Other if the type should be determined using generic
1308 /// target-independent logic.
1309 EVT
1310 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1311                                        unsigned DstAlign, unsigned SrcAlign,
1312                                        bool IsZeroVal,
1313                                        bool MemcpyStrSrc,
1314                                        MachineFunction &MF) const {
1315   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1316   // linux.  This is because the stack realignment code can't handle certain
1317   // cases like PR2962.  This should be removed when PR2962 is fixed.
1318   const Function *F = MF.getFunction();
1319   if (IsZeroVal &&
1320       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1321     if (Size >= 16 &&
1322         (Subtarget->isUnalignedMemAccessFast() ||
1323          ((DstAlign == 0 || DstAlign >= 16) &&
1324           (SrcAlign == 0 || SrcAlign >= 16))) &&
1325         Subtarget->getStackAlignment() >= 16) {
1326       if (Subtarget->getStackAlignment() >= 32) {
1327         if (Subtarget->hasAVX2())
1328           return MVT::v8i32;
1329         if (Subtarget->hasAVX())
1330           return MVT::v8f32;
1331       }
1332       if (Subtarget->hasSSE2())
1333         return MVT::v4i32;
1334       if (Subtarget->hasSSE1())
1335         return MVT::v4f32;
1336     } else if (!MemcpyStrSrc && Size >= 8 &&
1337                !Subtarget->is64Bit() &&
1338                Subtarget->getStackAlignment() >= 8 &&
1339                Subtarget->hasSSE2()) {
1340       // Do not use f64 to lower memcpy if source is string constant. It's
1341       // better to use i32 to avoid the loads.
1342       return MVT::f64;
1343     }
1344   }
1345   if (Subtarget->is64Bit() && Size >= 8)
1346     return MVT::i64;
1347   return MVT::i32;
1348 }
1349
1350 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1351 /// current function.  The returned value is a member of the
1352 /// MachineJumpTableInfo::JTEntryKind enum.
1353 unsigned X86TargetLowering::getJumpTableEncoding() const {
1354   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1355   // symbol.
1356   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1357       Subtarget->isPICStyleGOT())
1358     return MachineJumpTableInfo::EK_Custom32;
1359
1360   // Otherwise, use the normal jump table encoding heuristics.
1361   return TargetLowering::getJumpTableEncoding();
1362 }
1363
1364 const MCExpr *
1365 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1366                                              const MachineBasicBlock *MBB,
1367                                              unsigned uid,MCContext &Ctx) const{
1368   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1369          Subtarget->isPICStyleGOT());
1370   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1371   // entries.
1372   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1373                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1374 }
1375
1376 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1377 /// jumptable.
1378 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1379                                                     SelectionDAG &DAG) const {
1380   if (!Subtarget->is64Bit())
1381     // This doesn't have DebugLoc associated with it, but is not really the
1382     // same as a Register.
1383     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1384   return Table;
1385 }
1386
1387 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1388 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1389 /// MCExpr.
1390 const MCExpr *X86TargetLowering::
1391 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1392                              MCContext &Ctx) const {
1393   // X86-64 uses RIP relative addressing based on the jump table label.
1394   if (Subtarget->isPICStyleRIPRel())
1395     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1396
1397   // Otherwise, the reference is relative to the PIC base.
1398   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1399 }
1400
1401 // FIXME: Why this routine is here? Move to RegInfo!
1402 std::pair<const TargetRegisterClass*, uint8_t>
1403 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1404   const TargetRegisterClass *RRC = 0;
1405   uint8_t Cost = 1;
1406   switch (VT.getSimpleVT().SimpleTy) {
1407   default:
1408     return TargetLowering::findRepresentativeClass(VT);
1409   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1410     RRC = Subtarget->is64Bit() ?
1411       (const TargetRegisterClass*)&X86::GR64RegClass :
1412       (const TargetRegisterClass*)&X86::GR32RegClass;
1413     break;
1414   case MVT::x86mmx:
1415     RRC = &X86::VR64RegClass;
1416     break;
1417   case MVT::f32: case MVT::f64:
1418   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1419   case MVT::v4f32: case MVT::v2f64:
1420   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1421   case MVT::v4f64:
1422     RRC = &X86::VR128RegClass;
1423     break;
1424   }
1425   return std::make_pair(RRC, Cost);
1426 }
1427
1428 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1429                                                unsigned &Offset) const {
1430   if (!Subtarget->isTargetLinux())
1431     return false;
1432
1433   if (Subtarget->is64Bit()) {
1434     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1435     Offset = 0x28;
1436     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1437       AddressSpace = 256;
1438     else
1439       AddressSpace = 257;
1440   } else {
1441     // %gs:0x14 on i386
1442     Offset = 0x14;
1443     AddressSpace = 256;
1444   }
1445   return true;
1446 }
1447
1448
1449 //===----------------------------------------------------------------------===//
1450 //               Return Value Calling Convention Implementation
1451 //===----------------------------------------------------------------------===//
1452
1453 #include "X86GenCallingConv.inc"
1454
1455 bool
1456 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1457                                   MachineFunction &MF, bool isVarArg,
1458                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1459                         LLVMContext &Context) const {
1460   SmallVector<CCValAssign, 16> RVLocs;
1461   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1462                  RVLocs, Context);
1463   return CCInfo.CheckReturn(Outs, RetCC_X86);
1464 }
1465
1466 SDValue
1467 X86TargetLowering::LowerReturn(SDValue Chain,
1468                                CallingConv::ID CallConv, bool isVarArg,
1469                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1470                                const SmallVectorImpl<SDValue> &OutVals,
1471                                DebugLoc dl, SelectionDAG &DAG) const {
1472   MachineFunction &MF = DAG.getMachineFunction();
1473   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1474
1475   SmallVector<CCValAssign, 16> RVLocs;
1476   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1477                  RVLocs, *DAG.getContext());
1478   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1479
1480   // Add the regs to the liveout set for the function.
1481   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1482   for (unsigned i = 0; i != RVLocs.size(); ++i)
1483     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1484       MRI.addLiveOut(RVLocs[i].getLocReg());
1485
1486   SDValue Flag;
1487
1488   SmallVector<SDValue, 6> RetOps;
1489   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1490   // Operand #1 = Bytes To Pop
1491   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1492                    MVT::i16));
1493
1494   // Copy the result values into the output registers.
1495   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1496     CCValAssign &VA = RVLocs[i];
1497     assert(VA.isRegLoc() && "Can only return in registers!");
1498     SDValue ValToCopy = OutVals[i];
1499     EVT ValVT = ValToCopy.getValueType();
1500
1501     // If this is x86-64, and we disabled SSE, we can't return FP values,
1502     // or SSE or MMX vectors.
1503     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1504          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1505           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1506       report_fatal_error("SSE register return with SSE disabled");
1507     }
1508     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1509     // llvm-gcc has never done it right and no one has noticed, so this
1510     // should be OK for now.
1511     if (ValVT == MVT::f64 &&
1512         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1513       report_fatal_error("SSE2 register return with SSE2 disabled");
1514
1515     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1516     // the RET instruction and handled by the FP Stackifier.
1517     if (VA.getLocReg() == X86::ST0 ||
1518         VA.getLocReg() == X86::ST1) {
1519       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1520       // change the value to the FP stack register class.
1521       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1522         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1523       RetOps.push_back(ValToCopy);
1524       // Don't emit a copytoreg.
1525       continue;
1526     }
1527
1528     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1529     // which is returned in RAX / RDX.
1530     if (Subtarget->is64Bit()) {
1531       if (ValVT == MVT::x86mmx) {
1532         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1533           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1534           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1535                                   ValToCopy);
1536           // If we don't have SSE2 available, convert to v4f32 so the generated
1537           // register is legal.
1538           if (!Subtarget->hasSSE2())
1539             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1540         }
1541       }
1542     }
1543
1544     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1545     Flag = Chain.getValue(1);
1546   }
1547
1548   // The x86-64 ABI for returning structs by value requires that we copy
1549   // the sret argument into %rax for the return. We saved the argument into
1550   // a virtual register in the entry block, so now we copy the value out
1551   // and into %rax.
1552   if (Subtarget->is64Bit() &&
1553       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1554     MachineFunction &MF = DAG.getMachineFunction();
1555     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1556     unsigned Reg = FuncInfo->getSRetReturnReg();
1557     assert(Reg &&
1558            "SRetReturnReg should have been set in LowerFormalArguments().");
1559     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1560
1561     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1562     Flag = Chain.getValue(1);
1563
1564     // RAX now acts like a return value.
1565     MRI.addLiveOut(X86::RAX);
1566   }
1567
1568   RetOps[0] = Chain;  // Update chain.
1569
1570   // Add the flag if we have it.
1571   if (Flag.getNode())
1572     RetOps.push_back(Flag);
1573
1574   return DAG.getNode(X86ISD::RET_FLAG, dl,
1575                      MVT::Other, &RetOps[0], RetOps.size());
1576 }
1577
1578 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1579   if (N->getNumValues() != 1)
1580     return false;
1581   if (!N->hasNUsesOfValue(1, 0))
1582     return false;
1583
1584   SDValue TCChain = Chain;
1585   SDNode *Copy = *N->use_begin();
1586   if (Copy->getOpcode() == ISD::CopyToReg) {
1587     // If the copy has a glue operand, we conservatively assume it isn't safe to
1588     // perform a tail call.
1589     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1590       return false;
1591     TCChain = Copy->getOperand(0);
1592   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1593     return false;
1594
1595   bool HasRet = false;
1596   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1597        UI != UE; ++UI) {
1598     if (UI->getOpcode() != X86ISD::RET_FLAG)
1599       return false;
1600     HasRet = true;
1601   }
1602
1603   if (!HasRet)
1604     return false;
1605
1606   Chain = TCChain;
1607   return true;
1608 }
1609
1610 EVT
1611 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1612                                             ISD::NodeType ExtendKind) const {
1613   MVT ReturnMVT;
1614   // TODO: Is this also valid on 32-bit?
1615   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1616     ReturnMVT = MVT::i8;
1617   else
1618     ReturnMVT = MVT::i32;
1619
1620   EVT MinVT = getRegisterType(Context, ReturnMVT);
1621   return VT.bitsLT(MinVT) ? MinVT : VT;
1622 }
1623
1624 /// LowerCallResult - Lower the result values of a call into the
1625 /// appropriate copies out of appropriate physical registers.
1626 ///
1627 SDValue
1628 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1629                                    CallingConv::ID CallConv, bool isVarArg,
1630                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1631                                    DebugLoc dl, SelectionDAG &DAG,
1632                                    SmallVectorImpl<SDValue> &InVals) const {
1633
1634   // Assign locations to each value returned by this call.
1635   SmallVector<CCValAssign, 16> RVLocs;
1636   bool Is64Bit = Subtarget->is64Bit();
1637   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1638                  getTargetMachine(), RVLocs, *DAG.getContext());
1639   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1640
1641   // Copy all of the result registers out of their specified physreg.
1642   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1643     CCValAssign &VA = RVLocs[i];
1644     EVT CopyVT = VA.getValVT();
1645
1646     // If this is x86-64, and we disabled SSE, we can't return FP values
1647     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1648         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1649       report_fatal_error("SSE register return with SSE disabled");
1650     }
1651
1652     SDValue Val;
1653
1654     // If this is a call to a function that returns an fp value on the floating
1655     // point stack, we must guarantee the the value is popped from the stack, so
1656     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1657     // if the return value is not used. We use the FpPOP_RETVAL instruction
1658     // instead.
1659     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1660       // If we prefer to use the value in xmm registers, copy it out as f80 and
1661       // use a truncate to move it from fp stack reg to xmm reg.
1662       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1663       SDValue Ops[] = { Chain, InFlag };
1664       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1665                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1666       Val = Chain.getValue(0);
1667
1668       // Round the f80 to the right size, which also moves it to the appropriate
1669       // xmm register.
1670       if (CopyVT != VA.getValVT())
1671         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1672                           // This truncation won't change the value.
1673                           DAG.getIntPtrConstant(1));
1674     } else {
1675       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1676                                  CopyVT, InFlag).getValue(1);
1677       Val = Chain.getValue(0);
1678     }
1679     InFlag = Chain.getValue(2);
1680     InVals.push_back(Val);
1681   }
1682
1683   return Chain;
1684 }
1685
1686
1687 //===----------------------------------------------------------------------===//
1688 //                C & StdCall & Fast Calling Convention implementation
1689 //===----------------------------------------------------------------------===//
1690 //  StdCall calling convention seems to be standard for many Windows' API
1691 //  routines and around. It differs from C calling convention just a little:
1692 //  callee should clean up the stack, not caller. Symbols should be also
1693 //  decorated in some fancy way :) It doesn't support any vector arguments.
1694 //  For info on fast calling convention see Fast Calling Convention (tail call)
1695 //  implementation LowerX86_32FastCCCallTo.
1696
1697 /// CallIsStructReturn - Determines whether a call uses struct return
1698 /// semantics.
1699 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1700   if (Outs.empty())
1701     return false;
1702
1703   return Outs[0].Flags.isSRet();
1704 }
1705
1706 /// ArgsAreStructReturn - Determines whether a function uses struct
1707 /// return semantics.
1708 static bool
1709 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1710   if (Ins.empty())
1711     return false;
1712
1713   return Ins[0].Flags.isSRet();
1714 }
1715
1716 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1717 /// by "Src" to address "Dst" with size and alignment information specified by
1718 /// the specific parameter attribute. The copy will be passed as a byval
1719 /// function parameter.
1720 static SDValue
1721 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1722                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1723                           DebugLoc dl) {
1724   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1725
1726   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1727                        /*isVolatile*/false, /*AlwaysInline=*/true,
1728                        MachinePointerInfo(), MachinePointerInfo());
1729 }
1730
1731 /// IsTailCallConvention - Return true if the calling convention is one that
1732 /// supports tail call optimization.
1733 static bool IsTailCallConvention(CallingConv::ID CC) {
1734   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1735 }
1736
1737 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1738   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1739     return false;
1740
1741   CallSite CS(CI);
1742   CallingConv::ID CalleeCC = CS.getCallingConv();
1743   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1744     return false;
1745
1746   return true;
1747 }
1748
1749 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1750 /// a tailcall target by changing its ABI.
1751 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1752                                    bool GuaranteedTailCallOpt) {
1753   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1754 }
1755
1756 SDValue
1757 X86TargetLowering::LowerMemArgument(SDValue Chain,
1758                                     CallingConv::ID CallConv,
1759                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1760                                     DebugLoc dl, SelectionDAG &DAG,
1761                                     const CCValAssign &VA,
1762                                     MachineFrameInfo *MFI,
1763                                     unsigned i) const {
1764   // Create the nodes corresponding to a load from this parameter slot.
1765   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1766   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1767                               getTargetMachine().Options.GuaranteedTailCallOpt);
1768   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1769   EVT ValVT;
1770
1771   // If value is passed by pointer we have address passed instead of the value
1772   // itself.
1773   if (VA.getLocInfo() == CCValAssign::Indirect)
1774     ValVT = VA.getLocVT();
1775   else
1776     ValVT = VA.getValVT();
1777
1778   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1779   // changed with more analysis.
1780   // In case of tail call optimization mark all arguments mutable. Since they
1781   // could be overwritten by lowering of arguments in case of a tail call.
1782   if (Flags.isByVal()) {
1783     unsigned Bytes = Flags.getByValSize();
1784     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1785     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1786     return DAG.getFrameIndex(FI, getPointerTy());
1787   } else {
1788     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1789                                     VA.getLocMemOffset(), isImmutable);
1790     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1791     return DAG.getLoad(ValVT, dl, Chain, FIN,
1792                        MachinePointerInfo::getFixedStack(FI),
1793                        false, false, false, 0);
1794   }
1795 }
1796
1797 SDValue
1798 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1799                                         CallingConv::ID CallConv,
1800                                         bool isVarArg,
1801                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1802                                         DebugLoc dl,
1803                                         SelectionDAG &DAG,
1804                                         SmallVectorImpl<SDValue> &InVals)
1805                                           const {
1806   MachineFunction &MF = DAG.getMachineFunction();
1807   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1808
1809   const Function* Fn = MF.getFunction();
1810   if (Fn->hasExternalLinkage() &&
1811       Subtarget->isTargetCygMing() &&
1812       Fn->getName() == "main")
1813     FuncInfo->setForceFramePointer(true);
1814
1815   MachineFrameInfo *MFI = MF.getFrameInfo();
1816   bool Is64Bit = Subtarget->is64Bit();
1817   bool IsWindows = Subtarget->isTargetWindows();
1818   bool IsWin64 = Subtarget->isTargetWin64();
1819
1820   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1821          "Var args not supported with calling convention fastcc or ghc");
1822
1823   // Assign locations to all of the incoming arguments.
1824   SmallVector<CCValAssign, 16> ArgLocs;
1825   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826                  ArgLocs, *DAG.getContext());
1827
1828   // Allocate shadow area for Win64
1829   if (IsWin64) {
1830     CCInfo.AllocateStack(32, 8);
1831   }
1832
1833   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1834
1835   unsigned LastVal = ~0U;
1836   SDValue ArgValue;
1837   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1838     CCValAssign &VA = ArgLocs[i];
1839     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1840     // places.
1841     assert(VA.getValNo() != LastVal &&
1842            "Don't support value assigned to multiple locs yet");
1843     (void)LastVal;
1844     LastVal = VA.getValNo();
1845
1846     if (VA.isRegLoc()) {
1847       EVT RegVT = VA.getLocVT();
1848       const TargetRegisterClass *RC;
1849       if (RegVT == MVT::i32)
1850         RC = &X86::GR32RegClass;
1851       else if (Is64Bit && RegVT == MVT::i64)
1852         RC = &X86::GR64RegClass;
1853       else if (RegVT == MVT::f32)
1854         RC = &X86::FR32RegClass;
1855       else if (RegVT == MVT::f64)
1856         RC = &X86::FR64RegClass;
1857       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1858         RC = &X86::VR256RegClass;
1859       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1860         RC = &X86::VR128RegClass;
1861       else if (RegVT == MVT::x86mmx)
1862         RC = &X86::VR64RegClass;
1863       else
1864         llvm_unreachable("Unknown argument type!");
1865
1866       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1867       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1868
1869       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1870       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1871       // right size.
1872       if (VA.getLocInfo() == CCValAssign::SExt)
1873         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1874                                DAG.getValueType(VA.getValVT()));
1875       else if (VA.getLocInfo() == CCValAssign::ZExt)
1876         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1877                                DAG.getValueType(VA.getValVT()));
1878       else if (VA.getLocInfo() == CCValAssign::BCvt)
1879         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1880
1881       if (VA.isExtInLoc()) {
1882         // Handle MMX values passed in XMM regs.
1883         if (RegVT.isVector()) {
1884           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1885                                  ArgValue);
1886         } else
1887           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1888       }
1889     } else {
1890       assert(VA.isMemLoc());
1891       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1892     }
1893
1894     // If value is passed via pointer - do a load.
1895     if (VA.getLocInfo() == CCValAssign::Indirect)
1896       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1897                              MachinePointerInfo(), false, false, false, 0);
1898
1899     InVals.push_back(ArgValue);
1900   }
1901
1902   // The x86-64 ABI for returning structs by value requires that we copy
1903   // the sret argument into %rax for the return. Save the argument into
1904   // a virtual register so that we can access it from the return points.
1905   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1906     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1907     unsigned Reg = FuncInfo->getSRetReturnReg();
1908     if (!Reg) {
1909       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1910       FuncInfo->setSRetReturnReg(Reg);
1911     }
1912     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1913     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1914   }
1915
1916   unsigned StackSize = CCInfo.getNextStackOffset();
1917   // Align stack specially for tail calls.
1918   if (FuncIsMadeTailCallSafe(CallConv,
1919                              MF.getTarget().Options.GuaranteedTailCallOpt))
1920     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1921
1922   // If the function takes variable number of arguments, make a frame index for
1923   // the start of the first vararg value... for expansion of llvm.va_start.
1924   if (isVarArg) {
1925     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1926                     CallConv != CallingConv::X86_ThisCall)) {
1927       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1928     }
1929     if (Is64Bit) {
1930       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1931
1932       // FIXME: We should really autogenerate these arrays
1933       static const uint16_t GPR64ArgRegsWin64[] = {
1934         X86::RCX, X86::RDX, X86::R8,  X86::R9
1935       };
1936       static const uint16_t GPR64ArgRegs64Bit[] = {
1937         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1938       };
1939       static const uint16_t XMMArgRegs64Bit[] = {
1940         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1941         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1942       };
1943       const uint16_t *GPR64ArgRegs;
1944       unsigned NumXMMRegs = 0;
1945
1946       if (IsWin64) {
1947         // The XMM registers which might contain var arg parameters are shadowed
1948         // in their paired GPR.  So we only need to save the GPR to their home
1949         // slots.
1950         TotalNumIntRegs = 4;
1951         GPR64ArgRegs = GPR64ArgRegsWin64;
1952       } else {
1953         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1954         GPR64ArgRegs = GPR64ArgRegs64Bit;
1955
1956         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1957                                                 TotalNumXMMRegs);
1958       }
1959       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1960                                                        TotalNumIntRegs);
1961
1962       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1963       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1964              "SSE register cannot be used when SSE is disabled!");
1965       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1966                NoImplicitFloatOps) &&
1967              "SSE register cannot be used when SSE is disabled!");
1968       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1969           !Subtarget->hasSSE1())
1970         // Kernel mode asks for SSE to be disabled, so don't push them
1971         // on the stack.
1972         TotalNumXMMRegs = 0;
1973
1974       if (IsWin64) {
1975         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1976         // Get to the caller-allocated home save location.  Add 8 to account
1977         // for the return address.
1978         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1979         FuncInfo->setRegSaveFrameIndex(
1980           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1981         // Fixup to set vararg frame on shadow area (4 x i64).
1982         if (NumIntRegs < 4)
1983           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1984       } else {
1985         // For X86-64, if there are vararg parameters that are passed via
1986         // registers, then we must store them to their spots on the stack so
1987         // they may be loaded by deferencing the result of va_next.
1988         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1989         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1990         FuncInfo->setRegSaveFrameIndex(
1991           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1992                                false));
1993       }
1994
1995       // Store the integer parameter registers.
1996       SmallVector<SDValue, 8> MemOps;
1997       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1998                                         getPointerTy());
1999       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2000       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2001         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2002                                   DAG.getIntPtrConstant(Offset));
2003         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2004                                      &X86::GR64RegClass);
2005         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2006         SDValue Store =
2007           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2008                        MachinePointerInfo::getFixedStack(
2009                          FuncInfo->getRegSaveFrameIndex(), Offset),
2010                        false, false, 0);
2011         MemOps.push_back(Store);
2012         Offset += 8;
2013       }
2014
2015       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2016         // Now store the XMM (fp + vector) parameter registers.
2017         SmallVector<SDValue, 11> SaveXMMOps;
2018         SaveXMMOps.push_back(Chain);
2019
2020         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2021         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2022         SaveXMMOps.push_back(ALVal);
2023
2024         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2025                                FuncInfo->getRegSaveFrameIndex()));
2026         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2027                                FuncInfo->getVarArgsFPOffset()));
2028
2029         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2030           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2031                                        &X86::VR128RegClass);
2032           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2033           SaveXMMOps.push_back(Val);
2034         }
2035         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2036                                      MVT::Other,
2037                                      &SaveXMMOps[0], SaveXMMOps.size()));
2038       }
2039
2040       if (!MemOps.empty())
2041         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2042                             &MemOps[0], MemOps.size());
2043     }
2044   }
2045
2046   // Some CCs need callee pop.
2047   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2048                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2049     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2050   } else {
2051     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2052     // If this is an sret function, the return should pop the hidden pointer.
2053     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2054         ArgsAreStructReturn(Ins))
2055       FuncInfo->setBytesToPopOnReturn(4);
2056   }
2057
2058   if (!Is64Bit) {
2059     // RegSaveFrameIndex is X86-64 only.
2060     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2061     if (CallConv == CallingConv::X86_FastCall ||
2062         CallConv == CallingConv::X86_ThisCall)
2063       // fastcc functions can't have varargs.
2064       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2065   }
2066
2067   FuncInfo->setArgumentStackSize(StackSize);
2068
2069   return Chain;
2070 }
2071
2072 SDValue
2073 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2074                                     SDValue StackPtr, SDValue Arg,
2075                                     DebugLoc dl, SelectionDAG &DAG,
2076                                     const CCValAssign &VA,
2077                                     ISD::ArgFlagsTy Flags) const {
2078   unsigned LocMemOffset = VA.getLocMemOffset();
2079   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2080   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2081   if (Flags.isByVal())
2082     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2083
2084   return DAG.getStore(Chain, dl, Arg, PtrOff,
2085                       MachinePointerInfo::getStack(LocMemOffset),
2086                       false, false, 0);
2087 }
2088
2089 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2090 /// optimization is performed and it is required.
2091 SDValue
2092 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2093                                            SDValue &OutRetAddr, SDValue Chain,
2094                                            bool IsTailCall, bool Is64Bit,
2095                                            int FPDiff, DebugLoc dl) const {
2096   // Adjust the Return address stack slot.
2097   EVT VT = getPointerTy();
2098   OutRetAddr = getReturnAddressFrameIndex(DAG);
2099
2100   // Load the "old" Return address.
2101   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2102                            false, false, false, 0);
2103   return SDValue(OutRetAddr.getNode(), 1);
2104 }
2105
2106 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2107 /// optimization is performed and it is required (FPDiff!=0).
2108 static SDValue
2109 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2110                          SDValue Chain, SDValue RetAddrFrIdx,
2111                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2112   // Store the return address to the appropriate stack slot.
2113   if (!FPDiff) return Chain;
2114   // Calculate the new stack slot for the return address.
2115   int SlotSize = Is64Bit ? 8 : 4;
2116   int NewReturnAddrFI =
2117     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2118   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2119   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2120   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2121                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2122                        false, false, 0);
2123   return Chain;
2124 }
2125
2126 SDValue
2127 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2128                              CallingConv::ID CallConv, bool isVarArg,
2129                              bool doesNotRet, bool &isTailCall,
2130                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2131                              const SmallVectorImpl<SDValue> &OutVals,
2132                              const SmallVectorImpl<ISD::InputArg> &Ins,
2133                              DebugLoc dl, SelectionDAG &DAG,
2134                              SmallVectorImpl<SDValue> &InVals) const {
2135   MachineFunction &MF = DAG.getMachineFunction();
2136   bool Is64Bit        = Subtarget->is64Bit();
2137   bool IsWin64        = Subtarget->isTargetWin64();
2138   bool IsWindows      = Subtarget->isTargetWindows();
2139   bool IsStructRet    = CallIsStructReturn(Outs);
2140   bool IsSibcall      = false;
2141
2142   if (MF.getTarget().Options.DisableTailCalls)
2143     isTailCall = false;
2144
2145   if (isTailCall) {
2146     // Check if it's really possible to do a tail call.
2147     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2148                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2149                                                    Outs, OutVals, Ins, DAG);
2150
2151     // Sibcalls are automatically detected tailcalls which do not require
2152     // ABI changes.
2153     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2154       IsSibcall = true;
2155
2156     if (isTailCall)
2157       ++NumTailCalls;
2158   }
2159
2160   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2161          "Var args not supported with calling convention fastcc or ghc");
2162
2163   // Analyze operands of the call, assigning locations to each operand.
2164   SmallVector<CCValAssign, 16> ArgLocs;
2165   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2166                  ArgLocs, *DAG.getContext());
2167
2168   // Allocate shadow area for Win64
2169   if (IsWin64) {
2170     CCInfo.AllocateStack(32, 8);
2171   }
2172
2173   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2174
2175   // Get a count of how many bytes are to be pushed on the stack.
2176   unsigned NumBytes = CCInfo.getNextStackOffset();
2177   if (IsSibcall)
2178     // This is a sibcall. The memory operands are available in caller's
2179     // own caller's stack.
2180     NumBytes = 0;
2181   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2182            IsTailCallConvention(CallConv))
2183     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2184
2185   int FPDiff = 0;
2186   if (isTailCall && !IsSibcall) {
2187     // Lower arguments at fp - stackoffset + fpdiff.
2188     unsigned NumBytesCallerPushed =
2189       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2190     FPDiff = NumBytesCallerPushed - NumBytes;
2191
2192     // Set the delta of movement of the returnaddr stackslot.
2193     // But only set if delta is greater than previous delta.
2194     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2195       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2196   }
2197
2198   if (!IsSibcall)
2199     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2200
2201   SDValue RetAddrFrIdx;
2202   // Load return address for tail calls.
2203   if (isTailCall && FPDiff)
2204     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2205                                     Is64Bit, FPDiff, dl);
2206
2207   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2208   SmallVector<SDValue, 8> MemOpChains;
2209   SDValue StackPtr;
2210
2211   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2212   // of tail call optimization arguments are handle later.
2213   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2214     CCValAssign &VA = ArgLocs[i];
2215     EVT RegVT = VA.getLocVT();
2216     SDValue Arg = OutVals[i];
2217     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2218     bool isByVal = Flags.isByVal();
2219
2220     // Promote the value if needed.
2221     switch (VA.getLocInfo()) {
2222     default: llvm_unreachable("Unknown loc info!");
2223     case CCValAssign::Full: break;
2224     case CCValAssign::SExt:
2225       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2226       break;
2227     case CCValAssign::ZExt:
2228       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2229       break;
2230     case CCValAssign::AExt:
2231       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2232         // Special case: passing MMX values in XMM registers.
2233         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2234         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2235         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2236       } else
2237         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2238       break;
2239     case CCValAssign::BCvt:
2240       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2241       break;
2242     case CCValAssign::Indirect: {
2243       // Store the argument.
2244       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2245       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2246       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2247                            MachinePointerInfo::getFixedStack(FI),
2248                            false, false, 0);
2249       Arg = SpillSlot;
2250       break;
2251     }
2252     }
2253
2254     if (VA.isRegLoc()) {
2255       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2256       if (isVarArg && IsWin64) {
2257         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2258         // shadow reg if callee is a varargs function.
2259         unsigned ShadowReg = 0;
2260         switch (VA.getLocReg()) {
2261         case X86::XMM0: ShadowReg = X86::RCX; break;
2262         case X86::XMM1: ShadowReg = X86::RDX; break;
2263         case X86::XMM2: ShadowReg = X86::R8; break;
2264         case X86::XMM3: ShadowReg = X86::R9; break;
2265         }
2266         if (ShadowReg)
2267           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2268       }
2269     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2270       assert(VA.isMemLoc());
2271       if (StackPtr.getNode() == 0)
2272         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2273       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2274                                              dl, DAG, VA, Flags));
2275     }
2276   }
2277
2278   if (!MemOpChains.empty())
2279     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2280                         &MemOpChains[0], MemOpChains.size());
2281
2282   // Build a sequence of copy-to-reg nodes chained together with token chain
2283   // and flag operands which copy the outgoing args into registers.
2284   SDValue InFlag;
2285   // Tail call byval lowering might overwrite argument registers so in case of
2286   // tail call optimization the copies to registers are lowered later.
2287   if (!isTailCall)
2288     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2289       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2290                                RegsToPass[i].second, InFlag);
2291       InFlag = Chain.getValue(1);
2292     }
2293
2294   if (Subtarget->isPICStyleGOT()) {
2295     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2296     // GOT pointer.
2297     if (!isTailCall) {
2298       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2299                                DAG.getNode(X86ISD::GlobalBaseReg,
2300                                            DebugLoc(), getPointerTy()),
2301                                InFlag);
2302       InFlag = Chain.getValue(1);
2303     } else {
2304       // If we are tail calling and generating PIC/GOT style code load the
2305       // address of the callee into ECX. The value in ecx is used as target of
2306       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2307       // for tail calls on PIC/GOT architectures. Normally we would just put the
2308       // address of GOT into ebx and then call target@PLT. But for tail calls
2309       // ebx would be restored (since ebx is callee saved) before jumping to the
2310       // target@PLT.
2311
2312       // Note: The actual moving to ECX is done further down.
2313       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2314       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2315           !G->getGlobal()->hasProtectedVisibility())
2316         Callee = LowerGlobalAddress(Callee, DAG);
2317       else if (isa<ExternalSymbolSDNode>(Callee))
2318         Callee = LowerExternalSymbol(Callee, DAG);
2319     }
2320   }
2321
2322   if (Is64Bit && isVarArg && !IsWin64) {
2323     // From AMD64 ABI document:
2324     // For calls that may call functions that use varargs or stdargs
2325     // (prototype-less calls or calls to functions containing ellipsis (...) in
2326     // the declaration) %al is used as hidden argument to specify the number
2327     // of SSE registers used. The contents of %al do not need to match exactly
2328     // the number of registers, but must be an ubound on the number of SSE
2329     // registers used and is in the range 0 - 8 inclusive.
2330
2331     // Count the number of XMM registers allocated.
2332     static const uint16_t XMMArgRegs[] = {
2333       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335     };
2336     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2337     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2338            && "SSE registers cannot be used when SSE is disabled");
2339
2340     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2341                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2342     InFlag = Chain.getValue(1);
2343   }
2344
2345
2346   // For tail calls lower the arguments to the 'real' stack slot.
2347   if (isTailCall) {
2348     // Force all the incoming stack arguments to be loaded from the stack
2349     // before any new outgoing arguments are stored to the stack, because the
2350     // outgoing stack slots may alias the incoming argument stack slots, and
2351     // the alias isn't otherwise explicit. This is slightly more conservative
2352     // than necessary, because it means that each store effectively depends
2353     // on every argument instead of just those arguments it would clobber.
2354     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2355
2356     SmallVector<SDValue, 8> MemOpChains2;
2357     SDValue FIN;
2358     int FI = 0;
2359     // Do not flag preceding copytoreg stuff together with the following stuff.
2360     InFlag = SDValue();
2361     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2362       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2363         CCValAssign &VA = ArgLocs[i];
2364         if (VA.isRegLoc())
2365           continue;
2366         assert(VA.isMemLoc());
2367         SDValue Arg = OutVals[i];
2368         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2369         // Create frame index.
2370         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2371         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2372         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2373         FIN = DAG.getFrameIndex(FI, getPointerTy());
2374
2375         if (Flags.isByVal()) {
2376           // Copy relative to framepointer.
2377           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2378           if (StackPtr.getNode() == 0)
2379             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2380                                           getPointerTy());
2381           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2382
2383           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2384                                                            ArgChain,
2385                                                            Flags, DAG, dl));
2386         } else {
2387           // Store relative to framepointer.
2388           MemOpChains2.push_back(
2389             DAG.getStore(ArgChain, dl, Arg, FIN,
2390                          MachinePointerInfo::getFixedStack(FI),
2391                          false, false, 0));
2392         }
2393       }
2394     }
2395
2396     if (!MemOpChains2.empty())
2397       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2398                           &MemOpChains2[0], MemOpChains2.size());
2399
2400     // Copy arguments to their registers.
2401     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2402       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2403                                RegsToPass[i].second, InFlag);
2404       InFlag = Chain.getValue(1);
2405     }
2406     InFlag =SDValue();
2407
2408     // Store the return address to the appropriate stack slot.
2409     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2410                                      FPDiff, dl);
2411   }
2412
2413   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2414     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2415     // In the 64-bit large code model, we have to make all calls
2416     // through a register, since the call instruction's 32-bit
2417     // pc-relative offset may not be large enough to hold the whole
2418     // address.
2419   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2420     // If the callee is a GlobalAddress node (quite common, every direct call
2421     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2422     // it.
2423
2424     // We should use extra load for direct calls to dllimported functions in
2425     // non-JIT mode.
2426     const GlobalValue *GV = G->getGlobal();
2427     if (!GV->hasDLLImportLinkage()) {
2428       unsigned char OpFlags = 0;
2429       bool ExtraLoad = false;
2430       unsigned WrapperKind = ISD::DELETED_NODE;
2431
2432       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2433       // external symbols most go through the PLT in PIC mode.  If the symbol
2434       // has hidden or protected visibility, or if it is static or local, then
2435       // we don't need to use the PLT - we can directly call it.
2436       if (Subtarget->isTargetELF() &&
2437           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2438           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2439         OpFlags = X86II::MO_PLT;
2440       } else if (Subtarget->isPICStyleStubAny() &&
2441                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2442                  (!Subtarget->getTargetTriple().isMacOSX() ||
2443                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2444         // PC-relative references to external symbols should go through $stub,
2445         // unless we're building with the leopard linker or later, which
2446         // automatically synthesizes these stubs.
2447         OpFlags = X86II::MO_DARWIN_STUB;
2448       } else if (Subtarget->isPICStyleRIPRel() &&
2449                  isa<Function>(GV) &&
2450                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2451         // If the function is marked as non-lazy, generate an indirect call
2452         // which loads from the GOT directly. This avoids runtime overhead
2453         // at the cost of eager binding (and one extra byte of encoding).
2454         OpFlags = X86II::MO_GOTPCREL;
2455         WrapperKind = X86ISD::WrapperRIP;
2456         ExtraLoad = true;
2457       }
2458
2459       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2460                                           G->getOffset(), OpFlags);
2461
2462       // Add a wrapper if needed.
2463       if (WrapperKind != ISD::DELETED_NODE)
2464         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2465       // Add extra indirection if needed.
2466       if (ExtraLoad)
2467         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2468                              MachinePointerInfo::getGOT(),
2469                              false, false, false, 0);
2470     }
2471   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2472     unsigned char OpFlags = 0;
2473
2474     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2475     // external symbols should go through the PLT.
2476     if (Subtarget->isTargetELF() &&
2477         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2478       OpFlags = X86II::MO_PLT;
2479     } else if (Subtarget->isPICStyleStubAny() &&
2480                (!Subtarget->getTargetTriple().isMacOSX() ||
2481                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2482       // PC-relative references to external symbols should go through $stub,
2483       // unless we're building with the leopard linker or later, which
2484       // automatically synthesizes these stubs.
2485       OpFlags = X86II::MO_DARWIN_STUB;
2486     }
2487
2488     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2489                                          OpFlags);
2490   }
2491
2492   // Returns a chain & a flag for retval copy to use.
2493   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2494   SmallVector<SDValue, 8> Ops;
2495
2496   if (!IsSibcall && isTailCall) {
2497     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2498                            DAG.getIntPtrConstant(0, true), InFlag);
2499     InFlag = Chain.getValue(1);
2500   }
2501
2502   Ops.push_back(Chain);
2503   Ops.push_back(Callee);
2504
2505   if (isTailCall)
2506     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2507
2508   // Add argument registers to the end of the list so that they are known live
2509   // into the call.
2510   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2511     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2512                                   RegsToPass[i].second.getValueType()));
2513
2514   // Add an implicit use GOT pointer in EBX.
2515   if (!isTailCall && Subtarget->isPICStyleGOT())
2516     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2517
2518   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2519   if (Is64Bit && isVarArg && !IsWin64)
2520     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2521
2522   // Add a register mask operand representing the call-preserved registers.
2523   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2524   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2525   assert(Mask && "Missing call preserved mask for calling convention");
2526   Ops.push_back(DAG.getRegisterMask(Mask));
2527
2528   if (InFlag.getNode())
2529     Ops.push_back(InFlag);
2530
2531   if (isTailCall) {
2532     // We used to do:
2533     //// If this is the first return lowered for this function, add the regs
2534     //// to the liveout set for the function.
2535     // This isn't right, although it's probably harmless on x86; liveouts
2536     // should be computed from returns not tail calls.  Consider a void
2537     // function making a tail call to a function returning int.
2538     return DAG.getNode(X86ISD::TC_RETURN, dl,
2539                        NodeTys, &Ops[0], Ops.size());
2540   }
2541
2542   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2543   InFlag = Chain.getValue(1);
2544
2545   // Create the CALLSEQ_END node.
2546   unsigned NumBytesForCalleeToPush;
2547   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2548                        getTargetMachine().Options.GuaranteedTailCallOpt))
2549     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2550   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2551            IsStructRet)
2552     // If this is a call to a struct-return function, the callee
2553     // pops the hidden struct pointer, so we have to push it back.
2554     // This is common for Darwin/X86, Linux & Mingw32 targets.
2555     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2556     NumBytesForCalleeToPush = 4;
2557   else
2558     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2559
2560   // Returns a flag for retval copy to use.
2561   if (!IsSibcall) {
2562     Chain = DAG.getCALLSEQ_END(Chain,
2563                                DAG.getIntPtrConstant(NumBytes, true),
2564                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2565                                                      true),
2566                                InFlag);
2567     InFlag = Chain.getValue(1);
2568   }
2569
2570   // Handle result values, copying them out of physregs into vregs that we
2571   // return.
2572   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2573                          Ins, dl, DAG, InVals);
2574 }
2575
2576
2577 //===----------------------------------------------------------------------===//
2578 //                Fast Calling Convention (tail call) implementation
2579 //===----------------------------------------------------------------------===//
2580
2581 //  Like std call, callee cleans arguments, convention except that ECX is
2582 //  reserved for storing the tail called function address. Only 2 registers are
2583 //  free for argument passing (inreg). Tail call optimization is performed
2584 //  provided:
2585 //                * tailcallopt is enabled
2586 //                * caller/callee are fastcc
2587 //  On X86_64 architecture with GOT-style position independent code only local
2588 //  (within module) calls are supported at the moment.
2589 //  To keep the stack aligned according to platform abi the function
2590 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2591 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2592 //  If a tail called function callee has more arguments than the caller the
2593 //  caller needs to make sure that there is room to move the RETADDR to. This is
2594 //  achieved by reserving an area the size of the argument delta right after the
2595 //  original REtADDR, but before the saved framepointer or the spilled registers
2596 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2597 //  stack layout:
2598 //    arg1
2599 //    arg2
2600 //    RETADDR
2601 //    [ new RETADDR
2602 //      move area ]
2603 //    (possible EBP)
2604 //    ESI
2605 //    EDI
2606 //    local1 ..
2607
2608 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2609 /// for a 16 byte align requirement.
2610 unsigned
2611 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2612                                                SelectionDAG& DAG) const {
2613   MachineFunction &MF = DAG.getMachineFunction();
2614   const TargetMachine &TM = MF.getTarget();
2615   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2616   unsigned StackAlignment = TFI.getStackAlignment();
2617   uint64_t AlignMask = StackAlignment - 1;
2618   int64_t Offset = StackSize;
2619   uint64_t SlotSize = TD->getPointerSize();
2620   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2621     // Number smaller than 12 so just add the difference.
2622     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2623   } else {
2624     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2625     Offset = ((~AlignMask) & Offset) + StackAlignment +
2626       (StackAlignment-SlotSize);
2627   }
2628   return Offset;
2629 }
2630
2631 /// MatchingStackOffset - Return true if the given stack call argument is
2632 /// already available in the same position (relatively) of the caller's
2633 /// incoming argument stack.
2634 static
2635 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2636                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2637                          const X86InstrInfo *TII) {
2638   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2639   int FI = INT_MAX;
2640   if (Arg.getOpcode() == ISD::CopyFromReg) {
2641     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2642     if (!TargetRegisterInfo::isVirtualRegister(VR))
2643       return false;
2644     MachineInstr *Def = MRI->getVRegDef(VR);
2645     if (!Def)
2646       return false;
2647     if (!Flags.isByVal()) {
2648       if (!TII->isLoadFromStackSlot(Def, FI))
2649         return false;
2650     } else {
2651       unsigned Opcode = Def->getOpcode();
2652       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2653           Def->getOperand(1).isFI()) {
2654         FI = Def->getOperand(1).getIndex();
2655         Bytes = Flags.getByValSize();
2656       } else
2657         return false;
2658     }
2659   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2660     if (Flags.isByVal())
2661       // ByVal argument is passed in as a pointer but it's now being
2662       // dereferenced. e.g.
2663       // define @foo(%struct.X* %A) {
2664       //   tail call @bar(%struct.X* byval %A)
2665       // }
2666       return false;
2667     SDValue Ptr = Ld->getBasePtr();
2668     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2669     if (!FINode)
2670       return false;
2671     FI = FINode->getIndex();
2672   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2673     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2674     FI = FINode->getIndex();
2675     Bytes = Flags.getByValSize();
2676   } else
2677     return false;
2678
2679   assert(FI != INT_MAX);
2680   if (!MFI->isFixedObjectIndex(FI))
2681     return false;
2682   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2683 }
2684
2685 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2686 /// for tail call optimization. Targets which want to do tail call
2687 /// optimization should implement this function.
2688 bool
2689 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2690                                                      CallingConv::ID CalleeCC,
2691                                                      bool isVarArg,
2692                                                      bool isCalleeStructRet,
2693                                                      bool isCallerStructRet,
2694                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2695                                     const SmallVectorImpl<SDValue> &OutVals,
2696                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2697                                                      SelectionDAG& DAG) const {
2698   if (!IsTailCallConvention(CalleeCC) &&
2699       CalleeCC != CallingConv::C)
2700     return false;
2701
2702   // If -tailcallopt is specified, make fastcc functions tail-callable.
2703   const MachineFunction &MF = DAG.getMachineFunction();
2704   const Function *CallerF = DAG.getMachineFunction().getFunction();
2705   CallingConv::ID CallerCC = CallerF->getCallingConv();
2706   bool CCMatch = CallerCC == CalleeCC;
2707
2708   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2709     if (IsTailCallConvention(CalleeCC) && CCMatch)
2710       return true;
2711     return false;
2712   }
2713
2714   // Look for obvious safe cases to perform tail call optimization that do not
2715   // require ABI changes. This is what gcc calls sibcall.
2716
2717   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2718   // emit a special epilogue.
2719   if (RegInfo->needsStackRealignment(MF))
2720     return false;
2721
2722   // Also avoid sibcall optimization if either caller or callee uses struct
2723   // return semantics.
2724   if (isCalleeStructRet || isCallerStructRet)
2725     return false;
2726
2727   // An stdcall caller is expected to clean up its arguments; the callee
2728   // isn't going to do that.
2729   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2730     return false;
2731
2732   // Do not sibcall optimize vararg calls unless all arguments are passed via
2733   // registers.
2734   if (isVarArg && !Outs.empty()) {
2735
2736     // Optimizing for varargs on Win64 is unlikely to be safe without
2737     // additional testing.
2738     if (Subtarget->isTargetWin64())
2739       return false;
2740
2741     SmallVector<CCValAssign, 16> ArgLocs;
2742     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2743                    getTargetMachine(), ArgLocs, *DAG.getContext());
2744
2745     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2746     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2747       if (!ArgLocs[i].isRegLoc())
2748         return false;
2749   }
2750
2751   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2752   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2753   // this into a sibcall.
2754   bool Unused = false;
2755   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2756     if (!Ins[i].Used) {
2757       Unused = true;
2758       break;
2759     }
2760   }
2761   if (Unused) {
2762     SmallVector<CCValAssign, 16> RVLocs;
2763     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2764                    getTargetMachine(), RVLocs, *DAG.getContext());
2765     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2766     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2767       CCValAssign &VA = RVLocs[i];
2768       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2769         return false;
2770     }
2771   }
2772
2773   // If the calling conventions do not match, then we'd better make sure the
2774   // results are returned in the same way as what the caller expects.
2775   if (!CCMatch) {
2776     SmallVector<CCValAssign, 16> RVLocs1;
2777     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2778                     getTargetMachine(), RVLocs1, *DAG.getContext());
2779     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2780
2781     SmallVector<CCValAssign, 16> RVLocs2;
2782     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2783                     getTargetMachine(), RVLocs2, *DAG.getContext());
2784     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2785
2786     if (RVLocs1.size() != RVLocs2.size())
2787       return false;
2788     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2789       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2790         return false;
2791       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2792         return false;
2793       if (RVLocs1[i].isRegLoc()) {
2794         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2795           return false;
2796       } else {
2797         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2798           return false;
2799       }
2800     }
2801   }
2802
2803   // If the callee takes no arguments then go on to check the results of the
2804   // call.
2805   if (!Outs.empty()) {
2806     // Check if stack adjustment is needed. For now, do not do this if any
2807     // argument is passed on the stack.
2808     SmallVector<CCValAssign, 16> ArgLocs;
2809     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2810                    getTargetMachine(), ArgLocs, *DAG.getContext());
2811
2812     // Allocate shadow area for Win64
2813     if (Subtarget->isTargetWin64()) {
2814       CCInfo.AllocateStack(32, 8);
2815     }
2816
2817     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2818     if (CCInfo.getNextStackOffset()) {
2819       MachineFunction &MF = DAG.getMachineFunction();
2820       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2821         return false;
2822
2823       // Check if the arguments are already laid out in the right way as
2824       // the caller's fixed stack objects.
2825       MachineFrameInfo *MFI = MF.getFrameInfo();
2826       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2827       const X86InstrInfo *TII =
2828         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2829       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2830         CCValAssign &VA = ArgLocs[i];
2831         SDValue Arg = OutVals[i];
2832         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2833         if (VA.getLocInfo() == CCValAssign::Indirect)
2834           return false;
2835         if (!VA.isRegLoc()) {
2836           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2837                                    MFI, MRI, TII))
2838             return false;
2839         }
2840       }
2841     }
2842
2843     // If the tailcall address may be in a register, then make sure it's
2844     // possible to register allocate for it. In 32-bit, the call address can
2845     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2846     // callee-saved registers are restored. These happen to be the same
2847     // registers used to pass 'inreg' arguments so watch out for those.
2848     if (!Subtarget->is64Bit() &&
2849         !isa<GlobalAddressSDNode>(Callee) &&
2850         !isa<ExternalSymbolSDNode>(Callee)) {
2851       unsigned NumInRegs = 0;
2852       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2853         CCValAssign &VA = ArgLocs[i];
2854         if (!VA.isRegLoc())
2855           continue;
2856         unsigned Reg = VA.getLocReg();
2857         switch (Reg) {
2858         default: break;
2859         case X86::EAX: case X86::EDX: case X86::ECX:
2860           if (++NumInRegs == 3)
2861             return false;
2862           break;
2863         }
2864       }
2865     }
2866   }
2867
2868   return true;
2869 }
2870
2871 FastISel *
2872 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2873   return X86::createFastISel(funcInfo);
2874 }
2875
2876
2877 //===----------------------------------------------------------------------===//
2878 //                           Other Lowering Hooks
2879 //===----------------------------------------------------------------------===//
2880
2881 static bool MayFoldLoad(SDValue Op) {
2882   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2883 }
2884
2885 static bool MayFoldIntoStore(SDValue Op) {
2886   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2887 }
2888
2889 static bool isTargetShuffle(unsigned Opcode) {
2890   switch(Opcode) {
2891   default: return false;
2892   case X86ISD::PSHUFD:
2893   case X86ISD::PSHUFHW:
2894   case X86ISD::PSHUFLW:
2895   case X86ISD::SHUFP:
2896   case X86ISD::PALIGN:
2897   case X86ISD::MOVLHPS:
2898   case X86ISD::MOVLHPD:
2899   case X86ISD::MOVHLPS:
2900   case X86ISD::MOVLPS:
2901   case X86ISD::MOVLPD:
2902   case X86ISD::MOVSHDUP:
2903   case X86ISD::MOVSLDUP:
2904   case X86ISD::MOVDDUP:
2905   case X86ISD::MOVSS:
2906   case X86ISD::MOVSD:
2907   case X86ISD::UNPCKL:
2908   case X86ISD::UNPCKH:
2909   case X86ISD::VPERMILP:
2910   case X86ISD::VPERM2X128:
2911     return true;
2912   }
2913 }
2914
2915 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2916                                     SDValue V1, SelectionDAG &DAG) {
2917   switch(Opc) {
2918   default: llvm_unreachable("Unknown x86 shuffle node");
2919   case X86ISD::MOVSHDUP:
2920   case X86ISD::MOVSLDUP:
2921   case X86ISD::MOVDDUP:
2922     return DAG.getNode(Opc, dl, VT, V1);
2923   }
2924 }
2925
2926 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2927                                     SDValue V1, unsigned TargetMask,
2928                                     SelectionDAG &DAG) {
2929   switch(Opc) {
2930   default: llvm_unreachable("Unknown x86 shuffle node");
2931   case X86ISD::PSHUFD:
2932   case X86ISD::PSHUFHW:
2933   case X86ISD::PSHUFLW:
2934   case X86ISD::VPERMILP:
2935   case X86ISD::VPERMI:
2936     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2937   }
2938 }
2939
2940 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2941                                     SDValue V1, SDValue V2, unsigned TargetMask,
2942                                     SelectionDAG &DAG) {
2943   switch(Opc) {
2944   default: llvm_unreachable("Unknown x86 shuffle node");
2945   case X86ISD::PALIGN:
2946   case X86ISD::SHUFP:
2947   case X86ISD::VPERM2X128:
2948     return DAG.getNode(Opc, dl, VT, V1, V2,
2949                        DAG.getConstant(TargetMask, MVT::i8));
2950   }
2951 }
2952
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2955   switch(Opc) {
2956   default: llvm_unreachable("Unknown x86 shuffle node");
2957   case X86ISD::MOVLHPS:
2958   case X86ISD::MOVLHPD:
2959   case X86ISD::MOVHLPS:
2960   case X86ISD::MOVLPS:
2961   case X86ISD::MOVLPD:
2962   case X86ISD::MOVSS:
2963   case X86ISD::MOVSD:
2964   case X86ISD::UNPCKL:
2965   case X86ISD::UNPCKH:
2966     return DAG.getNode(Opc, dl, VT, V1, V2);
2967   }
2968 }
2969
2970 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2971   MachineFunction &MF = DAG.getMachineFunction();
2972   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2973   int ReturnAddrIndex = FuncInfo->getRAIndex();
2974
2975   if (ReturnAddrIndex == 0) {
2976     // Set up a frame object for the return address.
2977     uint64_t SlotSize = TD->getPointerSize();
2978     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2979                                                            false);
2980     FuncInfo->setRAIndex(ReturnAddrIndex);
2981   }
2982
2983   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2984 }
2985
2986
2987 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2988                                        bool hasSymbolicDisplacement) {
2989   // Offset should fit into 32 bit immediate field.
2990   if (!isInt<32>(Offset))
2991     return false;
2992
2993   // If we don't have a symbolic displacement - we don't have any extra
2994   // restrictions.
2995   if (!hasSymbolicDisplacement)
2996     return true;
2997
2998   // FIXME: Some tweaks might be needed for medium code model.
2999   if (M != CodeModel::Small && M != CodeModel::Kernel)
3000     return false;
3001
3002   // For small code model we assume that latest object is 16MB before end of 31
3003   // bits boundary. We may also accept pretty large negative constants knowing
3004   // that all objects are in the positive half of address space.
3005   if (M == CodeModel::Small && Offset < 16*1024*1024)
3006     return true;
3007
3008   // For kernel code model we know that all object resist in the negative half
3009   // of 32bits address space. We may not accept negative offsets, since they may
3010   // be just off and we may accept pretty large positive ones.
3011   if (M == CodeModel::Kernel && Offset > 0)
3012     return true;
3013
3014   return false;
3015 }
3016
3017 /// isCalleePop - Determines whether the callee is required to pop its
3018 /// own arguments. Callee pop is necessary to support tail calls.
3019 bool X86::isCalleePop(CallingConv::ID CallingConv,
3020                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3021   if (IsVarArg)
3022     return false;
3023
3024   switch (CallingConv) {
3025   default:
3026     return false;
3027   case CallingConv::X86_StdCall:
3028     return !is64Bit;
3029   case CallingConv::X86_FastCall:
3030     return !is64Bit;
3031   case CallingConv::X86_ThisCall:
3032     return !is64Bit;
3033   case CallingConv::Fast:
3034     return TailCallOpt;
3035   case CallingConv::GHC:
3036     return TailCallOpt;
3037   }
3038 }
3039
3040 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3041 /// specific condition code, returning the condition code and the LHS/RHS of the
3042 /// comparison to make.
3043 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3044                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3045   if (!isFP) {
3046     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3047       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3048         // X > -1   -> X == 0, jump !sign.
3049         RHS = DAG.getConstant(0, RHS.getValueType());
3050         return X86::COND_NS;
3051       }
3052       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3053         // X < 0   -> X == 0, jump on sign.
3054         return X86::COND_S;
3055       }
3056       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3057         // X < 1   -> X <= 0
3058         RHS = DAG.getConstant(0, RHS.getValueType());
3059         return X86::COND_LE;
3060       }
3061     }
3062
3063     switch (SetCCOpcode) {
3064     default: llvm_unreachable("Invalid integer condition!");
3065     case ISD::SETEQ:  return X86::COND_E;
3066     case ISD::SETGT:  return X86::COND_G;
3067     case ISD::SETGE:  return X86::COND_GE;
3068     case ISD::SETLT:  return X86::COND_L;
3069     case ISD::SETLE:  return X86::COND_LE;
3070     case ISD::SETNE:  return X86::COND_NE;
3071     case ISD::SETULT: return X86::COND_B;
3072     case ISD::SETUGT: return X86::COND_A;
3073     case ISD::SETULE: return X86::COND_BE;
3074     case ISD::SETUGE: return X86::COND_AE;
3075     }
3076   }
3077
3078   // First determine if it is required or is profitable to flip the operands.
3079
3080   // If LHS is a foldable load, but RHS is not, flip the condition.
3081   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3082       !ISD::isNON_EXTLoad(RHS.getNode())) {
3083     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3084     std::swap(LHS, RHS);
3085   }
3086
3087   switch (SetCCOpcode) {
3088   default: break;
3089   case ISD::SETOLT:
3090   case ISD::SETOLE:
3091   case ISD::SETUGT:
3092   case ISD::SETUGE:
3093     std::swap(LHS, RHS);
3094     break;
3095   }
3096
3097   // On a floating point condition, the flags are set as follows:
3098   // ZF  PF  CF   op
3099   //  0 | 0 | 0 | X > Y
3100   //  0 | 0 | 1 | X < Y
3101   //  1 | 0 | 0 | X == Y
3102   //  1 | 1 | 1 | unordered
3103   switch (SetCCOpcode) {
3104   default: llvm_unreachable("Condcode should be pre-legalized away");
3105   case ISD::SETUEQ:
3106   case ISD::SETEQ:   return X86::COND_E;
3107   case ISD::SETOLT:              // flipped
3108   case ISD::SETOGT:
3109   case ISD::SETGT:   return X86::COND_A;
3110   case ISD::SETOLE:              // flipped
3111   case ISD::SETOGE:
3112   case ISD::SETGE:   return X86::COND_AE;
3113   case ISD::SETUGT:              // flipped
3114   case ISD::SETULT:
3115   case ISD::SETLT:   return X86::COND_B;
3116   case ISD::SETUGE:              // flipped
3117   case ISD::SETULE:
3118   case ISD::SETLE:   return X86::COND_BE;
3119   case ISD::SETONE:
3120   case ISD::SETNE:   return X86::COND_NE;
3121   case ISD::SETUO:   return X86::COND_P;
3122   case ISD::SETO:    return X86::COND_NP;
3123   case ISD::SETOEQ:
3124   case ISD::SETUNE:  return X86::COND_INVALID;
3125   }
3126 }
3127
3128 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3129 /// code. Current x86 isa includes the following FP cmov instructions:
3130 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3131 static bool hasFPCMov(unsigned X86CC) {
3132   switch (X86CC) {
3133   default:
3134     return false;
3135   case X86::COND_B:
3136   case X86::COND_BE:
3137   case X86::COND_E:
3138   case X86::COND_P:
3139   case X86::COND_A:
3140   case X86::COND_AE:
3141   case X86::COND_NE:
3142   case X86::COND_NP:
3143     return true;
3144   }
3145 }
3146
3147 /// isFPImmLegal - Returns true if the target can instruction select the
3148 /// specified FP immediate natively. If false, the legalizer will
3149 /// materialize the FP immediate as a load from a constant pool.
3150 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3151   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3152     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3153       return true;
3154   }
3155   return false;
3156 }
3157
3158 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3159 /// the specified range (L, H].
3160 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3161   return (Val < 0) || (Val >= Low && Val < Hi);
3162 }
3163
3164 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3165 /// specified value.
3166 static bool isUndefOrEqual(int Val, int CmpVal) {
3167   if (Val < 0 || Val == CmpVal)
3168     return true;
3169   return false;
3170 }
3171
3172 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3173 /// from position Pos and ending in Pos+Size, falls within the specified
3174 /// sequential range (L, L+Pos]. or is undef.
3175 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3176                                        int Pos, int Size, int Low) {
3177   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3178     if (!isUndefOrEqual(Mask[i], Low))
3179       return false;
3180   return true;
3181 }
3182
3183 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3184 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3185 /// the second operand.
3186 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3187   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3188     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3189   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3190     return (Mask[0] < 2 && Mask[1] < 2);
3191   return false;
3192 }
3193
3194 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3195 /// is suitable for input to PSHUFHW.
3196 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT) {
3197   if (VT != MVT::v8i16)
3198     return false;
3199
3200   // Lower quadword copied in order or undef.
3201   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3202     return false;
3203
3204   // Upper quadword shuffled.
3205   for (unsigned i = 4; i != 8; ++i)
3206     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3207       return false;
3208
3209   return true;
3210 }
3211
3212 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFLW.
3214 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT) {
3215   if (VT != MVT::v8i16)
3216     return false;
3217
3218   // Upper quadword copied in order.
3219   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3220     return false;
3221
3222   // Lower quadword shuffled.
3223   for (unsigned i = 0; i != 4; ++i)
3224     if (Mask[i] >= 4)
3225       return false;
3226
3227   return true;
3228 }
3229
3230 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3231 /// is suitable for input to PALIGNR.
3232 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3233                           const X86Subtarget *Subtarget) {
3234   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3235       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3236     return false;
3237
3238   unsigned NumElts = VT.getVectorNumElements();
3239   unsigned NumLanes = VT.getSizeInBits()/128;
3240   unsigned NumLaneElts = NumElts/NumLanes;
3241
3242   // Do not handle 64-bit element shuffles with palignr.
3243   if (NumLaneElts == 2)
3244     return false;
3245
3246   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3247     unsigned i;
3248     for (i = 0; i != NumLaneElts; ++i) {
3249       if (Mask[i+l] >= 0)
3250         break;
3251     }
3252
3253     // Lane is all undef, go to next lane
3254     if (i == NumLaneElts)
3255       continue;
3256
3257     int Start = Mask[i+l];
3258
3259     // Make sure its in this lane in one of the sources
3260     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3261         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3262       return false;
3263
3264     // If not lane 0, then we must match lane 0
3265     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3266       return false;
3267
3268     // Correct second source to be contiguous with first source
3269     if (Start >= (int)NumElts)
3270       Start -= NumElts - NumLaneElts;
3271
3272     // Make sure we're shifting in the right direction.
3273     if (Start <= (int)(i+l))
3274       return false;
3275
3276     Start -= i;
3277
3278     // Check the rest of the elements to see if they are consecutive.
3279     for (++i; i != NumLaneElts; ++i) {
3280       int Idx = Mask[i+l];
3281
3282       // Make sure its in this lane
3283       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3284           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3285         return false;
3286
3287       // If not lane 0, then we must match lane 0
3288       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3289         return false;
3290
3291       if (Idx >= (int)NumElts)
3292         Idx -= NumElts - NumLaneElts;
3293
3294       if (!isUndefOrEqual(Idx, Start+i))
3295         return false;
3296
3297     }
3298   }
3299
3300   return true;
3301 }
3302
3303 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3304 /// the two vector operands have swapped position.
3305 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3306                                      unsigned NumElems) {
3307   for (unsigned i = 0; i != NumElems; ++i) {
3308     int idx = Mask[i];
3309     if (idx < 0)
3310       continue;
3311     else if (idx < (int)NumElems)
3312       Mask[i] = idx + NumElems;
3313     else
3314       Mask[i] = idx - NumElems;
3315   }
3316 }
3317
3318 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3319 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3320 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3321 /// reverse of what x86 shuffles want.
3322 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3323                         bool Commuted = false) {
3324   if (!HasAVX && VT.getSizeInBits() == 256)
3325     return false;
3326
3327   unsigned NumElems = VT.getVectorNumElements();
3328   unsigned NumLanes = VT.getSizeInBits()/128;
3329   unsigned NumLaneElems = NumElems/NumLanes;
3330
3331   if (NumLaneElems != 2 && NumLaneElems != 4)
3332     return false;
3333
3334   // VSHUFPSY divides the resulting vector into 4 chunks.
3335   // The sources are also splitted into 4 chunks, and each destination
3336   // chunk must come from a different source chunk.
3337   //
3338   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3339   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3340   //
3341   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3342   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3343   //
3344   // VSHUFPDY divides the resulting vector into 4 chunks.
3345   // The sources are also splitted into 4 chunks, and each destination
3346   // chunk must come from a different source chunk.
3347   //
3348   //  SRC1 =>      X3       X2       X1       X0
3349   //  SRC2 =>      Y3       Y2       Y1       Y0
3350   //
3351   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3352   //
3353   unsigned HalfLaneElems = NumLaneElems/2;
3354   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3355     for (unsigned i = 0; i != NumLaneElems; ++i) {
3356       int Idx = Mask[i+l];
3357       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3358       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3359         return false;
3360       // For VSHUFPSY, the mask of the second half must be the same as the
3361       // first but with the appropriate offsets. This works in the same way as
3362       // VPERMILPS works with masks.
3363       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3364         continue;
3365       if (!isUndefOrEqual(Idx, Mask[i]+l))
3366         return false;
3367     }
3368   }
3369
3370   return true;
3371 }
3372
3373 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3374 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3375 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3376   unsigned NumElems = VT.getVectorNumElements();
3377
3378   if (VT.getSizeInBits() != 128)
3379     return false;
3380
3381   if (NumElems != 4)
3382     return false;
3383
3384   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3385   return isUndefOrEqual(Mask[0], 6) &&
3386          isUndefOrEqual(Mask[1], 7) &&
3387          isUndefOrEqual(Mask[2], 2) &&
3388          isUndefOrEqual(Mask[3], 3);
3389 }
3390
3391 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3392 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3393 /// <2, 3, 2, 3>
3394 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3395   unsigned NumElems = VT.getVectorNumElements();
3396
3397   if (VT.getSizeInBits() != 128)
3398     return false;
3399
3400   if (NumElems != 4)
3401     return false;
3402
3403   return isUndefOrEqual(Mask[0], 2) &&
3404          isUndefOrEqual(Mask[1], 3) &&
3405          isUndefOrEqual(Mask[2], 2) &&
3406          isUndefOrEqual(Mask[3], 3);
3407 }
3408
3409 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3410 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3411 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3412   if (VT.getSizeInBits() != 128)
3413     return false;
3414
3415   unsigned NumElems = VT.getVectorNumElements();
3416
3417   if (NumElems != 2 && NumElems != 4)
3418     return false;
3419
3420   for (unsigned i = 0; i != NumElems/2; ++i)
3421     if (!isUndefOrEqual(Mask[i], i + NumElems))
3422       return false;
3423
3424   for (unsigned i = NumElems/2; i != NumElems; ++i)
3425     if (!isUndefOrEqual(Mask[i], i))
3426       return false;
3427
3428   return true;
3429 }
3430
3431 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3432 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3433 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3434   unsigned NumElems = VT.getVectorNumElements();
3435
3436   if ((NumElems != 2 && NumElems != 4)
3437       || VT.getSizeInBits() > 128)
3438     return false;
3439
3440   for (unsigned i = 0; i != NumElems/2; ++i)
3441     if (!isUndefOrEqual(Mask[i], i))
3442       return false;
3443
3444   for (unsigned i = 0; i != NumElems/2; ++i)
3445     if (!isUndefOrEqual(Mask[i + NumElems/2], i + NumElems))
3446       return false;
3447
3448   return true;
3449 }
3450
3451 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3452 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3453 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3454                          bool HasAVX2, bool V2IsSplat = false) {
3455   unsigned NumElts = VT.getVectorNumElements();
3456
3457   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3458          "Unsupported vector type for unpckh");
3459
3460   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3461       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3462     return false;
3463
3464   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3465   // independently on 128-bit lanes.
3466   unsigned NumLanes = VT.getSizeInBits()/128;
3467   unsigned NumLaneElts = NumElts/NumLanes;
3468
3469   for (unsigned l = 0; l != NumLanes; ++l) {
3470     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3471          i != (l+1)*NumLaneElts;
3472          i += 2, ++j) {
3473       int BitI  = Mask[i];
3474       int BitI1 = Mask[i+1];
3475       if (!isUndefOrEqual(BitI, j))
3476         return false;
3477       if (V2IsSplat) {
3478         if (!isUndefOrEqual(BitI1, NumElts))
3479           return false;
3480       } else {
3481         if (!isUndefOrEqual(BitI1, j + NumElts))
3482           return false;
3483       }
3484     }
3485   }
3486
3487   return true;
3488 }
3489
3490 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3491 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3492 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3493                          bool HasAVX2, bool V2IsSplat = false) {
3494   unsigned NumElts = VT.getVectorNumElements();
3495
3496   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3497          "Unsupported vector type for unpckh");
3498
3499   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3500       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3501     return false;
3502
3503   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3504   // independently on 128-bit lanes.
3505   unsigned NumLanes = VT.getSizeInBits()/128;
3506   unsigned NumLaneElts = NumElts/NumLanes;
3507
3508   for (unsigned l = 0; l != NumLanes; ++l) {
3509     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3510          i != (l+1)*NumLaneElts; i += 2, ++j) {
3511       int BitI  = Mask[i];
3512       int BitI1 = Mask[i+1];
3513       if (!isUndefOrEqual(BitI, j))
3514         return false;
3515       if (V2IsSplat) {
3516         if (isUndefOrEqual(BitI1, NumElts))
3517           return false;
3518       } else {
3519         if (!isUndefOrEqual(BitI1, j+NumElts))
3520           return false;
3521       }
3522     }
3523   }
3524   return true;
3525 }
3526
3527 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3528 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3529 /// <0, 0, 1, 1>
3530 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3531                                   bool HasAVX2) {
3532   unsigned NumElts = VT.getVectorNumElements();
3533
3534   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3535          "Unsupported vector type for unpckh");
3536
3537   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3538       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3539     return false;
3540
3541   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3542   // FIXME: Need a better way to get rid of this, there's no latency difference
3543   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3544   // the former later. We should also remove the "_undef" special mask.
3545   if (NumElts == 4 && VT.getSizeInBits() == 256)
3546     return false;
3547
3548   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3549   // independently on 128-bit lanes.
3550   unsigned NumLanes = VT.getSizeInBits()/128;
3551   unsigned NumLaneElts = NumElts/NumLanes;
3552
3553   for (unsigned l = 0; l != NumLanes; ++l) {
3554     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3555          i != (l+1)*NumLaneElts;
3556          i += 2, ++j) {
3557       int BitI  = Mask[i];
3558       int BitI1 = Mask[i+1];
3559
3560       if (!isUndefOrEqual(BitI, j))
3561         return false;
3562       if (!isUndefOrEqual(BitI1, j))
3563         return false;
3564     }
3565   }
3566
3567   return true;
3568 }
3569
3570 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3571 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3572 /// <2, 2, 3, 3>
3573 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3574   unsigned NumElts = VT.getVectorNumElements();
3575
3576   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3577          "Unsupported vector type for unpckh");
3578
3579   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3580       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3581     return false;
3582
3583   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3584   // independently on 128-bit lanes.
3585   unsigned NumLanes = VT.getSizeInBits()/128;
3586   unsigned NumLaneElts = NumElts/NumLanes;
3587
3588   for (unsigned l = 0; l != NumLanes; ++l) {
3589     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3590          i != (l+1)*NumLaneElts; i += 2, ++j) {
3591       int BitI  = Mask[i];
3592       int BitI1 = Mask[i+1];
3593       if (!isUndefOrEqual(BitI, j))
3594         return false;
3595       if (!isUndefOrEqual(BitI1, j))
3596         return false;
3597     }
3598   }
3599   return true;
3600 }
3601
3602 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3603 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3604 /// MOVSD, and MOVD, i.e. setting the lowest element.
3605 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3606   if (VT.getVectorElementType().getSizeInBits() < 32)
3607     return false;
3608   if (VT.getSizeInBits() == 256)
3609     return false;
3610
3611   unsigned NumElts = VT.getVectorNumElements();
3612
3613   if (!isUndefOrEqual(Mask[0], NumElts))
3614     return false;
3615
3616   for (unsigned i = 1; i != NumElts; ++i)
3617     if (!isUndefOrEqual(Mask[i], i))
3618       return false;
3619
3620   return true;
3621 }
3622
3623 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3624 /// as permutations between 128-bit chunks or halves. As an example: this
3625 /// shuffle bellow:
3626 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3627 /// The first half comes from the second half of V1 and the second half from the
3628 /// the second half of V2.
3629 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3630   if (!HasAVX || VT.getSizeInBits() != 256)
3631     return false;
3632
3633   // The shuffle result is divided into half A and half B. In total the two
3634   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3635   // B must come from C, D, E or F.
3636   unsigned HalfSize = VT.getVectorNumElements()/2;
3637   bool MatchA = false, MatchB = false;
3638
3639   // Check if A comes from one of C, D, E, F.
3640   for (unsigned Half = 0; Half != 4; ++Half) {
3641     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3642       MatchA = true;
3643       break;
3644     }
3645   }
3646
3647   // Check if B comes from one of C, D, E, F.
3648   for (unsigned Half = 0; Half != 4; ++Half) {
3649     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3650       MatchB = true;
3651       break;
3652     }
3653   }
3654
3655   return MatchA && MatchB;
3656 }
3657
3658 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3659 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3660 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3661   EVT VT = SVOp->getValueType(0);
3662
3663   unsigned HalfSize = VT.getVectorNumElements()/2;
3664
3665   unsigned FstHalf = 0, SndHalf = 0;
3666   for (unsigned i = 0; i < HalfSize; ++i) {
3667     if (SVOp->getMaskElt(i) > 0) {
3668       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3669       break;
3670     }
3671   }
3672   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3673     if (SVOp->getMaskElt(i) > 0) {
3674       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3675       break;
3676     }
3677   }
3678
3679   return (FstHalf | (SndHalf << 4));
3680 }
3681
3682 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3683 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3684 /// Note that VPERMIL mask matching is different depending whether theunderlying
3685 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3686 /// to the same elements of the low, but to the higher half of the source.
3687 /// In VPERMILPD the two lanes could be shuffled independently of each other
3688 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3689 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3690   if (!HasAVX)
3691     return false;
3692
3693   unsigned NumElts = VT.getVectorNumElements();
3694   // Only match 256-bit with 32/64-bit types
3695   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3696     return false;
3697
3698   unsigned NumLanes = VT.getSizeInBits()/128;
3699   unsigned LaneSize = NumElts/NumLanes;
3700   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3701     for (unsigned i = 0; i != LaneSize; ++i) {
3702       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3703         return false;
3704       if (NumElts != 8 || l == 0)
3705         continue;
3706       // VPERMILPS handling
3707       if (Mask[i] < 0)
3708         continue;
3709       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3710         return false;
3711     }
3712   }
3713
3714   return true;
3715 }
3716
3717 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3718 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3719 /// element of vector 2 and the other elements to come from vector 1 in order.
3720 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3721                                bool V2IsSplat = false, bool V2IsUndef = false) {
3722   unsigned NumOps = VT.getVectorNumElements();
3723   if (VT.getSizeInBits() == 256)
3724     return false;
3725   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3726     return false;
3727
3728   if (!isUndefOrEqual(Mask[0], 0))
3729     return false;
3730
3731   for (unsigned i = 1; i != NumOps; ++i)
3732     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3733           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3734           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3735       return false;
3736
3737   return true;
3738 }
3739
3740 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3741 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3742 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3743 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3744                            const X86Subtarget *Subtarget) {
3745   if (!Subtarget->hasSSE3())
3746     return false;
3747
3748   unsigned NumElems = VT.getVectorNumElements();
3749
3750   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3751       (VT.getSizeInBits() == 256 && NumElems != 8))
3752     return false;
3753
3754   // "i+1" is the value the indexed mask element must have
3755   for (unsigned i = 0; i != NumElems; i += 2)
3756     if (!isUndefOrEqual(Mask[i], i+1) ||
3757         !isUndefOrEqual(Mask[i+1], i+1))
3758       return false;
3759
3760   return true;
3761 }
3762
3763 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3764 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3765 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3766 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3767                            const X86Subtarget *Subtarget) {
3768   if (!Subtarget->hasSSE3())
3769     return false;
3770
3771   unsigned NumElems = VT.getVectorNumElements();
3772
3773   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3774       (VT.getSizeInBits() == 256 && NumElems != 8))
3775     return false;
3776
3777   // "i" is the value the indexed mask element must have
3778   for (unsigned i = 0; i != NumElems; i += 2)
3779     if (!isUndefOrEqual(Mask[i], i) ||
3780         !isUndefOrEqual(Mask[i+1], i))
3781       return false;
3782
3783   return true;
3784 }
3785
3786 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3787 /// specifies a shuffle of elements that is suitable for input to 256-bit
3788 /// version of MOVDDUP.
3789 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3790   unsigned NumElts = VT.getVectorNumElements();
3791
3792   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3793     return false;
3794
3795   for (unsigned i = 0; i != NumElts/2; ++i)
3796     if (!isUndefOrEqual(Mask[i], 0))
3797       return false;
3798   for (unsigned i = NumElts/2; i != NumElts; ++i)
3799     if (!isUndefOrEqual(Mask[i], NumElts/2))
3800       return false;
3801   return true;
3802 }
3803
3804 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3805 /// specifies a shuffle of elements that is suitable for input to 128-bit
3806 /// version of MOVDDUP.
3807 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3808   if (VT.getSizeInBits() != 128)
3809     return false;
3810
3811   unsigned e = VT.getVectorNumElements() / 2;
3812   for (unsigned i = 0; i != e; ++i)
3813     if (!isUndefOrEqual(Mask[i], i))
3814       return false;
3815   for (unsigned i = 0; i != e; ++i)
3816     if (!isUndefOrEqual(Mask[e+i], i))
3817       return false;
3818   return true;
3819 }
3820
3821 /// isVEXTRACTF128Index - Return true if the specified
3822 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3823 /// suitable for input to VEXTRACTF128.
3824 bool X86::isVEXTRACTF128Index(SDNode *N) {
3825   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3826     return false;
3827
3828   // The index should be aligned on a 128-bit boundary.
3829   uint64_t Index =
3830     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3831
3832   unsigned VL = N->getValueType(0).getVectorNumElements();
3833   unsigned VBits = N->getValueType(0).getSizeInBits();
3834   unsigned ElSize = VBits / VL;
3835   bool Result = (Index * ElSize) % 128 == 0;
3836
3837   return Result;
3838 }
3839
3840 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3841 /// operand specifies a subvector insert that is suitable for input to
3842 /// VINSERTF128.
3843 bool X86::isVINSERTF128Index(SDNode *N) {
3844   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3845     return false;
3846
3847   // The index should be aligned on a 128-bit boundary.
3848   uint64_t Index =
3849     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3850
3851   unsigned VL = N->getValueType(0).getVectorNumElements();
3852   unsigned VBits = N->getValueType(0).getSizeInBits();
3853   unsigned ElSize = VBits / VL;
3854   bool Result = (Index * ElSize) % 128 == 0;
3855
3856   return Result;
3857 }
3858
3859 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3860 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3861 /// Handles 128-bit and 256-bit.
3862 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3863   EVT VT = N->getValueType(0);
3864
3865   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3866          "Unsupported vector type for PSHUF/SHUFP");
3867
3868   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3869   // independently on 128-bit lanes.
3870   unsigned NumElts = VT.getVectorNumElements();
3871   unsigned NumLanes = VT.getSizeInBits()/128;
3872   unsigned NumLaneElts = NumElts/NumLanes;
3873
3874   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3875          "Only supports 2 or 4 elements per lane");
3876
3877   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3878   unsigned Mask = 0;
3879   for (unsigned i = 0; i != NumElts; ++i) {
3880     int Elt = N->getMaskElt(i);
3881     if (Elt < 0) continue;
3882     Elt %= NumLaneElts;
3883     unsigned ShAmt = i << Shift;
3884     if (ShAmt >= 8) ShAmt -= 8;
3885     Mask |= Elt << ShAmt;
3886   }
3887
3888   return Mask;
3889 }
3890
3891 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3892 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3893 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3894   unsigned Mask = 0;
3895   // 8 nodes, but we only care about the last 4.
3896   for (unsigned i = 7; i >= 4; --i) {
3897     int Val = N->getMaskElt(i);
3898     if (Val >= 0)
3899       Mask |= (Val - 4);
3900     if (i != 4)
3901       Mask <<= 2;
3902   }
3903   return Mask;
3904 }
3905
3906 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3907 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3908 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3909   unsigned Mask = 0;
3910   // 8 nodes, but we only care about the first 4.
3911   for (int i = 3; i >= 0; --i) {
3912     int Val = N->getMaskElt(i);
3913     if (Val >= 0)
3914       Mask |= Val;
3915     if (i != 0)
3916       Mask <<= 2;
3917   }
3918   return Mask;
3919 }
3920
3921 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3922 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3923 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3924   EVT VT = SVOp->getValueType(0);
3925   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3926
3927   unsigned NumElts = VT.getVectorNumElements();
3928   unsigned NumLanes = VT.getSizeInBits()/128;
3929   unsigned NumLaneElts = NumElts/NumLanes;
3930
3931   int Val = 0;
3932   unsigned i;
3933   for (i = 0; i != NumElts; ++i) {
3934     Val = SVOp->getMaskElt(i);
3935     if (Val >= 0)
3936       break;
3937   }
3938   if (Val >= (int)NumElts)
3939     Val -= NumElts - NumLaneElts;
3940
3941   assert(Val - i > 0 && "PALIGNR imm should be positive");
3942   return (Val - i) * EltSize;
3943 }
3944
3945 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3946 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3947 /// instructions.
3948 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3949   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3950     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3951
3952   uint64_t Index =
3953     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3954
3955   EVT VecVT = N->getOperand(0).getValueType();
3956   EVT ElVT = VecVT.getVectorElementType();
3957
3958   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3959   return Index / NumElemsPerChunk;
3960 }
3961
3962 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3963 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3964 /// instructions.
3965 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3966   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3967     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3968
3969   uint64_t Index =
3970     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3971
3972   EVT VecVT = N->getValueType(0);
3973   EVT ElVT = VecVT.getVectorElementType();
3974
3975   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3976   return Index / NumElemsPerChunk;
3977 }
3978
3979 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
3980 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
3981 /// Handles 256-bit.
3982 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
3983   EVT VT = N->getValueType(0);
3984
3985   unsigned NumElts = VT.getVectorNumElements();
3986
3987   assert((VT.is256BitVector() && NumElts == 4) &&
3988          "Unsupported vector type for VPERMQ/VPERMPD");
3989
3990   unsigned Mask = 0;
3991   for (unsigned i = 0; i != NumElts; ++i) {
3992     int Elt = N->getMaskElt(i);
3993     if (Elt < 0)
3994       continue;
3995     Mask |= Elt << (i*2);
3996   }
3997
3998   return Mask;
3999 }
4000 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4001 /// constant +0.0.
4002 bool X86::isZeroNode(SDValue Elt) {
4003   return ((isa<ConstantSDNode>(Elt) &&
4004            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4005           (isa<ConstantFPSDNode>(Elt) &&
4006            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4007 }
4008
4009 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4010 /// their permute mask.
4011 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4012                                     SelectionDAG &DAG) {
4013   EVT VT = SVOp->getValueType(0);
4014   unsigned NumElems = VT.getVectorNumElements();
4015   SmallVector<int, 8> MaskVec;
4016
4017   for (unsigned i = 0; i != NumElems; ++i) {
4018     int idx = SVOp->getMaskElt(i);
4019     if (idx < 0)
4020       MaskVec.push_back(idx);
4021     else if (idx < (int)NumElems)
4022       MaskVec.push_back(idx + NumElems);
4023     else
4024       MaskVec.push_back(idx - NumElems);
4025   }
4026   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4027                               SVOp->getOperand(0), &MaskVec[0]);
4028 }
4029
4030 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4031 /// match movhlps. The lower half elements should come from upper half of
4032 /// V1 (and in order), and the upper half elements should come from the upper
4033 /// half of V2 (and in order).
4034 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4035   if (VT.getSizeInBits() != 128)
4036     return false;
4037   if (VT.getVectorNumElements() != 4)
4038     return false;
4039   for (unsigned i = 0, e = 2; i != e; ++i)
4040     if (!isUndefOrEqual(Mask[i], i+2))
4041       return false;
4042   for (unsigned i = 2; i != 4; ++i)
4043     if (!isUndefOrEqual(Mask[i], i+4))
4044       return false;
4045   return true;
4046 }
4047
4048 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4049 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4050 /// required.
4051 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4052   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4053     return false;
4054   N = N->getOperand(0).getNode();
4055   if (!ISD::isNON_EXTLoad(N))
4056     return false;
4057   if (LD)
4058     *LD = cast<LoadSDNode>(N);
4059   return true;
4060 }
4061
4062 // Test whether the given value is a vector value which will be legalized
4063 // into a load.
4064 static bool WillBeConstantPoolLoad(SDNode *N) {
4065   if (N->getOpcode() != ISD::BUILD_VECTOR)
4066     return false;
4067
4068   // Check for any non-constant elements.
4069   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4070     switch (N->getOperand(i).getNode()->getOpcode()) {
4071     case ISD::UNDEF:
4072     case ISD::ConstantFP:
4073     case ISD::Constant:
4074       break;
4075     default:
4076       return false;
4077     }
4078
4079   // Vectors of all-zeros and all-ones are materialized with special
4080   // instructions rather than being loaded.
4081   return !ISD::isBuildVectorAllZeros(N) &&
4082          !ISD::isBuildVectorAllOnes(N);
4083 }
4084
4085 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4086 /// match movlp{s|d}. The lower half elements should come from lower half of
4087 /// V1 (and in order), and the upper half elements should come from the upper
4088 /// half of V2 (and in order). And since V1 will become the source of the
4089 /// MOVLP, it must be either a vector load or a scalar load to vector.
4090 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4091                                ArrayRef<int> Mask, EVT VT) {
4092   if (VT.getSizeInBits() != 128)
4093     return false;
4094
4095   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4096     return false;
4097   // Is V2 is a vector load, don't do this transformation. We will try to use
4098   // load folding shufps op.
4099   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4100     return false;
4101
4102   unsigned NumElems = VT.getVectorNumElements();
4103
4104   if (NumElems != 2 && NumElems != 4)
4105     return false;
4106   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4107     if (!isUndefOrEqual(Mask[i], i))
4108       return false;
4109   for (unsigned i = NumElems/2; i != NumElems; ++i)
4110     if (!isUndefOrEqual(Mask[i], i+NumElems))
4111       return false;
4112   return true;
4113 }
4114
4115 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4116 /// all the same.
4117 static bool isSplatVector(SDNode *N) {
4118   if (N->getOpcode() != ISD::BUILD_VECTOR)
4119     return false;
4120
4121   SDValue SplatValue = N->getOperand(0);
4122   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4123     if (N->getOperand(i) != SplatValue)
4124       return false;
4125   return true;
4126 }
4127
4128 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4129 /// to an zero vector.
4130 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4131 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4132   SDValue V1 = N->getOperand(0);
4133   SDValue V2 = N->getOperand(1);
4134   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4135   for (unsigned i = 0; i != NumElems; ++i) {
4136     int Idx = N->getMaskElt(i);
4137     if (Idx >= (int)NumElems) {
4138       unsigned Opc = V2.getOpcode();
4139       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4140         continue;
4141       if (Opc != ISD::BUILD_VECTOR ||
4142           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4143         return false;
4144     } else if (Idx >= 0) {
4145       unsigned Opc = V1.getOpcode();
4146       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4147         continue;
4148       if (Opc != ISD::BUILD_VECTOR ||
4149           !X86::isZeroNode(V1.getOperand(Idx)))
4150         return false;
4151     }
4152   }
4153   return true;
4154 }
4155
4156 /// getZeroVector - Returns a vector of specified type with all zero elements.
4157 ///
4158 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4159                              SelectionDAG &DAG, DebugLoc dl) {
4160   assert(VT.isVector() && "Expected a vector type");
4161   unsigned Size = VT.getSizeInBits();
4162
4163   // Always build SSE zero vectors as <4 x i32> bitcasted
4164   // to their dest type. This ensures they get CSE'd.
4165   SDValue Vec;
4166   if (Size == 128) {  // SSE
4167     if (Subtarget->hasSSE2()) {  // SSE2
4168       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4169       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4170     } else { // SSE1
4171       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4172       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4173     }
4174   } else if (Size == 256) { // AVX
4175     if (Subtarget->hasAVX2()) { // AVX2
4176       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4177       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4178       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4179     } else {
4180       // 256-bit logic and arithmetic instructions in AVX are all
4181       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4182       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4183       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4184       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4185     }
4186   } else
4187     llvm_unreachable("Unexpected vector type");
4188
4189   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4190 }
4191
4192 /// getOnesVector - Returns a vector of specified type with all bits set.
4193 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4194 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4195 /// Then bitcast to their original type, ensuring they get CSE'd.
4196 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4197                              DebugLoc dl) {
4198   assert(VT.isVector() && "Expected a vector type");
4199   unsigned Size = VT.getSizeInBits();
4200
4201   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4202   SDValue Vec;
4203   if (Size == 256) {
4204     if (HasAVX2) { // AVX2
4205       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4206       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4207     } else { // AVX
4208       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4209       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4210     }
4211   } else if (Size == 128) {
4212     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4213   } else
4214     llvm_unreachable("Unexpected vector type");
4215
4216   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4217 }
4218
4219 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4220 /// that point to V2 points to its first element.
4221 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4222   for (unsigned i = 0; i != NumElems; ++i) {
4223     if (Mask[i] > (int)NumElems) {
4224       Mask[i] = NumElems;
4225     }
4226   }
4227 }
4228
4229 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4230 /// operation of specified width.
4231 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4232                        SDValue V2) {
4233   unsigned NumElems = VT.getVectorNumElements();
4234   SmallVector<int, 8> Mask;
4235   Mask.push_back(NumElems);
4236   for (unsigned i = 1; i != NumElems; ++i)
4237     Mask.push_back(i);
4238   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4239 }
4240
4241 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4242 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4243                           SDValue V2) {
4244   unsigned NumElems = VT.getVectorNumElements();
4245   SmallVector<int, 8> Mask;
4246   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4247     Mask.push_back(i);
4248     Mask.push_back(i + NumElems);
4249   }
4250   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4251 }
4252
4253 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4254 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4255                           SDValue V2) {
4256   unsigned NumElems = VT.getVectorNumElements();
4257   unsigned Half = NumElems/2;
4258   SmallVector<int, 8> Mask;
4259   for (unsigned i = 0; i != Half; ++i) {
4260     Mask.push_back(i + Half);
4261     Mask.push_back(i + NumElems + Half);
4262   }
4263   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4264 }
4265
4266 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4267 // a generic shuffle instruction because the target has no such instructions.
4268 // Generate shuffles which repeat i16 and i8 several times until they can be
4269 // represented by v4f32 and then be manipulated by target suported shuffles.
4270 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4271   EVT VT = V.getValueType();
4272   int NumElems = VT.getVectorNumElements();
4273   DebugLoc dl = V.getDebugLoc();
4274
4275   while (NumElems > 4) {
4276     if (EltNo < NumElems/2) {
4277       V = getUnpackl(DAG, dl, VT, V, V);
4278     } else {
4279       V = getUnpackh(DAG, dl, VT, V, V);
4280       EltNo -= NumElems/2;
4281     }
4282     NumElems >>= 1;
4283   }
4284   return V;
4285 }
4286
4287 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4288 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4289   EVT VT = V.getValueType();
4290   DebugLoc dl = V.getDebugLoc();
4291   unsigned Size = VT.getSizeInBits();
4292
4293   if (Size == 128) {
4294     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4295     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4296     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4297                              &SplatMask[0]);
4298   } else if (Size == 256) {
4299     // To use VPERMILPS to splat scalars, the second half of indicies must
4300     // refer to the higher part, which is a duplication of the lower one,
4301     // because VPERMILPS can only handle in-lane permutations.
4302     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4303                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4304
4305     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4306     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4307                              &SplatMask[0]);
4308   } else
4309     llvm_unreachable("Vector size not supported");
4310
4311   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4312 }
4313
4314 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4315 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4316   EVT SrcVT = SV->getValueType(0);
4317   SDValue V1 = SV->getOperand(0);
4318   DebugLoc dl = SV->getDebugLoc();
4319
4320   int EltNo = SV->getSplatIndex();
4321   int NumElems = SrcVT.getVectorNumElements();
4322   unsigned Size = SrcVT.getSizeInBits();
4323
4324   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4325           "Unknown how to promote splat for type");
4326
4327   // Extract the 128-bit part containing the splat element and update
4328   // the splat element index when it refers to the higher register.
4329   if (Size == 256) {
4330     unsigned Idx = (EltNo >= NumElems/2) ? NumElems/2 : 0;
4331     V1 = Extract128BitVector(V1, Idx, DAG, dl);
4332     if (Idx > 0)
4333       EltNo -= NumElems/2;
4334   }
4335
4336   // All i16 and i8 vector types can't be used directly by a generic shuffle
4337   // instruction because the target has no such instruction. Generate shuffles
4338   // which repeat i16 and i8 several times until they fit in i32, and then can
4339   // be manipulated by target suported shuffles.
4340   EVT EltVT = SrcVT.getVectorElementType();
4341   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4342     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4343
4344   // Recreate the 256-bit vector and place the same 128-bit vector
4345   // into the low and high part. This is necessary because we want
4346   // to use VPERM* to shuffle the vectors
4347   if (Size == 256) {
4348     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4349   }
4350
4351   return getLegalSplat(DAG, V1, EltNo);
4352 }
4353
4354 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4355 /// vector of zero or undef vector.  This produces a shuffle where the low
4356 /// element of V2 is swizzled into the zero/undef vector, landing at element
4357 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4358 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4359                                            bool IsZero,
4360                                            const X86Subtarget *Subtarget,
4361                                            SelectionDAG &DAG) {
4362   EVT VT = V2.getValueType();
4363   SDValue V1 = IsZero
4364     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4365   unsigned NumElems = VT.getVectorNumElements();
4366   SmallVector<int, 16> MaskVec;
4367   for (unsigned i = 0; i != NumElems; ++i)
4368     // If this is the insertion idx, put the low elt of V2 here.
4369     MaskVec.push_back(i == Idx ? NumElems : i);
4370   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4371 }
4372
4373 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4374 /// target specific opcode. Returns true if the Mask could be calculated.
4375 /// Sets IsUnary to true if only uses one source.
4376 static bool getTargetShuffleMask(SDNode *N, EVT VT,
4377                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4378   unsigned NumElems = VT.getVectorNumElements();
4379   SDValue ImmN;
4380
4381   IsUnary = false;
4382   switch(N->getOpcode()) {
4383   case X86ISD::SHUFP:
4384     ImmN = N->getOperand(N->getNumOperands()-1);
4385     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4386     break;
4387   case X86ISD::UNPCKH:
4388     DecodeUNPCKHMask(VT, Mask);
4389     break;
4390   case X86ISD::UNPCKL:
4391     DecodeUNPCKLMask(VT, Mask);
4392     break;
4393   case X86ISD::MOVHLPS:
4394     DecodeMOVHLPSMask(NumElems, Mask);
4395     break;
4396   case X86ISD::MOVLHPS:
4397     DecodeMOVLHPSMask(NumElems, Mask);
4398     break;
4399   case X86ISD::PSHUFD:
4400   case X86ISD::VPERMILP:
4401     ImmN = N->getOperand(N->getNumOperands()-1);
4402     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4403     IsUnary = true;
4404     break;
4405   case X86ISD::PSHUFHW:
4406     ImmN = N->getOperand(N->getNumOperands()-1);
4407     DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4408     IsUnary = true;
4409     break;
4410   case X86ISD::PSHUFLW:
4411     ImmN = N->getOperand(N->getNumOperands()-1);
4412     DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4413     IsUnary = true;
4414     break;
4415   case X86ISD::MOVSS:
4416   case X86ISD::MOVSD: {
4417     // The index 0 always comes from the first element of the second source,
4418     // this is why MOVSS and MOVSD are used in the first place. The other
4419     // elements come from the other positions of the first source vector
4420     Mask.push_back(NumElems);
4421     for (unsigned i = 1; i != NumElems; ++i) {
4422       Mask.push_back(i);
4423     }
4424     break;
4425   }
4426   case X86ISD::VPERM2X128:
4427     ImmN = N->getOperand(N->getNumOperands()-1);
4428     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4429     if (Mask.empty()) return false;
4430     break;
4431   case X86ISD::MOVDDUP:
4432   case X86ISD::MOVLHPD:
4433   case X86ISD::MOVLPD:
4434   case X86ISD::MOVLPS:
4435   case X86ISD::MOVSHDUP:
4436   case X86ISD::MOVSLDUP:
4437   case X86ISD::PALIGN:
4438     // Not yet implemented
4439     return false;
4440   default: llvm_unreachable("unknown target shuffle node");
4441   }
4442
4443   return true;
4444 }
4445
4446 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4447 /// element of the result of the vector shuffle.
4448 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4449                                    unsigned Depth) {
4450   if (Depth == 6)
4451     return SDValue();  // Limit search depth.
4452
4453   SDValue V = SDValue(N, 0);
4454   EVT VT = V.getValueType();
4455   unsigned Opcode = V.getOpcode();
4456
4457   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4458   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4459     int Elt = SV->getMaskElt(Index);
4460
4461     if (Elt < 0)
4462       return DAG.getUNDEF(VT.getVectorElementType());
4463
4464     unsigned NumElems = VT.getVectorNumElements();
4465     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4466                                          : SV->getOperand(1);
4467     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4468   }
4469
4470   // Recurse into target specific vector shuffles to find scalars.
4471   if (isTargetShuffle(Opcode)) {
4472     unsigned NumElems = VT.getVectorNumElements();
4473     SmallVector<int, 16> ShuffleMask;
4474     SDValue ImmN;
4475     bool IsUnary;
4476
4477     if (!getTargetShuffleMask(N, VT, ShuffleMask, IsUnary))
4478       return SDValue();
4479
4480     int Elt = ShuffleMask[Index];
4481     if (Elt < 0)
4482       return DAG.getUNDEF(VT.getVectorElementType());
4483
4484     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4485                                            : N->getOperand(1);
4486     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4487                                Depth+1);
4488   }
4489
4490   // Actual nodes that may contain scalar elements
4491   if (Opcode == ISD::BITCAST) {
4492     V = V.getOperand(0);
4493     EVT SrcVT = V.getValueType();
4494     unsigned NumElems = VT.getVectorNumElements();
4495
4496     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4497       return SDValue();
4498   }
4499
4500   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4501     return (Index == 0) ? V.getOperand(0)
4502                         : DAG.getUNDEF(VT.getVectorElementType());
4503
4504   if (V.getOpcode() == ISD::BUILD_VECTOR)
4505     return V.getOperand(Index);
4506
4507   return SDValue();
4508 }
4509
4510 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4511 /// shuffle operation which come from a consecutively from a zero. The
4512 /// search can start in two different directions, from left or right.
4513 static
4514 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4515                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4516   unsigned i;
4517   for (i = 0; i != NumElems; ++i) {
4518     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4519     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4520     if (!(Elt.getNode() &&
4521          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4522       break;
4523   }
4524
4525   return i;
4526 }
4527
4528 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4529 /// correspond consecutively to elements from one of the vector operands,
4530 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4531 static
4532 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4533                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4534                               unsigned NumElems, unsigned &OpNum) {
4535   bool SeenV1 = false;
4536   bool SeenV2 = false;
4537
4538   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4539     int Idx = SVOp->getMaskElt(i);
4540     // Ignore undef indicies
4541     if (Idx < 0)
4542       continue;
4543
4544     if (Idx < (int)NumElems)
4545       SeenV1 = true;
4546     else
4547       SeenV2 = true;
4548
4549     // Only accept consecutive elements from the same vector
4550     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4551       return false;
4552   }
4553
4554   OpNum = SeenV1 ? 0 : 1;
4555   return true;
4556 }
4557
4558 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4559 /// logical left shift of a vector.
4560 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4561                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4562   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4563   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4564               false /* check zeros from right */, DAG);
4565   unsigned OpSrc;
4566
4567   if (!NumZeros)
4568     return false;
4569
4570   // Considering the elements in the mask that are not consecutive zeros,
4571   // check if they consecutively come from only one of the source vectors.
4572   //
4573   //               V1 = {X, A, B, C}     0
4574   //                         \  \  \    /
4575   //   vector_shuffle V1, V2 <1, 2, 3, X>
4576   //
4577   if (!isShuffleMaskConsecutive(SVOp,
4578             0,                   // Mask Start Index
4579             NumElems-NumZeros,   // Mask End Index(exclusive)
4580             NumZeros,            // Where to start looking in the src vector
4581             NumElems,            // Number of elements in vector
4582             OpSrc))              // Which source operand ?
4583     return false;
4584
4585   isLeft = false;
4586   ShAmt = NumZeros;
4587   ShVal = SVOp->getOperand(OpSrc);
4588   return true;
4589 }
4590
4591 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4592 /// logical left shift of a vector.
4593 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4594                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4595   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4596   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4597               true /* check zeros from left */, DAG);
4598   unsigned OpSrc;
4599
4600   if (!NumZeros)
4601     return false;
4602
4603   // Considering the elements in the mask that are not consecutive zeros,
4604   // check if they consecutively come from only one of the source vectors.
4605   //
4606   //                           0    { A, B, X, X } = V2
4607   //                          / \    /  /
4608   //   vector_shuffle V1, V2 <X, X, 4, 5>
4609   //
4610   if (!isShuffleMaskConsecutive(SVOp,
4611             NumZeros,     // Mask Start Index
4612             NumElems,     // Mask End Index(exclusive)
4613             0,            // Where to start looking in the src vector
4614             NumElems,     // Number of elements in vector
4615             OpSrc))       // Which source operand ?
4616     return false;
4617
4618   isLeft = true;
4619   ShAmt = NumZeros;
4620   ShVal = SVOp->getOperand(OpSrc);
4621   return true;
4622 }
4623
4624 /// isVectorShift - Returns true if the shuffle can be implemented as a
4625 /// logical left or right shift of a vector.
4626 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4627                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4628   // Although the logic below support any bitwidth size, there are no
4629   // shift instructions which handle more than 128-bit vectors.
4630   if (SVOp->getValueType(0).getSizeInBits() > 128)
4631     return false;
4632
4633   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4634       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4635     return true;
4636
4637   return false;
4638 }
4639
4640 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4641 ///
4642 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4643                                        unsigned NumNonZero, unsigned NumZero,
4644                                        SelectionDAG &DAG,
4645                                        const X86Subtarget* Subtarget,
4646                                        const TargetLowering &TLI) {
4647   if (NumNonZero > 8)
4648     return SDValue();
4649
4650   DebugLoc dl = Op.getDebugLoc();
4651   SDValue V(0, 0);
4652   bool First = true;
4653   for (unsigned i = 0; i < 16; ++i) {
4654     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4655     if (ThisIsNonZero && First) {
4656       if (NumZero)
4657         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4658       else
4659         V = DAG.getUNDEF(MVT::v8i16);
4660       First = false;
4661     }
4662
4663     if ((i & 1) != 0) {
4664       SDValue ThisElt(0, 0), LastElt(0, 0);
4665       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4666       if (LastIsNonZero) {
4667         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4668                               MVT::i16, Op.getOperand(i-1));
4669       }
4670       if (ThisIsNonZero) {
4671         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4672         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4673                               ThisElt, DAG.getConstant(8, MVT::i8));
4674         if (LastIsNonZero)
4675           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4676       } else
4677         ThisElt = LastElt;
4678
4679       if (ThisElt.getNode())
4680         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4681                         DAG.getIntPtrConstant(i/2));
4682     }
4683   }
4684
4685   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4686 }
4687
4688 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4689 ///
4690 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4691                                      unsigned NumNonZero, unsigned NumZero,
4692                                      SelectionDAG &DAG,
4693                                      const X86Subtarget* Subtarget,
4694                                      const TargetLowering &TLI) {
4695   if (NumNonZero > 4)
4696     return SDValue();
4697
4698   DebugLoc dl = Op.getDebugLoc();
4699   SDValue V(0, 0);
4700   bool First = true;
4701   for (unsigned i = 0; i < 8; ++i) {
4702     bool isNonZero = (NonZeros & (1 << i)) != 0;
4703     if (isNonZero) {
4704       if (First) {
4705         if (NumZero)
4706           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4707         else
4708           V = DAG.getUNDEF(MVT::v8i16);
4709         First = false;
4710       }
4711       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4712                       MVT::v8i16, V, Op.getOperand(i),
4713                       DAG.getIntPtrConstant(i));
4714     }
4715   }
4716
4717   return V;
4718 }
4719
4720 /// getVShift - Return a vector logical shift node.
4721 ///
4722 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4723                          unsigned NumBits, SelectionDAG &DAG,
4724                          const TargetLowering &TLI, DebugLoc dl) {
4725   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4726   EVT ShVT = MVT::v2i64;
4727   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4728   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4729   return DAG.getNode(ISD::BITCAST, dl, VT,
4730                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4731                              DAG.getConstant(NumBits,
4732                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4733 }
4734
4735 SDValue
4736 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4737                                           SelectionDAG &DAG) const {
4738
4739   // Check if the scalar load can be widened into a vector load. And if
4740   // the address is "base + cst" see if the cst can be "absorbed" into
4741   // the shuffle mask.
4742   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4743     SDValue Ptr = LD->getBasePtr();
4744     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4745       return SDValue();
4746     EVT PVT = LD->getValueType(0);
4747     if (PVT != MVT::i32 && PVT != MVT::f32)
4748       return SDValue();
4749
4750     int FI = -1;
4751     int64_t Offset = 0;
4752     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4753       FI = FINode->getIndex();
4754       Offset = 0;
4755     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4756                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4757       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4758       Offset = Ptr.getConstantOperandVal(1);
4759       Ptr = Ptr.getOperand(0);
4760     } else {
4761       return SDValue();
4762     }
4763
4764     // FIXME: 256-bit vector instructions don't require a strict alignment,
4765     // improve this code to support it better.
4766     unsigned RequiredAlign = VT.getSizeInBits()/8;
4767     SDValue Chain = LD->getChain();
4768     // Make sure the stack object alignment is at least 16 or 32.
4769     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4770     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4771       if (MFI->isFixedObjectIndex(FI)) {
4772         // Can't change the alignment. FIXME: It's possible to compute
4773         // the exact stack offset and reference FI + adjust offset instead.
4774         // If someone *really* cares about this. That's the way to implement it.
4775         return SDValue();
4776       } else {
4777         MFI->setObjectAlignment(FI, RequiredAlign);
4778       }
4779     }
4780
4781     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4782     // Ptr + (Offset & ~15).
4783     if (Offset < 0)
4784       return SDValue();
4785     if ((Offset % RequiredAlign) & 3)
4786       return SDValue();
4787     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4788     if (StartOffset)
4789       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4790                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4791
4792     int EltNo = (Offset - StartOffset) >> 2;
4793     int NumElems = VT.getVectorNumElements();
4794
4795     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4796     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4797                              LD->getPointerInfo().getWithOffset(StartOffset),
4798                              false, false, false, 0);
4799
4800     SmallVector<int, 8> Mask;
4801     for (int i = 0; i < NumElems; ++i)
4802       Mask.push_back(EltNo);
4803
4804     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4805   }
4806
4807   return SDValue();
4808 }
4809
4810 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4811 /// vector of type 'VT', see if the elements can be replaced by a single large
4812 /// load which has the same value as a build_vector whose operands are 'elts'.
4813 ///
4814 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4815 ///
4816 /// FIXME: we'd also like to handle the case where the last elements are zero
4817 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4818 /// There's even a handy isZeroNode for that purpose.
4819 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4820                                         DebugLoc &DL, SelectionDAG &DAG) {
4821   EVT EltVT = VT.getVectorElementType();
4822   unsigned NumElems = Elts.size();
4823
4824   LoadSDNode *LDBase = NULL;
4825   unsigned LastLoadedElt = -1U;
4826
4827   // For each element in the initializer, see if we've found a load or an undef.
4828   // If we don't find an initial load element, or later load elements are
4829   // non-consecutive, bail out.
4830   for (unsigned i = 0; i < NumElems; ++i) {
4831     SDValue Elt = Elts[i];
4832
4833     if (!Elt.getNode() ||
4834         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4835       return SDValue();
4836     if (!LDBase) {
4837       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4838         return SDValue();
4839       LDBase = cast<LoadSDNode>(Elt.getNode());
4840       LastLoadedElt = i;
4841       continue;
4842     }
4843     if (Elt.getOpcode() == ISD::UNDEF)
4844       continue;
4845
4846     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4847     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4848       return SDValue();
4849     LastLoadedElt = i;
4850   }
4851
4852   // If we have found an entire vector of loads and undefs, then return a large
4853   // load of the entire vector width starting at the base pointer.  If we found
4854   // consecutive loads for the low half, generate a vzext_load node.
4855   if (LastLoadedElt == NumElems - 1) {
4856     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4857       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4858                          LDBase->getPointerInfo(),
4859                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4860                          LDBase->isInvariant(), 0);
4861     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4862                        LDBase->getPointerInfo(),
4863                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4864                        LDBase->isInvariant(), LDBase->getAlignment());
4865   }
4866   if (NumElems == 4 && LastLoadedElt == 1 &&
4867       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4868     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4869     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4870     SDValue ResNode =
4871         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4872                                 LDBase->getPointerInfo(),
4873                                 LDBase->getAlignment(),
4874                                 false/*isVolatile*/, true/*ReadMem*/,
4875                                 false/*WriteMem*/);
4876     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4877   }
4878   return SDValue();
4879 }
4880
4881 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4882 /// to generate a splat value for the following cases:
4883 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4884 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4885 /// a scalar load, or a constant.
4886 /// The VBROADCAST node is returned when a pattern is found,
4887 /// or SDValue() otherwise.
4888 SDValue
4889 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4890   if (!Subtarget->hasAVX())
4891     return SDValue();
4892
4893   EVT VT = Op.getValueType();
4894   DebugLoc dl = Op.getDebugLoc();
4895
4896   SDValue Ld;
4897   bool ConstSplatVal;
4898
4899   switch (Op.getOpcode()) {
4900     default:
4901       // Unknown pattern found.
4902       return SDValue();
4903
4904     case ISD::BUILD_VECTOR: {
4905       // The BUILD_VECTOR node must be a splat.
4906       if (!isSplatVector(Op.getNode()))
4907         return SDValue();
4908
4909       Ld = Op.getOperand(0);
4910       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4911                      Ld.getOpcode() == ISD::ConstantFP);
4912
4913       // The suspected load node has several users. Make sure that all
4914       // of its users are from the BUILD_VECTOR node.
4915       // Constants may have multiple users.
4916       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4917         return SDValue();
4918       break;
4919     }
4920
4921     case ISD::VECTOR_SHUFFLE: {
4922       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4923
4924       // Shuffles must have a splat mask where the first element is
4925       // broadcasted.
4926       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4927         return SDValue();
4928
4929       SDValue Sc = Op.getOperand(0);
4930       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4931         return SDValue();
4932
4933       Ld = Sc.getOperand(0);
4934       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4935                        Ld.getOpcode() == ISD::ConstantFP);
4936
4937       // The scalar_to_vector node and the suspected
4938       // load node must have exactly one user.
4939       // Constants may have multiple users.
4940       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
4941         return SDValue();
4942       break;
4943     }
4944   }
4945
4946   bool Is256 = VT.getSizeInBits() == 256;
4947   bool Is128 = VT.getSizeInBits() == 128;
4948
4949   // Handle the broadcasting a single constant scalar from the constant pool
4950   // into a vector. On Sandybridge it is still better to load a constant vector
4951   // from the constant pool and not to broadcast it from a scalar.
4952   if (ConstSplatVal && Subtarget->hasAVX2()) {
4953     EVT CVT = Ld.getValueType();
4954     assert(!CVT.isVector() && "Must not broadcast a vector type");
4955     unsigned ScalarSize = CVT.getSizeInBits();
4956
4957     if ((Is256 && (ScalarSize == 32 || ScalarSize == 64)) ||
4958         (Is128 && (ScalarSize == 32))) {
4959
4960       const Constant *C = 0;
4961       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4962         C = CI->getConstantIntValue();
4963       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4964         C = CF->getConstantFPValue();
4965
4966       assert(C && "Invalid constant type");
4967
4968       SDValue CP = DAG.getConstantPool(C, getPointerTy());
4969       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4970       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4971                          MachinePointerInfo::getConstantPool(),
4972                          false, false, false, Alignment);
4973
4974       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4975     }
4976   }
4977
4978   // The scalar source must be a normal load.
4979   if (!ISD::isNormalLoad(Ld.getNode()))
4980     return SDValue();
4981
4982   // Reject loads that have uses of the chain result
4983   if (Ld->hasAnyUseOfValue(1))
4984     return SDValue();
4985
4986   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4987
4988   // VBroadcast to YMM
4989   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
4990     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4991
4992   // VBroadcast to XMM
4993   if (Is128 && (ScalarSize == 32))
4994     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4995
4996   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4997   // double since there is vbroadcastsd xmm
4998   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
4999     // VBroadcast to YMM
5000     if (Is256 && (ScalarSize == 8 || ScalarSize == 16))
5001       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5002
5003     // VBroadcast to XMM
5004     if (Is128 && (ScalarSize ==  8 || ScalarSize == 16 || ScalarSize == 64))
5005       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5006   }
5007
5008   // Unsupported broadcast.
5009   return SDValue();
5010 }
5011
5012 SDValue
5013 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5014   DebugLoc dl = Op.getDebugLoc();
5015
5016   EVT VT = Op.getValueType();
5017   EVT ExtVT = VT.getVectorElementType();
5018   unsigned NumElems = Op.getNumOperands();
5019
5020   // Vectors containing all zeros can be matched by pxor and xorps later
5021   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5022     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5023     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5024     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5025       return Op;
5026
5027     return getZeroVector(VT, Subtarget, DAG, dl);
5028   }
5029
5030   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5031   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5032   // vpcmpeqd on 256-bit vectors.
5033   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5034     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5035       return Op;
5036
5037     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5038   }
5039
5040   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5041   if (Broadcast.getNode())
5042     return Broadcast;
5043
5044   unsigned EVTBits = ExtVT.getSizeInBits();
5045
5046   unsigned NumZero  = 0;
5047   unsigned NumNonZero = 0;
5048   unsigned NonZeros = 0;
5049   bool IsAllConstants = true;
5050   SmallSet<SDValue, 8> Values;
5051   for (unsigned i = 0; i < NumElems; ++i) {
5052     SDValue Elt = Op.getOperand(i);
5053     if (Elt.getOpcode() == ISD::UNDEF)
5054       continue;
5055     Values.insert(Elt);
5056     if (Elt.getOpcode() != ISD::Constant &&
5057         Elt.getOpcode() != ISD::ConstantFP)
5058       IsAllConstants = false;
5059     if (X86::isZeroNode(Elt))
5060       NumZero++;
5061     else {
5062       NonZeros |= (1 << i);
5063       NumNonZero++;
5064     }
5065   }
5066
5067   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5068   if (NumNonZero == 0)
5069     return DAG.getUNDEF(VT);
5070
5071   // Special case for single non-zero, non-undef, element.
5072   if (NumNonZero == 1) {
5073     unsigned Idx = CountTrailingZeros_32(NonZeros);
5074     SDValue Item = Op.getOperand(Idx);
5075
5076     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5077     // the value are obviously zero, truncate the value to i32 and do the
5078     // insertion that way.  Only do this if the value is non-constant or if the
5079     // value is a constant being inserted into element 0.  It is cheaper to do
5080     // a constant pool load than it is to do a movd + shuffle.
5081     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5082         (!IsAllConstants || Idx == 0)) {
5083       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5084         // Handle SSE only.
5085         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5086         EVT VecVT = MVT::v4i32;
5087         unsigned VecElts = 4;
5088
5089         // Truncate the value (which may itself be a constant) to i32, and
5090         // convert it to a vector with movd (S2V+shuffle to zero extend).
5091         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5092         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5093         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5094
5095         // Now we have our 32-bit value zero extended in the low element of
5096         // a vector.  If Idx != 0, swizzle it into place.
5097         if (Idx != 0) {
5098           SmallVector<int, 4> Mask;
5099           Mask.push_back(Idx);
5100           for (unsigned i = 1; i != VecElts; ++i)
5101             Mask.push_back(i);
5102           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5103                                       &Mask[0]);
5104         }
5105         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5106       }
5107     }
5108
5109     // If we have a constant or non-constant insertion into the low element of
5110     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5111     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5112     // depending on what the source datatype is.
5113     if (Idx == 0) {
5114       if (NumZero == 0)
5115         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5116
5117       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5118           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5119         if (VT.getSizeInBits() == 256) {
5120           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5121           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5122                              Item, DAG.getIntPtrConstant(0));
5123         }
5124         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5125         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5126         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5127         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5128       }
5129
5130       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5131         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5132         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5133         if (VT.getSizeInBits() == 256) {
5134           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5135           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5136         } else {
5137           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5138           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5139         }
5140         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5141       }
5142     }
5143
5144     // Is it a vector logical left shift?
5145     if (NumElems == 2 && Idx == 1 &&
5146         X86::isZeroNode(Op.getOperand(0)) &&
5147         !X86::isZeroNode(Op.getOperand(1))) {
5148       unsigned NumBits = VT.getSizeInBits();
5149       return getVShift(true, VT,
5150                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5151                                    VT, Op.getOperand(1)),
5152                        NumBits/2, DAG, *this, dl);
5153     }
5154
5155     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5156       return SDValue();
5157
5158     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5159     // is a non-constant being inserted into an element other than the low one,
5160     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5161     // movd/movss) to move this into the low element, then shuffle it into
5162     // place.
5163     if (EVTBits == 32) {
5164       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5165
5166       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5167       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5168       SmallVector<int, 8> MaskVec;
5169       for (unsigned i = 0; i < NumElems; i++)
5170         MaskVec.push_back(i == Idx ? 0 : 1);
5171       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5172     }
5173   }
5174
5175   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5176   if (Values.size() == 1) {
5177     if (EVTBits == 32) {
5178       // Instead of a shuffle like this:
5179       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5180       // Check if it's possible to issue this instead.
5181       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5182       unsigned Idx = CountTrailingZeros_32(NonZeros);
5183       SDValue Item = Op.getOperand(Idx);
5184       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5185         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5186     }
5187     return SDValue();
5188   }
5189
5190   // A vector full of immediates; various special cases are already
5191   // handled, so this is best done with a single constant-pool load.
5192   if (IsAllConstants)
5193     return SDValue();
5194
5195   // For AVX-length vectors, build the individual 128-bit pieces and use
5196   // shuffles to put them in place.
5197   if (VT.getSizeInBits() == 256) {
5198     SmallVector<SDValue, 32> V;
5199     for (unsigned i = 0; i != NumElems; ++i)
5200       V.push_back(Op.getOperand(i));
5201
5202     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5203
5204     // Build both the lower and upper subvector.
5205     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5206     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5207                                 NumElems/2);
5208
5209     // Recreate the wider vector with the lower and upper part.
5210     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5211   }
5212
5213   // Let legalizer expand 2-wide build_vectors.
5214   if (EVTBits == 64) {
5215     if (NumNonZero == 1) {
5216       // One half is zero or undef.
5217       unsigned Idx = CountTrailingZeros_32(NonZeros);
5218       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5219                                  Op.getOperand(Idx));
5220       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5221     }
5222     return SDValue();
5223   }
5224
5225   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5226   if (EVTBits == 8 && NumElems == 16) {
5227     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5228                                         Subtarget, *this);
5229     if (V.getNode()) return V;
5230   }
5231
5232   if (EVTBits == 16 && NumElems == 8) {
5233     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5234                                       Subtarget, *this);
5235     if (V.getNode()) return V;
5236   }
5237
5238   // If element VT is == 32 bits, turn it into a number of shuffles.
5239   SmallVector<SDValue, 8> V(NumElems);
5240   if (NumElems == 4 && NumZero > 0) {
5241     for (unsigned i = 0; i < 4; ++i) {
5242       bool isZero = !(NonZeros & (1 << i));
5243       if (isZero)
5244         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5245       else
5246         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5247     }
5248
5249     for (unsigned i = 0; i < 2; ++i) {
5250       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5251         default: break;
5252         case 0:
5253           V[i] = V[i*2];  // Must be a zero vector.
5254           break;
5255         case 1:
5256           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5257           break;
5258         case 2:
5259           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5260           break;
5261         case 3:
5262           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5263           break;
5264       }
5265     }
5266
5267     bool Reverse1 = (NonZeros & 0x3) == 2;
5268     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5269     int MaskVec[] = {
5270       Reverse1 ? 1 : 0,
5271       Reverse1 ? 0 : 1,
5272       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5273       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5274     };
5275     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5276   }
5277
5278   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5279     // Check for a build vector of consecutive loads.
5280     for (unsigned i = 0; i < NumElems; ++i)
5281       V[i] = Op.getOperand(i);
5282
5283     // Check for elements which are consecutive loads.
5284     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5285     if (LD.getNode())
5286       return LD;
5287
5288     // For SSE 4.1, use insertps to put the high elements into the low element.
5289     if (getSubtarget()->hasSSE41()) {
5290       SDValue Result;
5291       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5292         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5293       else
5294         Result = DAG.getUNDEF(VT);
5295
5296       for (unsigned i = 1; i < NumElems; ++i) {
5297         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5298         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5299                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5300       }
5301       return Result;
5302     }
5303
5304     // Otherwise, expand into a number of unpckl*, start by extending each of
5305     // our (non-undef) elements to the full vector width with the element in the
5306     // bottom slot of the vector (which generates no code for SSE).
5307     for (unsigned i = 0; i < NumElems; ++i) {
5308       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5309         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5310       else
5311         V[i] = DAG.getUNDEF(VT);
5312     }
5313
5314     // Next, we iteratively mix elements, e.g. for v4f32:
5315     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5316     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5317     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5318     unsigned EltStride = NumElems >> 1;
5319     while (EltStride != 0) {
5320       for (unsigned i = 0; i < EltStride; ++i) {
5321         // If V[i+EltStride] is undef and this is the first round of mixing,
5322         // then it is safe to just drop this shuffle: V[i] is already in the
5323         // right place, the one element (since it's the first round) being
5324         // inserted as undef can be dropped.  This isn't safe for successive
5325         // rounds because they will permute elements within both vectors.
5326         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5327             EltStride == NumElems/2)
5328           continue;
5329
5330         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5331       }
5332       EltStride >>= 1;
5333     }
5334     return V[0];
5335   }
5336   return SDValue();
5337 }
5338
5339 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5340 // them in a MMX register.  This is better than doing a stack convert.
5341 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5342   DebugLoc dl = Op.getDebugLoc();
5343   EVT ResVT = Op.getValueType();
5344
5345   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5346          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5347   int Mask[2];
5348   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5349   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5350   InVec = Op.getOperand(1);
5351   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5352     unsigned NumElts = ResVT.getVectorNumElements();
5353     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5354     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5355                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5356   } else {
5357     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5358     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5359     Mask[0] = 0; Mask[1] = 2;
5360     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5361   }
5362   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5363 }
5364
5365 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5366 // to create 256-bit vectors from two other 128-bit ones.
5367 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5368   DebugLoc dl = Op.getDebugLoc();
5369   EVT ResVT = Op.getValueType();
5370
5371   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5372
5373   SDValue V1 = Op.getOperand(0);
5374   SDValue V2 = Op.getOperand(1);
5375   unsigned NumElems = ResVT.getVectorNumElements();
5376
5377   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5378 }
5379
5380 SDValue
5381 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5382   EVT ResVT = Op.getValueType();
5383
5384   assert(Op.getNumOperands() == 2);
5385   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5386          "Unsupported CONCAT_VECTORS for value type");
5387
5388   // We support concatenate two MMX registers and place them in a MMX register.
5389   // This is better than doing a stack convert.
5390   if (ResVT.is128BitVector())
5391     return LowerMMXCONCAT_VECTORS(Op, DAG);
5392
5393   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5394   // from two other 128-bit ones.
5395   return LowerAVXCONCAT_VECTORS(Op, DAG);
5396 }
5397
5398 // Try to lower a shuffle node into a simple blend instruction.
5399 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5400                                           const X86Subtarget *Subtarget,
5401                                           SelectionDAG &DAG) {
5402   SDValue V1 = SVOp->getOperand(0);
5403   SDValue V2 = SVOp->getOperand(1);
5404   DebugLoc dl = SVOp->getDebugLoc();
5405   EVT VT = SVOp->getValueType(0);
5406   unsigned NumElems = VT.getVectorNumElements();
5407
5408   if (!Subtarget->hasSSE41())
5409     return SDValue();
5410
5411   unsigned ISDNo = 0;
5412   MVT OpTy;
5413
5414   switch (VT.getSimpleVT().SimpleTy) {
5415   default: return SDValue();
5416   case MVT::v8i16:
5417     ISDNo = X86ISD::BLENDPW;
5418     OpTy = MVT::v8i16;
5419     break;
5420   case MVT::v4i32:
5421   case MVT::v4f32:
5422     ISDNo = X86ISD::BLENDPS;
5423     OpTy = MVT::v4f32;
5424     break;
5425   case MVT::v2i64:
5426   case MVT::v2f64:
5427     ISDNo = X86ISD::BLENDPD;
5428     OpTy = MVT::v2f64;
5429     break;
5430   case MVT::v8i32:
5431   case MVT::v8f32:
5432     if (!Subtarget->hasAVX())
5433       return SDValue();
5434     ISDNo = X86ISD::BLENDPS;
5435     OpTy = MVT::v8f32;
5436     break;
5437   case MVT::v4i64:
5438   case MVT::v4f64:
5439     if (!Subtarget->hasAVX())
5440       return SDValue();
5441     ISDNo = X86ISD::BLENDPD;
5442     OpTy = MVT::v4f64;
5443     break;
5444   case MVT::v16i16:
5445     if (!Subtarget->hasAVX2())
5446       return SDValue();
5447     ISDNo = X86ISD::BLENDPW;
5448     OpTy = MVT::v16i16;
5449     break;
5450   }
5451   assert(ISDNo && "Invalid Op Number");
5452
5453   unsigned MaskVals = 0;
5454
5455   for (unsigned i = 0; i != NumElems; ++i) {
5456     int EltIdx = SVOp->getMaskElt(i);
5457     if (EltIdx == (int)i || EltIdx < 0)
5458       MaskVals |= (1<<i);
5459     else if (EltIdx == (int)(i + NumElems))
5460       continue; // Bit is set to zero;
5461     else
5462       return SDValue();
5463   }
5464
5465   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5466   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5467   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5468                              DAG.getConstant(MaskVals, MVT::i32));
5469   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5470 }
5471
5472 // v8i16 shuffles - Prefer shuffles in the following order:
5473 // 1. [all]   pshuflw, pshufhw, optional move
5474 // 2. [ssse3] 1 x pshufb
5475 // 3. [ssse3] 2 x pshufb + 1 x por
5476 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5477 SDValue
5478 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5479                                             SelectionDAG &DAG) const {
5480   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5481   SDValue V1 = SVOp->getOperand(0);
5482   SDValue V2 = SVOp->getOperand(1);
5483   DebugLoc dl = SVOp->getDebugLoc();
5484   SmallVector<int, 8> MaskVals;
5485
5486   // Determine if more than 1 of the words in each of the low and high quadwords
5487   // of the result come from the same quadword of one of the two inputs.  Undef
5488   // mask values count as coming from any quadword, for better codegen.
5489   unsigned LoQuad[] = { 0, 0, 0, 0 };
5490   unsigned HiQuad[] = { 0, 0, 0, 0 };
5491   std::bitset<4> InputQuads;
5492   for (unsigned i = 0; i < 8; ++i) {
5493     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5494     int EltIdx = SVOp->getMaskElt(i);
5495     MaskVals.push_back(EltIdx);
5496     if (EltIdx < 0) {
5497       ++Quad[0];
5498       ++Quad[1];
5499       ++Quad[2];
5500       ++Quad[3];
5501       continue;
5502     }
5503     ++Quad[EltIdx / 4];
5504     InputQuads.set(EltIdx / 4);
5505   }
5506
5507   int BestLoQuad = -1;
5508   unsigned MaxQuad = 1;
5509   for (unsigned i = 0; i < 4; ++i) {
5510     if (LoQuad[i] > MaxQuad) {
5511       BestLoQuad = i;
5512       MaxQuad = LoQuad[i];
5513     }
5514   }
5515
5516   int BestHiQuad = -1;
5517   MaxQuad = 1;
5518   for (unsigned i = 0; i < 4; ++i) {
5519     if (HiQuad[i] > MaxQuad) {
5520       BestHiQuad = i;
5521       MaxQuad = HiQuad[i];
5522     }
5523   }
5524
5525   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5526   // of the two input vectors, shuffle them into one input vector so only a
5527   // single pshufb instruction is necessary. If There are more than 2 input
5528   // quads, disable the next transformation since it does not help SSSE3.
5529   bool V1Used = InputQuads[0] || InputQuads[1];
5530   bool V2Used = InputQuads[2] || InputQuads[3];
5531   if (Subtarget->hasSSSE3()) {
5532     if (InputQuads.count() == 2 && V1Used && V2Used) {
5533       BestLoQuad = InputQuads[0] ? 0 : 1;
5534       BestHiQuad = InputQuads[2] ? 2 : 3;
5535     }
5536     if (InputQuads.count() > 2) {
5537       BestLoQuad = -1;
5538       BestHiQuad = -1;
5539     }
5540   }
5541
5542   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5543   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5544   // words from all 4 input quadwords.
5545   SDValue NewV;
5546   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5547     int MaskV[] = {
5548       BestLoQuad < 0 ? 0 : BestLoQuad,
5549       BestHiQuad < 0 ? 1 : BestHiQuad
5550     };
5551     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5552                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5553                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5554     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5555
5556     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5557     // source words for the shuffle, to aid later transformations.
5558     bool AllWordsInNewV = true;
5559     bool InOrder[2] = { true, true };
5560     for (unsigned i = 0; i != 8; ++i) {
5561       int idx = MaskVals[i];
5562       if (idx != (int)i)
5563         InOrder[i/4] = false;
5564       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5565         continue;
5566       AllWordsInNewV = false;
5567       break;
5568     }
5569
5570     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5571     if (AllWordsInNewV) {
5572       for (int i = 0; i != 8; ++i) {
5573         int idx = MaskVals[i];
5574         if (idx < 0)
5575           continue;
5576         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5577         if ((idx != i) && idx < 4)
5578           pshufhw = false;
5579         if ((idx != i) && idx > 3)
5580           pshuflw = false;
5581       }
5582       V1 = NewV;
5583       V2Used = false;
5584       BestLoQuad = 0;
5585       BestHiQuad = 1;
5586     }
5587
5588     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5589     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5590     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5591       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5592       unsigned TargetMask = 0;
5593       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5594                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5595       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5596       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5597                              getShufflePSHUFLWImmediate(SVOp);
5598       V1 = NewV.getOperand(0);
5599       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5600     }
5601   }
5602
5603   // If we have SSSE3, and all words of the result are from 1 input vector,
5604   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5605   // is present, fall back to case 4.
5606   if (Subtarget->hasSSSE3()) {
5607     SmallVector<SDValue,16> pshufbMask;
5608
5609     // If we have elements from both input vectors, set the high bit of the
5610     // shuffle mask element to zero out elements that come from V2 in the V1
5611     // mask, and elements that come from V1 in the V2 mask, so that the two
5612     // results can be OR'd together.
5613     bool TwoInputs = V1Used && V2Used;
5614     for (unsigned i = 0; i != 8; ++i) {
5615       int EltIdx = MaskVals[i] * 2;
5616       if (TwoInputs && (EltIdx >= 16)) {
5617         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5618         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5619         continue;
5620       }
5621       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5622       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5623     }
5624     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5625     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5626                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5627                                  MVT::v16i8, &pshufbMask[0], 16));
5628     if (!TwoInputs)
5629       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5630
5631     // Calculate the shuffle mask for the second input, shuffle it, and
5632     // OR it with the first shuffled input.
5633     pshufbMask.clear();
5634     for (unsigned i = 0; i != 8; ++i) {
5635       int EltIdx = MaskVals[i] * 2;
5636       if (EltIdx < 16) {
5637         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5638         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5639         continue;
5640       }
5641       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5642       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5643     }
5644     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5645     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5646                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5647                                  MVT::v16i8, &pshufbMask[0], 16));
5648     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5649     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5650   }
5651
5652   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5653   // and update MaskVals with new element order.
5654   std::bitset<8> InOrder;
5655   if (BestLoQuad >= 0) {
5656     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5657     for (int i = 0; i != 4; ++i) {
5658       int idx = MaskVals[i];
5659       if (idx < 0) {
5660         InOrder.set(i);
5661       } else if ((idx / 4) == BestLoQuad) {
5662         MaskV[i] = idx & 3;
5663         InOrder.set(i);
5664       }
5665     }
5666     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5667                                 &MaskV[0]);
5668
5669     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5670       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5671       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5672                                   NewV.getOperand(0),
5673                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5674     }
5675   }
5676
5677   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5678   // and update MaskVals with the new element order.
5679   if (BestHiQuad >= 0) {
5680     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5681     for (unsigned i = 4; i != 8; ++i) {
5682       int idx = MaskVals[i];
5683       if (idx < 0) {
5684         InOrder.set(i);
5685       } else if ((idx / 4) == BestHiQuad) {
5686         MaskV[i] = (idx & 3) + 4;
5687         InOrder.set(i);
5688       }
5689     }
5690     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5691                                 &MaskV[0]);
5692
5693     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5694       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5695       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5696                                   NewV.getOperand(0),
5697                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5698     }
5699   }
5700
5701   // In case BestHi & BestLo were both -1, which means each quadword has a word
5702   // from each of the four input quadwords, calculate the InOrder bitvector now
5703   // before falling through to the insert/extract cleanup.
5704   if (BestLoQuad == -1 && BestHiQuad == -1) {
5705     NewV = V1;
5706     for (int i = 0; i != 8; ++i)
5707       if (MaskVals[i] < 0 || MaskVals[i] == i)
5708         InOrder.set(i);
5709   }
5710
5711   // The other elements are put in the right place using pextrw and pinsrw.
5712   for (unsigned i = 0; i != 8; ++i) {
5713     if (InOrder[i])
5714       continue;
5715     int EltIdx = MaskVals[i];
5716     if (EltIdx < 0)
5717       continue;
5718     SDValue ExtOp = (EltIdx < 8)
5719     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5720                   DAG.getIntPtrConstant(EltIdx))
5721     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5722                   DAG.getIntPtrConstant(EltIdx - 8));
5723     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5724                        DAG.getIntPtrConstant(i));
5725   }
5726   return NewV;
5727 }
5728
5729 // v16i8 shuffles - Prefer shuffles in the following order:
5730 // 1. [ssse3] 1 x pshufb
5731 // 2. [ssse3] 2 x pshufb + 1 x por
5732 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5733 static
5734 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5735                                  SelectionDAG &DAG,
5736                                  const X86TargetLowering &TLI) {
5737   SDValue V1 = SVOp->getOperand(0);
5738   SDValue V2 = SVOp->getOperand(1);
5739   DebugLoc dl = SVOp->getDebugLoc();
5740   ArrayRef<int> MaskVals = SVOp->getMask();
5741
5742   // If we have SSSE3, case 1 is generated when all result bytes come from
5743   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5744   // present, fall back to case 3.
5745   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5746   bool V1Only = true;
5747   bool V2Only = true;
5748   for (unsigned i = 0; i < 16; ++i) {
5749     int EltIdx = MaskVals[i];
5750     if (EltIdx < 0)
5751       continue;
5752     if (EltIdx < 16)
5753       V2Only = false;
5754     else
5755       V1Only = false;
5756   }
5757
5758   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5759   if (TLI.getSubtarget()->hasSSSE3()) {
5760     SmallVector<SDValue,16> pshufbMask;
5761
5762     // If all result elements are from one input vector, then only translate
5763     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5764     //
5765     // Otherwise, we have elements from both input vectors, and must zero out
5766     // elements that come from V2 in the first mask, and V1 in the second mask
5767     // so that we can OR them together.
5768     bool TwoInputs = !(V1Only || V2Only);
5769     for (unsigned i = 0; i != 16; ++i) {
5770       int EltIdx = MaskVals[i];
5771       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5772         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5773         continue;
5774       }
5775       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5776     }
5777     // If all the elements are from V2, assign it to V1 and return after
5778     // building the first pshufb.
5779     if (V2Only)
5780       V1 = V2;
5781     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5782                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5783                                  MVT::v16i8, &pshufbMask[0], 16));
5784     if (!TwoInputs)
5785       return V1;
5786
5787     // Calculate the shuffle mask for the second input, shuffle it, and
5788     // OR it with the first shuffled input.
5789     pshufbMask.clear();
5790     for (unsigned i = 0; i != 16; ++i) {
5791       int EltIdx = MaskVals[i];
5792       if (EltIdx < 16) {
5793         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5794         continue;
5795       }
5796       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5797     }
5798     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5799                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5800                                  MVT::v16i8, &pshufbMask[0], 16));
5801     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5802   }
5803
5804   // No SSSE3 - Calculate in place words and then fix all out of place words
5805   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5806   // the 16 different words that comprise the two doublequadword input vectors.
5807   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5808   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5809   SDValue NewV = V2Only ? V2 : V1;
5810   for (int i = 0; i != 8; ++i) {
5811     int Elt0 = MaskVals[i*2];
5812     int Elt1 = MaskVals[i*2+1];
5813
5814     // This word of the result is all undef, skip it.
5815     if (Elt0 < 0 && Elt1 < 0)
5816       continue;
5817
5818     // This word of the result is already in the correct place, skip it.
5819     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5820       continue;
5821     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5822       continue;
5823
5824     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5825     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5826     SDValue InsElt;
5827
5828     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5829     // using a single extract together, load it and store it.
5830     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5831       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5832                            DAG.getIntPtrConstant(Elt1 / 2));
5833       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5834                         DAG.getIntPtrConstant(i));
5835       continue;
5836     }
5837
5838     // If Elt1 is defined, extract it from the appropriate source.  If the
5839     // source byte is not also odd, shift the extracted word left 8 bits
5840     // otherwise clear the bottom 8 bits if we need to do an or.
5841     if (Elt1 >= 0) {
5842       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5843                            DAG.getIntPtrConstant(Elt1 / 2));
5844       if ((Elt1 & 1) == 0)
5845         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5846                              DAG.getConstant(8,
5847                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5848       else if (Elt0 >= 0)
5849         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5850                              DAG.getConstant(0xFF00, MVT::i16));
5851     }
5852     // If Elt0 is defined, extract it from the appropriate source.  If the
5853     // source byte is not also even, shift the extracted word right 8 bits. If
5854     // Elt1 was also defined, OR the extracted values together before
5855     // inserting them in the result.
5856     if (Elt0 >= 0) {
5857       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5858                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5859       if ((Elt0 & 1) != 0)
5860         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5861                               DAG.getConstant(8,
5862                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5863       else if (Elt1 >= 0)
5864         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5865                              DAG.getConstant(0x00FF, MVT::i16));
5866       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5867                          : InsElt0;
5868     }
5869     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5870                        DAG.getIntPtrConstant(i));
5871   }
5872   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5873 }
5874
5875 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5876 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5877 /// done when every pair / quad of shuffle mask elements point to elements in
5878 /// the right sequence. e.g.
5879 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5880 static
5881 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5882                                  SelectionDAG &DAG, DebugLoc dl) {
5883   EVT VT = SVOp->getValueType(0);
5884   SDValue V1 = SVOp->getOperand(0);
5885   SDValue V2 = SVOp->getOperand(1);
5886   unsigned NumElems = VT.getVectorNumElements();
5887   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5888   EVT NewVT;
5889   switch (VT.getSimpleVT().SimpleTy) {
5890   default: llvm_unreachable("Unexpected!");
5891   case MVT::v4f32: NewVT = MVT::v2f64; break;
5892   case MVT::v4i32: NewVT = MVT::v2i64; break;
5893   case MVT::v8i16: NewVT = MVT::v4i32; break;
5894   case MVT::v16i8: NewVT = MVT::v4i32; break;
5895   }
5896
5897   int Scale = NumElems / NewWidth;
5898   SmallVector<int, 8> MaskVec;
5899   for (unsigned i = 0; i < NumElems; i += Scale) {
5900     int StartIdx = -1;
5901     for (int j = 0; j < Scale; ++j) {
5902       int EltIdx = SVOp->getMaskElt(i+j);
5903       if (EltIdx < 0)
5904         continue;
5905       if (StartIdx == -1)
5906         StartIdx = EltIdx - (EltIdx % Scale);
5907       if (EltIdx != StartIdx + j)
5908         return SDValue();
5909     }
5910     if (StartIdx == -1)
5911       MaskVec.push_back(-1);
5912     else
5913       MaskVec.push_back(StartIdx / Scale);
5914   }
5915
5916   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5917   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5918   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5919 }
5920
5921 /// getVZextMovL - Return a zero-extending vector move low node.
5922 ///
5923 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5924                             SDValue SrcOp, SelectionDAG &DAG,
5925                             const X86Subtarget *Subtarget, DebugLoc dl) {
5926   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5927     LoadSDNode *LD = NULL;
5928     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5929       LD = dyn_cast<LoadSDNode>(SrcOp);
5930     if (!LD) {
5931       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5932       // instead.
5933       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5934       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5935           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5936           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5937           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5938         // PR2108
5939         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5940         return DAG.getNode(ISD::BITCAST, dl, VT,
5941                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5942                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5943                                                    OpVT,
5944                                                    SrcOp.getOperand(0)
5945                                                           .getOperand(0))));
5946       }
5947     }
5948   }
5949
5950   return DAG.getNode(ISD::BITCAST, dl, VT,
5951                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5952                                  DAG.getNode(ISD::BITCAST, dl,
5953                                              OpVT, SrcOp)));
5954 }
5955
5956 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5957 /// which could not be matched by any known target speficic shuffle
5958 static SDValue
5959 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5960   EVT VT = SVOp->getValueType(0);
5961
5962   unsigned NumElems = VT.getVectorNumElements();
5963   unsigned NumLaneElems = NumElems / 2;
5964
5965   DebugLoc dl = SVOp->getDebugLoc();
5966   MVT EltVT = VT.getVectorElementType().getSimpleVT();
5967   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
5968   SDValue Shufs[2];
5969
5970   SmallVector<int, 16> Mask;
5971   for (unsigned l = 0; l < 2; ++l) {
5972     // Build a shuffle mask for the output, discovering on the fly which
5973     // input vectors to use as shuffle operands (recorded in InputUsed).
5974     // If building a suitable shuffle vector proves too hard, then bail
5975     // out with useBuildVector set.
5976     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
5977     unsigned LaneStart = l * NumLaneElems;
5978     for (unsigned i = 0; i != NumLaneElems; ++i) {
5979       // The mask element.  This indexes into the input.
5980       int Idx = SVOp->getMaskElt(i+LaneStart);
5981       if (Idx < 0) {
5982         // the mask element does not index into any input vector.
5983         Mask.push_back(-1);
5984         continue;
5985       }
5986
5987       // The input vector this mask element indexes into.
5988       int Input = Idx / NumLaneElems;
5989
5990       // Turn the index into an offset from the start of the input vector.
5991       Idx -= Input * NumLaneElems;
5992
5993       // Find or create a shuffle vector operand to hold this input.
5994       unsigned OpNo;
5995       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
5996         if (InputUsed[OpNo] == Input)
5997           // This input vector is already an operand.
5998           break;
5999         if (InputUsed[OpNo] < 0) {
6000           // Create a new operand for this input vector.
6001           InputUsed[OpNo] = Input;
6002           break;
6003         }
6004       }
6005
6006       if (OpNo >= array_lengthof(InputUsed)) {
6007         // More than two input vectors used! Give up.
6008         return SDValue();
6009       }
6010
6011       // Add the mask index for the new shuffle vector.
6012       Mask.push_back(Idx + OpNo * NumLaneElems);
6013     }
6014
6015     if (InputUsed[0] < 0) {
6016       // No input vectors were used! The result is undefined.
6017       Shufs[l] = DAG.getUNDEF(NVT);
6018     } else {
6019       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6020                                         (InputUsed[0] % 2) * NumLaneElems,
6021                                         DAG, dl);
6022       // If only one input was used, use an undefined vector for the other.
6023       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6024         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6025                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6026       // At least one input vector was used. Create a new shuffle vector.
6027       Shufs[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6028     }
6029
6030     Mask.clear();
6031   }
6032
6033   // Concatenate the result back
6034   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Shufs[0], Shufs[1]);
6035 }
6036
6037 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6038 /// 4 elements, and match them with several different shuffle types.
6039 static SDValue
6040 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6041   SDValue V1 = SVOp->getOperand(0);
6042   SDValue V2 = SVOp->getOperand(1);
6043   DebugLoc dl = SVOp->getDebugLoc();
6044   EVT VT = SVOp->getValueType(0);
6045
6046   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6047
6048   std::pair<int, int> Locs[4];
6049   int Mask1[] = { -1, -1, -1, -1 };
6050   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6051
6052   unsigned NumHi = 0;
6053   unsigned NumLo = 0;
6054   for (unsigned i = 0; i != 4; ++i) {
6055     int Idx = PermMask[i];
6056     if (Idx < 0) {
6057       Locs[i] = std::make_pair(-1, -1);
6058     } else {
6059       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6060       if (Idx < 4) {
6061         Locs[i] = std::make_pair(0, NumLo);
6062         Mask1[NumLo] = Idx;
6063         NumLo++;
6064       } else {
6065         Locs[i] = std::make_pair(1, NumHi);
6066         if (2+NumHi < 4)
6067           Mask1[2+NumHi] = Idx;
6068         NumHi++;
6069       }
6070     }
6071   }
6072
6073   if (NumLo <= 2 && NumHi <= 2) {
6074     // If no more than two elements come from either vector. This can be
6075     // implemented with two shuffles. First shuffle gather the elements.
6076     // The second shuffle, which takes the first shuffle as both of its
6077     // vector operands, put the elements into the right order.
6078     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6079
6080     int Mask2[] = { -1, -1, -1, -1 };
6081
6082     for (unsigned i = 0; i != 4; ++i)
6083       if (Locs[i].first != -1) {
6084         unsigned Idx = (i < 2) ? 0 : 4;
6085         Idx += Locs[i].first * 2 + Locs[i].second;
6086         Mask2[i] = Idx;
6087       }
6088
6089     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6090   }
6091
6092   if (NumLo == 3 || NumHi == 3) {
6093     // Otherwise, we must have three elements from one vector, call it X, and
6094     // one element from the other, call it Y.  First, use a shufps to build an
6095     // intermediate vector with the one element from Y and the element from X
6096     // that will be in the same half in the final destination (the indexes don't
6097     // matter). Then, use a shufps to build the final vector, taking the half
6098     // containing the element from Y from the intermediate, and the other half
6099     // from X.
6100     if (NumHi == 3) {
6101       // Normalize it so the 3 elements come from V1.
6102       CommuteVectorShuffleMask(PermMask, 4);
6103       std::swap(V1, V2);
6104     }
6105
6106     // Find the element from V2.
6107     unsigned HiIndex;
6108     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6109       int Val = PermMask[HiIndex];
6110       if (Val < 0)
6111         continue;
6112       if (Val >= 4)
6113         break;
6114     }
6115
6116     Mask1[0] = PermMask[HiIndex];
6117     Mask1[1] = -1;
6118     Mask1[2] = PermMask[HiIndex^1];
6119     Mask1[3] = -1;
6120     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6121
6122     if (HiIndex >= 2) {
6123       Mask1[0] = PermMask[0];
6124       Mask1[1] = PermMask[1];
6125       Mask1[2] = HiIndex & 1 ? 6 : 4;
6126       Mask1[3] = HiIndex & 1 ? 4 : 6;
6127       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6128     }
6129
6130     Mask1[0] = HiIndex & 1 ? 2 : 0;
6131     Mask1[1] = HiIndex & 1 ? 0 : 2;
6132     Mask1[2] = PermMask[2];
6133     Mask1[3] = PermMask[3];
6134     if (Mask1[2] >= 0)
6135       Mask1[2] += 4;
6136     if (Mask1[3] >= 0)
6137       Mask1[3] += 4;
6138     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6139   }
6140
6141   // Break it into (shuffle shuffle_hi, shuffle_lo).
6142   int LoMask[] = { -1, -1, -1, -1 };
6143   int HiMask[] = { -1, -1, -1, -1 };
6144
6145   int *MaskPtr = LoMask;
6146   unsigned MaskIdx = 0;
6147   unsigned LoIdx = 0;
6148   unsigned HiIdx = 2;
6149   for (unsigned i = 0; i != 4; ++i) {
6150     if (i == 2) {
6151       MaskPtr = HiMask;
6152       MaskIdx = 1;
6153       LoIdx = 0;
6154       HiIdx = 2;
6155     }
6156     int Idx = PermMask[i];
6157     if (Idx < 0) {
6158       Locs[i] = std::make_pair(-1, -1);
6159     } else if (Idx < 4) {
6160       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6161       MaskPtr[LoIdx] = Idx;
6162       LoIdx++;
6163     } else {
6164       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6165       MaskPtr[HiIdx] = Idx;
6166       HiIdx++;
6167     }
6168   }
6169
6170   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6171   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6172   int MaskOps[] = { -1, -1, -1, -1 };
6173   for (unsigned i = 0; i != 4; ++i)
6174     if (Locs[i].first != -1)
6175       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6176   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6177 }
6178
6179 static bool MayFoldVectorLoad(SDValue V) {
6180   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6181     V = V.getOperand(0);
6182   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6183     V = V.getOperand(0);
6184   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6185       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6186     // BUILD_VECTOR (load), undef
6187     V = V.getOperand(0);
6188   if (MayFoldLoad(V))
6189     return true;
6190   return false;
6191 }
6192
6193 // FIXME: the version above should always be used. Since there's
6194 // a bug where several vector shuffles can't be folded because the
6195 // DAG is not updated during lowering and a node claims to have two
6196 // uses while it only has one, use this version, and let isel match
6197 // another instruction if the load really happens to have more than
6198 // one use. Remove this version after this bug get fixed.
6199 // rdar://8434668, PR8156
6200 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6201   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6202     V = V.getOperand(0);
6203   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6204     V = V.getOperand(0);
6205   if (ISD::isNormalLoad(V.getNode()))
6206     return true;
6207   return false;
6208 }
6209
6210 static
6211 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6212   EVT VT = Op.getValueType();
6213
6214   // Canonizalize to v2f64.
6215   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6216   return DAG.getNode(ISD::BITCAST, dl, VT,
6217                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6218                                           V1, DAG));
6219 }
6220
6221 static
6222 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6223                         bool HasSSE2) {
6224   SDValue V1 = Op.getOperand(0);
6225   SDValue V2 = Op.getOperand(1);
6226   EVT VT = Op.getValueType();
6227
6228   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6229
6230   if (HasSSE2 && VT == MVT::v2f64)
6231     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6232
6233   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6234   return DAG.getNode(ISD::BITCAST, dl, VT,
6235                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6236                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6237                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6238 }
6239
6240 static
6241 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6242   SDValue V1 = Op.getOperand(0);
6243   SDValue V2 = Op.getOperand(1);
6244   EVT VT = Op.getValueType();
6245
6246   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6247          "unsupported shuffle type");
6248
6249   if (V2.getOpcode() == ISD::UNDEF)
6250     V2 = V1;
6251
6252   // v4i32 or v4f32
6253   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6254 }
6255
6256 static
6257 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6258   SDValue V1 = Op.getOperand(0);
6259   SDValue V2 = Op.getOperand(1);
6260   EVT VT = Op.getValueType();
6261   unsigned NumElems = VT.getVectorNumElements();
6262
6263   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6264   // operand of these instructions is only memory, so check if there's a
6265   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6266   // same masks.
6267   bool CanFoldLoad = false;
6268
6269   // Trivial case, when V2 comes from a load.
6270   if (MayFoldVectorLoad(V2))
6271     CanFoldLoad = true;
6272
6273   // When V1 is a load, it can be folded later into a store in isel, example:
6274   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6275   //    turns into:
6276   //  (MOVLPSmr addr:$src1, VR128:$src2)
6277   // So, recognize this potential and also use MOVLPS or MOVLPD
6278   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6279     CanFoldLoad = true;
6280
6281   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6282   if (CanFoldLoad) {
6283     if (HasSSE2 && NumElems == 2)
6284       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6285
6286     if (NumElems == 4)
6287       // If we don't care about the second element, procede to use movss.
6288       if (SVOp->getMaskElt(1) != -1)
6289         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6290   }
6291
6292   // movl and movlp will both match v2i64, but v2i64 is never matched by
6293   // movl earlier because we make it strict to avoid messing with the movlp load
6294   // folding logic (see the code above getMOVLP call). Match it here then,
6295   // this is horrible, but will stay like this until we move all shuffle
6296   // matching to x86 specific nodes. Note that for the 1st condition all
6297   // types are matched with movsd.
6298   if (HasSSE2) {
6299     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6300     // as to remove this logic from here, as much as possible
6301     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6302       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6303     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6304   }
6305
6306   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6307
6308   // Invert the operand order and use SHUFPS to match it.
6309   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6310                               getShuffleSHUFImmediate(SVOp), DAG);
6311 }
6312
6313 SDValue
6314 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6315   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6316   EVT VT = Op.getValueType();
6317   DebugLoc dl = Op.getDebugLoc();
6318   SDValue V1 = Op.getOperand(0);
6319   SDValue V2 = Op.getOperand(1);
6320
6321   if (isZeroShuffle(SVOp))
6322     return getZeroVector(VT, Subtarget, DAG, dl);
6323
6324   // Handle splat operations
6325   if (SVOp->isSplat()) {
6326     unsigned NumElem = VT.getVectorNumElements();
6327     int Size = VT.getSizeInBits();
6328
6329     // Use vbroadcast whenever the splat comes from a foldable load
6330     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6331     if (Broadcast.getNode())
6332       return Broadcast;
6333
6334     // Handle splats by matching through known shuffle masks
6335     if ((Size == 128 && NumElem <= 4) ||
6336         (Size == 256 && NumElem < 8))
6337       return SDValue();
6338
6339     // All remaning splats are promoted to target supported vector shuffles.
6340     return PromoteSplat(SVOp, DAG);
6341   }
6342
6343   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6344   // do it!
6345   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6346     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6347     if (NewOp.getNode())
6348       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6349   } else if ((VT == MVT::v4i32 ||
6350              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6351     // FIXME: Figure out a cleaner way to do this.
6352     // Try to make use of movq to zero out the top part.
6353     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6354       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6355       if (NewOp.getNode()) {
6356         EVT NewVT = NewOp.getValueType();
6357         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6358                                NewVT, true, false))
6359           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6360                               DAG, Subtarget, dl);
6361       }
6362     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6363       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6364       if (NewOp.getNode()) {
6365         EVT NewVT = NewOp.getValueType();
6366         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6367           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6368                               DAG, Subtarget, dl);
6369       }
6370     }
6371   }
6372   return SDValue();
6373 }
6374
6375 SDValue
6376 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6377   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6378   SDValue V1 = Op.getOperand(0);
6379   SDValue V2 = Op.getOperand(1);
6380   EVT VT = Op.getValueType();
6381   DebugLoc dl = Op.getDebugLoc();
6382   unsigned NumElems = VT.getVectorNumElements();
6383   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6384   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6385   bool V1IsSplat = false;
6386   bool V2IsSplat = false;
6387   bool HasSSE2 = Subtarget->hasSSE2();
6388   bool HasAVX    = Subtarget->hasAVX();
6389   bool HasAVX2   = Subtarget->hasAVX2();
6390   MachineFunction &MF = DAG.getMachineFunction();
6391   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6392
6393   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6394
6395   if (V1IsUndef && V2IsUndef)
6396     return DAG.getUNDEF(VT);
6397
6398   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6399
6400   // Vector shuffle lowering takes 3 steps:
6401   //
6402   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6403   //    narrowing and commutation of operands should be handled.
6404   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6405   //    shuffle nodes.
6406   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6407   //    so the shuffle can be broken into other shuffles and the legalizer can
6408   //    try the lowering again.
6409   //
6410   // The general idea is that no vector_shuffle operation should be left to
6411   // be matched during isel, all of them must be converted to a target specific
6412   // node here.
6413
6414   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6415   // narrowing and commutation of operands should be handled. The actual code
6416   // doesn't include all of those, work in progress...
6417   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6418   if (NewOp.getNode())
6419     return NewOp;
6420
6421   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6422
6423   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6424   // unpckh_undef). Only use pshufd if speed is more important than size.
6425   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6426     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6427   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6428     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6429
6430   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6431       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6432     return getMOVDDup(Op, dl, V1, DAG);
6433
6434   if (isMOVHLPS_v_undef_Mask(M, VT))
6435     return getMOVHighToLow(Op, dl, DAG);
6436
6437   // Use to match splats
6438   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6439       (VT == MVT::v2f64 || VT == MVT::v2i64))
6440     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6441
6442   if (isPSHUFDMask(M, VT)) {
6443     // The actual implementation will match the mask in the if above and then
6444     // during isel it can match several different instructions, not only pshufd
6445     // as its name says, sad but true, emulate the behavior for now...
6446     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6447       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6448
6449     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6450
6451     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6452       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6453
6454     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6455       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6456
6457     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6458                                 TargetMask, DAG);
6459   }
6460
6461   // Check if this can be converted into a logical shift.
6462   bool isLeft = false;
6463   unsigned ShAmt = 0;
6464   SDValue ShVal;
6465   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6466   if (isShift && ShVal.hasOneUse()) {
6467     // If the shifted value has multiple uses, it may be cheaper to use
6468     // v_set0 + movlhps or movhlps, etc.
6469     EVT EltVT = VT.getVectorElementType();
6470     ShAmt *= EltVT.getSizeInBits();
6471     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6472   }
6473
6474   if (isMOVLMask(M, VT)) {
6475     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6476       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6477     if (!isMOVLPMask(M, VT)) {
6478       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6479         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6480
6481       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6482         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6483     }
6484   }
6485
6486   // FIXME: fold these into legal mask.
6487   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6488     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6489
6490   if (isMOVHLPSMask(M, VT))
6491     return getMOVHighToLow(Op, dl, DAG);
6492
6493   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6494     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6495
6496   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6497     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6498
6499   if (isMOVLPMask(M, VT))
6500     return getMOVLP(Op, dl, DAG, HasSSE2);
6501
6502   if (ShouldXformToMOVHLPS(M, VT) ||
6503       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6504     return CommuteVectorShuffle(SVOp, DAG);
6505
6506   if (isShift) {
6507     // No better options. Use a vshldq / vsrldq.
6508     EVT EltVT = VT.getVectorElementType();
6509     ShAmt *= EltVT.getSizeInBits();
6510     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6511   }
6512
6513   bool Commuted = false;
6514   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6515   // 1,1,1,1 -> v8i16 though.
6516   V1IsSplat = isSplatVector(V1.getNode());
6517   V2IsSplat = isSplatVector(V2.getNode());
6518
6519   // Canonicalize the splat or undef, if present, to be on the RHS.
6520   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6521     CommuteVectorShuffleMask(M, NumElems);
6522     std::swap(V1, V2);
6523     std::swap(V1IsSplat, V2IsSplat);
6524     Commuted = true;
6525   }
6526
6527   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6528     // Shuffling low element of v1 into undef, just return v1.
6529     if (V2IsUndef)
6530       return V1;
6531     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6532     // the instruction selector will not match, so get a canonical MOVL with
6533     // swapped operands to undo the commute.
6534     return getMOVL(DAG, dl, VT, V2, V1);
6535   }
6536
6537   if (isUNPCKLMask(M, VT, HasAVX2))
6538     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6539
6540   if (isUNPCKHMask(M, VT, HasAVX2))
6541     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6542
6543   if (V2IsSplat) {
6544     // Normalize mask so all entries that point to V2 points to its first
6545     // element then try to match unpck{h|l} again. If match, return a
6546     // new vector_shuffle with the corrected mask.p
6547     SmallVector<int, 8> NewMask(M.begin(), M.end());
6548     NormalizeMask(NewMask, NumElems);
6549     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6550       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6551     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6552       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6553   }
6554
6555   if (Commuted) {
6556     // Commute is back and try unpck* again.
6557     // FIXME: this seems wrong.
6558     CommuteVectorShuffleMask(M, NumElems);
6559     std::swap(V1, V2);
6560     std::swap(V1IsSplat, V2IsSplat);
6561     Commuted = false;
6562
6563     if (isUNPCKLMask(M, VT, HasAVX2))
6564       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6565
6566     if (isUNPCKHMask(M, VT, HasAVX2))
6567       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6568   }
6569
6570   // Normalize the node to match x86 shuffle ops if needed
6571   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6572     return CommuteVectorShuffle(SVOp, DAG);
6573
6574   // The checks below are all present in isShuffleMaskLegal, but they are
6575   // inlined here right now to enable us to directly emit target specific
6576   // nodes, and remove one by one until they don't return Op anymore.
6577
6578   if (isPALIGNRMask(M, VT, Subtarget))
6579     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6580                                 getShufflePALIGNRImmediate(SVOp),
6581                                 DAG);
6582
6583   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6584       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6585     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6586       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6587   }
6588
6589   if (isPSHUFHWMask(M, VT))
6590     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6591                                 getShufflePSHUFHWImmediate(SVOp),
6592                                 DAG);
6593
6594   if (isPSHUFLWMask(M, VT))
6595     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6596                                 getShufflePSHUFLWImmediate(SVOp),
6597                                 DAG);
6598
6599   if (isSHUFPMask(M, VT, HasAVX))
6600     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6601                                 getShuffleSHUFImmediate(SVOp), DAG);
6602
6603   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6604     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6605   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6606     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6607
6608   //===--------------------------------------------------------------------===//
6609   // Generate target specific nodes for 128 or 256-bit shuffles only
6610   // supported in the AVX instruction set.
6611   //
6612
6613   // Handle VMOVDDUPY permutations
6614   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6615     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6616
6617   // Handle VPERMILPS/D* permutations
6618   if (isVPERMILPMask(M, VT, HasAVX)) {
6619     if (HasAVX2 && VT == MVT::v8i32)
6620       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6621                                   getShuffleSHUFImmediate(SVOp), DAG);
6622     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6623                                 getShuffleSHUFImmediate(SVOp), DAG);
6624   }
6625
6626   // Handle VPERM2F128/VPERM2I128 permutations
6627   if (isVPERM2X128Mask(M, VT, HasAVX))
6628     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6629                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6630
6631   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6632   if (BlendOp.getNode())
6633     return BlendOp;
6634
6635   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6636     SmallVector<SDValue, 8> permclMask;
6637     for (unsigned i = 0; i != 8; ++i) {
6638       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6639     }
6640     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6641                                &permclMask[0], 8);
6642     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6643     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6644                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6645   }
6646
6647   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6648     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6649                                 getShuffleCLImmediate(SVOp), DAG);
6650
6651
6652   //===--------------------------------------------------------------------===//
6653   // Since no target specific shuffle was selected for this generic one,
6654   // lower it into other known shuffles. FIXME: this isn't true yet, but
6655   // this is the plan.
6656   //
6657
6658   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6659   if (VT == MVT::v8i16) {
6660     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6661     if (NewOp.getNode())
6662       return NewOp;
6663   }
6664
6665   if (VT == MVT::v16i8) {
6666     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6667     if (NewOp.getNode())
6668       return NewOp;
6669   }
6670
6671   // Handle all 128-bit wide vectors with 4 elements, and match them with
6672   // several different shuffle types.
6673   if (NumElems == 4 && VT.getSizeInBits() == 128)
6674     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6675
6676   // Handle general 256-bit shuffles
6677   if (VT.is256BitVector())
6678     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6679
6680   return SDValue();
6681 }
6682
6683 SDValue
6684 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6685                                                 SelectionDAG &DAG) const {
6686   EVT VT = Op.getValueType();
6687   DebugLoc dl = Op.getDebugLoc();
6688
6689   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6690     return SDValue();
6691
6692   if (VT.getSizeInBits() == 8) {
6693     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6694                                     Op.getOperand(0), Op.getOperand(1));
6695     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6696                                     DAG.getValueType(VT));
6697     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6698   }
6699
6700   if (VT.getSizeInBits() == 16) {
6701     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6702     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6703     if (Idx == 0)
6704       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6705                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6706                                      DAG.getNode(ISD::BITCAST, dl,
6707                                                  MVT::v4i32,
6708                                                  Op.getOperand(0)),
6709                                      Op.getOperand(1)));
6710     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6711                                     Op.getOperand(0), Op.getOperand(1));
6712     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6713                                     DAG.getValueType(VT));
6714     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6715   }
6716
6717   if (VT == MVT::f32) {
6718     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6719     // the result back to FR32 register. It's only worth matching if the
6720     // result has a single use which is a store or a bitcast to i32.  And in
6721     // the case of a store, it's not worth it if the index is a constant 0,
6722     // because a MOVSSmr can be used instead, which is smaller and faster.
6723     if (!Op.hasOneUse())
6724       return SDValue();
6725     SDNode *User = *Op.getNode()->use_begin();
6726     if ((User->getOpcode() != ISD::STORE ||
6727          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6728           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6729         (User->getOpcode() != ISD::BITCAST ||
6730          User->getValueType(0) != MVT::i32))
6731       return SDValue();
6732     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6733                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6734                                               Op.getOperand(0)),
6735                                               Op.getOperand(1));
6736     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6737   }
6738
6739   if (VT == MVT::i32 || VT == MVT::i64) {
6740     // ExtractPS/pextrq works with constant index.
6741     if (isa<ConstantSDNode>(Op.getOperand(1)))
6742       return Op;
6743   }
6744   return SDValue();
6745 }
6746
6747
6748 SDValue
6749 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6750                                            SelectionDAG &DAG) const {
6751   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6752     return SDValue();
6753
6754   SDValue Vec = Op.getOperand(0);
6755   EVT VecVT = Vec.getValueType();
6756
6757   // If this is a 256-bit vector result, first extract the 128-bit vector and
6758   // then extract the element from the 128-bit vector.
6759   if (VecVT.getSizeInBits() == 256) {
6760     DebugLoc dl = Op.getNode()->getDebugLoc();
6761     unsigned NumElems = VecVT.getVectorNumElements();
6762     SDValue Idx = Op.getOperand(1);
6763     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6764
6765     // Get the 128-bit vector.
6766     bool Upper = IdxVal >= NumElems/2;
6767     Vec = Extract128BitVector(Vec, Upper ? NumElems/2 : 0, DAG, dl);
6768
6769     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6770                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6771   }
6772
6773   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6774
6775   if (Subtarget->hasSSE41()) {
6776     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6777     if (Res.getNode())
6778       return Res;
6779   }
6780
6781   EVT VT = Op.getValueType();
6782   DebugLoc dl = Op.getDebugLoc();
6783   // TODO: handle v16i8.
6784   if (VT.getSizeInBits() == 16) {
6785     SDValue Vec = Op.getOperand(0);
6786     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6787     if (Idx == 0)
6788       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6789                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6790                                      DAG.getNode(ISD::BITCAST, dl,
6791                                                  MVT::v4i32, Vec),
6792                                      Op.getOperand(1)));
6793     // Transform it so it match pextrw which produces a 32-bit result.
6794     EVT EltVT = MVT::i32;
6795     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6796                                     Op.getOperand(0), Op.getOperand(1));
6797     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6798                                     DAG.getValueType(VT));
6799     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6800   }
6801
6802   if (VT.getSizeInBits() == 32) {
6803     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6804     if (Idx == 0)
6805       return Op;
6806
6807     // SHUFPS the element to the lowest double word, then movss.
6808     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6809     EVT VVT = Op.getOperand(0).getValueType();
6810     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6811                                        DAG.getUNDEF(VVT), Mask);
6812     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6813                        DAG.getIntPtrConstant(0));
6814   }
6815
6816   if (VT.getSizeInBits() == 64) {
6817     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6818     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6819     //        to match extract_elt for f64.
6820     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6821     if (Idx == 0)
6822       return Op;
6823
6824     // UNPCKHPD the element to the lowest double word, then movsd.
6825     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6826     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6827     int Mask[2] = { 1, -1 };
6828     EVT VVT = Op.getOperand(0).getValueType();
6829     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6830                                        DAG.getUNDEF(VVT), Mask);
6831     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6832                        DAG.getIntPtrConstant(0));
6833   }
6834
6835   return SDValue();
6836 }
6837
6838 SDValue
6839 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6840                                                SelectionDAG &DAG) const {
6841   EVT VT = Op.getValueType();
6842   EVT EltVT = VT.getVectorElementType();
6843   DebugLoc dl = Op.getDebugLoc();
6844
6845   SDValue N0 = Op.getOperand(0);
6846   SDValue N1 = Op.getOperand(1);
6847   SDValue N2 = Op.getOperand(2);
6848
6849   if (VT.getSizeInBits() == 256)
6850     return SDValue();
6851
6852   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6853       isa<ConstantSDNode>(N2)) {
6854     unsigned Opc;
6855     if (VT == MVT::v8i16)
6856       Opc = X86ISD::PINSRW;
6857     else if (VT == MVT::v16i8)
6858       Opc = X86ISD::PINSRB;
6859     else
6860       Opc = X86ISD::PINSRB;
6861
6862     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6863     // argument.
6864     if (N1.getValueType() != MVT::i32)
6865       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6866     if (N2.getValueType() != MVT::i32)
6867       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6868     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6869   }
6870
6871   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6872     // Bits [7:6] of the constant are the source select.  This will always be
6873     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6874     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6875     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6876     // Bits [5:4] of the constant are the destination select.  This is the
6877     //  value of the incoming immediate.
6878     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6879     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6880     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6881     // Create this as a scalar to vector..
6882     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6883     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6884   }
6885
6886   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6887     // PINSR* works with constant index.
6888     return Op;
6889   }
6890   return SDValue();
6891 }
6892
6893 SDValue
6894 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6895   EVT VT = Op.getValueType();
6896   EVT EltVT = VT.getVectorElementType();
6897
6898   DebugLoc dl = Op.getDebugLoc();
6899   SDValue N0 = Op.getOperand(0);
6900   SDValue N1 = Op.getOperand(1);
6901   SDValue N2 = Op.getOperand(2);
6902
6903   // If this is a 256-bit vector result, first extract the 128-bit vector,
6904   // insert the element into the extracted half and then place it back.
6905   if (VT.getSizeInBits() == 256) {
6906     if (!isa<ConstantSDNode>(N2))
6907       return SDValue();
6908
6909     // Get the desired 128-bit vector half.
6910     unsigned NumElems = VT.getVectorNumElements();
6911     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6912     bool Upper = IdxVal >= NumElems/2;
6913     unsigned Ins128Idx = Upper ? NumElems/2 : 0;
6914     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6915
6916     // Insert the element into the desired half.
6917     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6918                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6919
6920     // Insert the changed part back to the 256-bit vector
6921     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6922   }
6923
6924   if (Subtarget->hasSSE41())
6925     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6926
6927   if (EltVT == MVT::i8)
6928     return SDValue();
6929
6930   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6931     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6932     // as its second argument.
6933     if (N1.getValueType() != MVT::i32)
6934       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6935     if (N2.getValueType() != MVT::i32)
6936       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6937     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6938   }
6939   return SDValue();
6940 }
6941
6942 SDValue
6943 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6944   LLVMContext *Context = DAG.getContext();
6945   DebugLoc dl = Op.getDebugLoc();
6946   EVT OpVT = Op.getValueType();
6947
6948   // If this is a 256-bit vector result, first insert into a 128-bit
6949   // vector and then insert into the 256-bit vector.
6950   if (OpVT.getSizeInBits() > 128) {
6951     // Insert into a 128-bit vector.
6952     EVT VT128 = EVT::getVectorVT(*Context,
6953                                  OpVT.getVectorElementType(),
6954                                  OpVT.getVectorNumElements() / 2);
6955
6956     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6957
6958     // Insert the 128-bit vector.
6959     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
6960   }
6961
6962   if (Op.getValueType() == MVT::v1i64 &&
6963       Op.getOperand(0).getValueType() == MVT::i64)
6964     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6965
6966   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6967   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6968          "Expected an SSE type!");
6969   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6970                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6971 }
6972
6973 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6974 // a simple subregister reference or explicit instructions to grab
6975 // upper bits of a vector.
6976 SDValue
6977 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6978   if (Subtarget->hasAVX()) {
6979     DebugLoc dl = Op.getNode()->getDebugLoc();
6980     SDValue Vec = Op.getNode()->getOperand(0);
6981     SDValue Idx = Op.getNode()->getOperand(1);
6982
6983     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
6984         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
6985         isa<ConstantSDNode>(Idx)) {
6986       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6987       return Extract128BitVector(Vec, IdxVal, DAG, dl);
6988     }
6989   }
6990   return SDValue();
6991 }
6992
6993 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6994 // simple superregister reference or explicit instructions to insert
6995 // the upper bits of a vector.
6996 SDValue
6997 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6998   if (Subtarget->hasAVX()) {
6999     DebugLoc dl = Op.getNode()->getDebugLoc();
7000     SDValue Vec = Op.getNode()->getOperand(0);
7001     SDValue SubVec = Op.getNode()->getOperand(1);
7002     SDValue Idx = Op.getNode()->getOperand(2);
7003
7004     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7005         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7006         isa<ConstantSDNode>(Idx)) {
7007       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7008       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7009     }
7010   }
7011   return SDValue();
7012 }
7013
7014 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7015 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7016 // one of the above mentioned nodes. It has to be wrapped because otherwise
7017 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7018 // be used to form addressing mode. These wrapped nodes will be selected
7019 // into MOV32ri.
7020 SDValue
7021 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7022   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7023
7024   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7025   // global base reg.
7026   unsigned char OpFlag = 0;
7027   unsigned WrapperKind = X86ISD::Wrapper;
7028   CodeModel::Model M = getTargetMachine().getCodeModel();
7029
7030   if (Subtarget->isPICStyleRIPRel() &&
7031       (M == CodeModel::Small || M == CodeModel::Kernel))
7032     WrapperKind = X86ISD::WrapperRIP;
7033   else if (Subtarget->isPICStyleGOT())
7034     OpFlag = X86II::MO_GOTOFF;
7035   else if (Subtarget->isPICStyleStubPIC())
7036     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7037
7038   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7039                                              CP->getAlignment(),
7040                                              CP->getOffset(), OpFlag);
7041   DebugLoc DL = CP->getDebugLoc();
7042   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7043   // With PIC, the address is actually $g + Offset.
7044   if (OpFlag) {
7045     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7046                          DAG.getNode(X86ISD::GlobalBaseReg,
7047                                      DebugLoc(), getPointerTy()),
7048                          Result);
7049   }
7050
7051   return Result;
7052 }
7053
7054 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7055   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7056
7057   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7058   // global base reg.
7059   unsigned char OpFlag = 0;
7060   unsigned WrapperKind = X86ISD::Wrapper;
7061   CodeModel::Model M = getTargetMachine().getCodeModel();
7062
7063   if (Subtarget->isPICStyleRIPRel() &&
7064       (M == CodeModel::Small || M == CodeModel::Kernel))
7065     WrapperKind = X86ISD::WrapperRIP;
7066   else if (Subtarget->isPICStyleGOT())
7067     OpFlag = X86II::MO_GOTOFF;
7068   else if (Subtarget->isPICStyleStubPIC())
7069     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7070
7071   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7072                                           OpFlag);
7073   DebugLoc DL = JT->getDebugLoc();
7074   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7075
7076   // With PIC, the address is actually $g + Offset.
7077   if (OpFlag)
7078     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7079                          DAG.getNode(X86ISD::GlobalBaseReg,
7080                                      DebugLoc(), getPointerTy()),
7081                          Result);
7082
7083   return Result;
7084 }
7085
7086 SDValue
7087 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7088   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7089
7090   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7091   // global base reg.
7092   unsigned char OpFlag = 0;
7093   unsigned WrapperKind = X86ISD::Wrapper;
7094   CodeModel::Model M = getTargetMachine().getCodeModel();
7095
7096   if (Subtarget->isPICStyleRIPRel() &&
7097       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7098     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7099       OpFlag = X86II::MO_GOTPCREL;
7100     WrapperKind = X86ISD::WrapperRIP;
7101   } else if (Subtarget->isPICStyleGOT()) {
7102     OpFlag = X86II::MO_GOT;
7103   } else if (Subtarget->isPICStyleStubPIC()) {
7104     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7105   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7106     OpFlag = X86II::MO_DARWIN_NONLAZY;
7107   }
7108
7109   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7110
7111   DebugLoc DL = Op.getDebugLoc();
7112   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7113
7114
7115   // With PIC, the address is actually $g + Offset.
7116   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7117       !Subtarget->is64Bit()) {
7118     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7119                          DAG.getNode(X86ISD::GlobalBaseReg,
7120                                      DebugLoc(), getPointerTy()),
7121                          Result);
7122   }
7123
7124   // For symbols that require a load from a stub to get the address, emit the
7125   // load.
7126   if (isGlobalStubReference(OpFlag))
7127     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7128                          MachinePointerInfo::getGOT(), false, false, false, 0);
7129
7130   return Result;
7131 }
7132
7133 SDValue
7134 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7135   // Create the TargetBlockAddressAddress node.
7136   unsigned char OpFlags =
7137     Subtarget->ClassifyBlockAddressReference();
7138   CodeModel::Model M = getTargetMachine().getCodeModel();
7139   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7140   DebugLoc dl = Op.getDebugLoc();
7141   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7142                                        /*isTarget=*/true, OpFlags);
7143
7144   if (Subtarget->isPICStyleRIPRel() &&
7145       (M == CodeModel::Small || M == CodeModel::Kernel))
7146     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7147   else
7148     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7149
7150   // With PIC, the address is actually $g + Offset.
7151   if (isGlobalRelativeToPICBase(OpFlags)) {
7152     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7153                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7154                          Result);
7155   }
7156
7157   return Result;
7158 }
7159
7160 SDValue
7161 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7162                                       int64_t Offset,
7163                                       SelectionDAG &DAG) const {
7164   // Create the TargetGlobalAddress node, folding in the constant
7165   // offset if it is legal.
7166   unsigned char OpFlags =
7167     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7168   CodeModel::Model M = getTargetMachine().getCodeModel();
7169   SDValue Result;
7170   if (OpFlags == X86II::MO_NO_FLAG &&
7171       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7172     // A direct static reference to a global.
7173     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7174     Offset = 0;
7175   } else {
7176     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7177   }
7178
7179   if (Subtarget->isPICStyleRIPRel() &&
7180       (M == CodeModel::Small || M == CodeModel::Kernel))
7181     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7182   else
7183     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7184
7185   // With PIC, the address is actually $g + Offset.
7186   if (isGlobalRelativeToPICBase(OpFlags)) {
7187     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7188                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7189                          Result);
7190   }
7191
7192   // For globals that require a load from a stub to get the address, emit the
7193   // load.
7194   if (isGlobalStubReference(OpFlags))
7195     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7196                          MachinePointerInfo::getGOT(), false, false, false, 0);
7197
7198   // If there was a non-zero offset that we didn't fold, create an explicit
7199   // addition for it.
7200   if (Offset != 0)
7201     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7202                          DAG.getConstant(Offset, getPointerTy()));
7203
7204   return Result;
7205 }
7206
7207 SDValue
7208 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7209   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7210   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7211   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7212 }
7213
7214 static SDValue
7215 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7216            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7217            unsigned char OperandFlags) {
7218   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7219   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7220   DebugLoc dl = GA->getDebugLoc();
7221   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7222                                            GA->getValueType(0),
7223                                            GA->getOffset(),
7224                                            OperandFlags);
7225   if (InFlag) {
7226     SDValue Ops[] = { Chain,  TGA, *InFlag };
7227     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7228   } else {
7229     SDValue Ops[]  = { Chain, TGA };
7230     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7231   }
7232
7233   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7234   MFI->setAdjustsStack(true);
7235
7236   SDValue Flag = Chain.getValue(1);
7237   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7238 }
7239
7240 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7241 static SDValue
7242 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7243                                 const EVT PtrVT) {
7244   SDValue InFlag;
7245   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7246   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7247                                      DAG.getNode(X86ISD::GlobalBaseReg,
7248                                                  DebugLoc(), PtrVT), InFlag);
7249   InFlag = Chain.getValue(1);
7250
7251   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7252 }
7253
7254 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7255 static SDValue
7256 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7257                                 const EVT PtrVT) {
7258   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7259                     X86::RAX, X86II::MO_TLSGD);
7260 }
7261
7262 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7263 // "local exec" model.
7264 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7265                                    const EVT PtrVT, TLSModel::Model model,
7266                                    bool is64Bit) {
7267   DebugLoc dl = GA->getDebugLoc();
7268
7269   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7270   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7271                                                          is64Bit ? 257 : 256));
7272
7273   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7274                                       DAG.getIntPtrConstant(0),
7275                                       MachinePointerInfo(Ptr),
7276                                       false, false, false, 0);
7277
7278   unsigned char OperandFlags = 0;
7279   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7280   // initialexec.
7281   unsigned WrapperKind = X86ISD::Wrapper;
7282   if (model == TLSModel::LocalExec) {
7283     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7284   } else if (is64Bit) {
7285     assert(model == TLSModel::InitialExec);
7286     OperandFlags = X86II::MO_GOTTPOFF;
7287     WrapperKind = X86ISD::WrapperRIP;
7288   } else {
7289     assert(model == TLSModel::InitialExec);
7290     OperandFlags = X86II::MO_INDNTPOFF;
7291   }
7292
7293   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7294   // exec)
7295   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7296                                            GA->getValueType(0),
7297                                            GA->getOffset(), OperandFlags);
7298   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7299
7300   if (model == TLSModel::InitialExec)
7301     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7302                          MachinePointerInfo::getGOT(), false, false, false, 0);
7303
7304   // The address of the thread local variable is the add of the thread
7305   // pointer with the offset of the variable.
7306   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7307 }
7308
7309 SDValue
7310 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7311
7312   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7313   const GlobalValue *GV = GA->getGlobal();
7314
7315   if (Subtarget->isTargetELF()) {
7316     // TODO: implement the "local dynamic" model
7317     // TODO: implement the "initial exec"model for pic executables
7318
7319     // If GV is an alias then use the aliasee for determining
7320     // thread-localness.
7321     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7322       GV = GA->resolveAliasedGlobal(false);
7323
7324     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7325
7326     switch (model) {
7327       case TLSModel::GeneralDynamic:
7328       case TLSModel::LocalDynamic: // not implemented
7329         if (Subtarget->is64Bit())
7330           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7331         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7332
7333       case TLSModel::InitialExec:
7334       case TLSModel::LocalExec:
7335         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7336                                    Subtarget->is64Bit());
7337     }
7338     llvm_unreachable("Unknown TLS model.");
7339   }
7340
7341   if (Subtarget->isTargetDarwin()) {
7342     // Darwin only has one model of TLS.  Lower to that.
7343     unsigned char OpFlag = 0;
7344     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7345                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7346
7347     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7348     // global base reg.
7349     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7350                   !Subtarget->is64Bit();
7351     if (PIC32)
7352       OpFlag = X86II::MO_TLVP_PIC_BASE;
7353     else
7354       OpFlag = X86II::MO_TLVP;
7355     DebugLoc DL = Op.getDebugLoc();
7356     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7357                                                 GA->getValueType(0),
7358                                                 GA->getOffset(), OpFlag);
7359     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7360
7361     // With PIC32, the address is actually $g + Offset.
7362     if (PIC32)
7363       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7364                            DAG.getNode(X86ISD::GlobalBaseReg,
7365                                        DebugLoc(), getPointerTy()),
7366                            Offset);
7367
7368     // Lowering the machine isd will make sure everything is in the right
7369     // location.
7370     SDValue Chain = DAG.getEntryNode();
7371     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7372     SDValue Args[] = { Chain, Offset };
7373     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7374
7375     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7376     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7377     MFI->setAdjustsStack(true);
7378
7379     // And our return value (tls address) is in the standard call return value
7380     // location.
7381     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7382     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7383                               Chain.getValue(1));
7384   }
7385
7386   if (Subtarget->isTargetWindows()) {
7387     // Just use the implicit TLS architecture
7388     // Need to generate someting similar to:
7389     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7390     //                                  ; from TEB
7391     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7392     //   mov     rcx, qword [rdx+rcx*8]
7393     //   mov     eax, .tls$:tlsvar
7394     //   [rax+rcx] contains the address
7395     // Windows 64bit: gs:0x58
7396     // Windows 32bit: fs:__tls_array
7397
7398     // If GV is an alias then use the aliasee for determining
7399     // thread-localness.
7400     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7401       GV = GA->resolveAliasedGlobal(false);
7402     DebugLoc dl = GA->getDebugLoc();
7403     SDValue Chain = DAG.getEntryNode();
7404
7405     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7406     // %gs:0x58 (64-bit).
7407     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7408                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7409                                                              256)
7410                                         : Type::getInt32PtrTy(*DAG.getContext(),
7411                                                               257));
7412
7413     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7414                                         Subtarget->is64Bit()
7415                                         ? DAG.getIntPtrConstant(0x58)
7416                                         : DAG.getExternalSymbol("_tls_array",
7417                                                                 getPointerTy()),
7418                                         MachinePointerInfo(Ptr),
7419                                         false, false, false, 0);
7420
7421     // Load the _tls_index variable
7422     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7423     if (Subtarget->is64Bit())
7424       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7425                            IDX, MachinePointerInfo(), MVT::i32,
7426                            false, false, 0);
7427     else
7428       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7429                         false, false, false, 0);
7430
7431     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7432                                     getPointerTy());
7433     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7434
7435     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7436     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7437                       false, false, false, 0);
7438
7439     // Get the offset of start of .tls section
7440     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7441                                              GA->getValueType(0),
7442                                              GA->getOffset(), X86II::MO_SECREL);
7443     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7444
7445     // The address of the thread local variable is the add of the thread
7446     // pointer with the offset of the variable.
7447     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7448   }
7449
7450   llvm_unreachable("TLS not implemented for this target.");
7451 }
7452
7453
7454 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7455 /// and take a 2 x i32 value to shift plus a shift amount.
7456 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7457   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7458   EVT VT = Op.getValueType();
7459   unsigned VTBits = VT.getSizeInBits();
7460   DebugLoc dl = Op.getDebugLoc();
7461   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7462   SDValue ShOpLo = Op.getOperand(0);
7463   SDValue ShOpHi = Op.getOperand(1);
7464   SDValue ShAmt  = Op.getOperand(2);
7465   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7466                                      DAG.getConstant(VTBits - 1, MVT::i8))
7467                        : DAG.getConstant(0, VT);
7468
7469   SDValue Tmp2, Tmp3;
7470   if (Op.getOpcode() == ISD::SHL_PARTS) {
7471     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7472     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7473   } else {
7474     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7475     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7476   }
7477
7478   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7479                                 DAG.getConstant(VTBits, MVT::i8));
7480   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7481                              AndNode, DAG.getConstant(0, MVT::i8));
7482
7483   SDValue Hi, Lo;
7484   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7485   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7486   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7487
7488   if (Op.getOpcode() == ISD::SHL_PARTS) {
7489     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7490     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7491   } else {
7492     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7493     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7494   }
7495
7496   SDValue Ops[2] = { Lo, Hi };
7497   return DAG.getMergeValues(Ops, 2, dl);
7498 }
7499
7500 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7501                                            SelectionDAG &DAG) const {
7502   EVT SrcVT = Op.getOperand(0).getValueType();
7503
7504   if (SrcVT.isVector())
7505     return SDValue();
7506
7507   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7508          "Unknown SINT_TO_FP to lower!");
7509
7510   // These are really Legal; return the operand so the caller accepts it as
7511   // Legal.
7512   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7513     return Op;
7514   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7515       Subtarget->is64Bit()) {
7516     return Op;
7517   }
7518
7519   DebugLoc dl = Op.getDebugLoc();
7520   unsigned Size = SrcVT.getSizeInBits()/8;
7521   MachineFunction &MF = DAG.getMachineFunction();
7522   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7523   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7524   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7525                                StackSlot,
7526                                MachinePointerInfo::getFixedStack(SSFI),
7527                                false, false, 0);
7528   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7529 }
7530
7531 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7532                                      SDValue StackSlot,
7533                                      SelectionDAG &DAG) const {
7534   // Build the FILD
7535   DebugLoc DL = Op.getDebugLoc();
7536   SDVTList Tys;
7537   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7538   if (useSSE)
7539     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7540   else
7541     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7542
7543   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7544
7545   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7546   MachineMemOperand *MMO;
7547   if (FI) {
7548     int SSFI = FI->getIndex();
7549     MMO =
7550       DAG.getMachineFunction()
7551       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7552                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7553   } else {
7554     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7555     StackSlot = StackSlot.getOperand(1);
7556   }
7557   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7558   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7559                                            X86ISD::FILD, DL,
7560                                            Tys, Ops, array_lengthof(Ops),
7561                                            SrcVT, MMO);
7562
7563   if (useSSE) {
7564     Chain = Result.getValue(1);
7565     SDValue InFlag = Result.getValue(2);
7566
7567     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7568     // shouldn't be necessary except that RFP cannot be live across
7569     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7570     MachineFunction &MF = DAG.getMachineFunction();
7571     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7572     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7573     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7574     Tys = DAG.getVTList(MVT::Other);
7575     SDValue Ops[] = {
7576       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7577     };
7578     MachineMemOperand *MMO =
7579       DAG.getMachineFunction()
7580       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7581                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7582
7583     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7584                                     Ops, array_lengthof(Ops),
7585                                     Op.getValueType(), MMO);
7586     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7587                          MachinePointerInfo::getFixedStack(SSFI),
7588                          false, false, false, 0);
7589   }
7590
7591   return Result;
7592 }
7593
7594 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7595 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7596                                                SelectionDAG &DAG) const {
7597   // This algorithm is not obvious. Here it is what we're trying to output:
7598   /*
7599      movq       %rax,  %xmm0
7600      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7601      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7602      #ifdef __SSE3__
7603        haddpd   %xmm0, %xmm0          
7604      #else
7605        pshufd   $0x4e, %xmm0, %xmm1 
7606        addpd    %xmm1, %xmm0
7607      #endif
7608   */
7609
7610   DebugLoc dl = Op.getDebugLoc();
7611   LLVMContext *Context = DAG.getContext();
7612
7613   // Build some magic constants.
7614   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7615   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7616   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7617
7618   SmallVector<Constant*,2> CV1;
7619   CV1.push_back(
7620         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7621   CV1.push_back(
7622         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7623   Constant *C1 = ConstantVector::get(CV1);
7624   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7625
7626   // Load the 64-bit value into an XMM register.
7627   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7628                             Op.getOperand(0));
7629   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7630                               MachinePointerInfo::getConstantPool(),
7631                               false, false, false, 16);
7632   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7633                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7634                               CLod0);
7635
7636   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7637                               MachinePointerInfo::getConstantPool(),
7638                               false, false, false, 16);
7639   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7640   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7641   SDValue Result;
7642
7643   if (Subtarget->hasSSE3()) {
7644     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7645     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7646   } else {
7647     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7648     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7649                                            S2F, 0x4E, DAG);
7650     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7651                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7652                          Sub);
7653   }
7654
7655   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7656                      DAG.getIntPtrConstant(0));
7657 }
7658
7659 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7660 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7661                                                SelectionDAG &DAG) const {
7662   DebugLoc dl = Op.getDebugLoc();
7663   // FP constant to bias correct the final result.
7664   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7665                                    MVT::f64);
7666
7667   // Load the 32-bit value into an XMM register.
7668   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7669                              Op.getOperand(0));
7670
7671   // Zero out the upper parts of the register.
7672   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7673
7674   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7675                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7676                      DAG.getIntPtrConstant(0));
7677
7678   // Or the load with the bias.
7679   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7680                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7681                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7682                                                    MVT::v2f64, Load)),
7683                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7684                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7685                                                    MVT::v2f64, Bias)));
7686   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7687                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7688                    DAG.getIntPtrConstant(0));
7689
7690   // Subtract the bias.
7691   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7692
7693   // Handle final rounding.
7694   EVT DestVT = Op.getValueType();
7695
7696   if (DestVT.bitsLT(MVT::f64))
7697     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7698                        DAG.getIntPtrConstant(0));
7699   if (DestVT.bitsGT(MVT::f64))
7700     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7701
7702   // Handle final rounding.
7703   return Sub;
7704 }
7705
7706 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7707                                            SelectionDAG &DAG) const {
7708   SDValue N0 = Op.getOperand(0);
7709   DebugLoc dl = Op.getDebugLoc();
7710
7711   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7712   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7713   // the optimization here.
7714   if (DAG.SignBitIsZero(N0))
7715     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7716
7717   EVT SrcVT = N0.getValueType();
7718   EVT DstVT = Op.getValueType();
7719   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7720     return LowerUINT_TO_FP_i64(Op, DAG);
7721   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7722     return LowerUINT_TO_FP_i32(Op, DAG);
7723   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7724     return SDValue();
7725
7726   // Make a 64-bit buffer, and use it to build an FILD.
7727   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7728   if (SrcVT == MVT::i32) {
7729     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7730     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7731                                      getPointerTy(), StackSlot, WordOff);
7732     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7733                                   StackSlot, MachinePointerInfo(),
7734                                   false, false, 0);
7735     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7736                                   OffsetSlot, MachinePointerInfo(),
7737                                   false, false, 0);
7738     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7739     return Fild;
7740   }
7741
7742   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7743   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7744                                StackSlot, MachinePointerInfo(),
7745                                false, false, 0);
7746   // For i64 source, we need to add the appropriate power of 2 if the input
7747   // was negative.  This is the same as the optimization in
7748   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7749   // we must be careful to do the computation in x87 extended precision, not
7750   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7751   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7752   MachineMemOperand *MMO =
7753     DAG.getMachineFunction()
7754     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7755                           MachineMemOperand::MOLoad, 8, 8);
7756
7757   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7758   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7759   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7760                                          MVT::i64, MMO);
7761
7762   APInt FF(32, 0x5F800000ULL);
7763
7764   // Check whether the sign bit is set.
7765   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7766                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7767                                  ISD::SETLT);
7768
7769   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7770   SDValue FudgePtr = DAG.getConstantPool(
7771                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7772                                          getPointerTy());
7773
7774   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7775   SDValue Zero = DAG.getIntPtrConstant(0);
7776   SDValue Four = DAG.getIntPtrConstant(4);
7777   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7778                                Zero, Four);
7779   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7780
7781   // Load the value out, extending it from f32 to f80.
7782   // FIXME: Avoid the extend by constructing the right constant pool?
7783   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7784                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7785                                  MVT::f32, false, false, 4);
7786   // Extend everything to 80 bits to force it to be done on x87.
7787   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7788   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7789 }
7790
7791 std::pair<SDValue,SDValue> X86TargetLowering::
7792 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7793   DebugLoc DL = Op.getDebugLoc();
7794
7795   EVT DstTy = Op.getValueType();
7796
7797   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7798     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7799     DstTy = MVT::i64;
7800   }
7801
7802   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7803          DstTy.getSimpleVT() >= MVT::i16 &&
7804          "Unknown FP_TO_INT to lower!");
7805
7806   // These are really Legal.
7807   if (DstTy == MVT::i32 &&
7808       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7809     return std::make_pair(SDValue(), SDValue());
7810   if (Subtarget->is64Bit() &&
7811       DstTy == MVT::i64 &&
7812       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7813     return std::make_pair(SDValue(), SDValue());
7814
7815   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7816   // stack slot, or into the FTOL runtime function.
7817   MachineFunction &MF = DAG.getMachineFunction();
7818   unsigned MemSize = DstTy.getSizeInBits()/8;
7819   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7820   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7821
7822   unsigned Opc;
7823   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7824     Opc = X86ISD::WIN_FTOL;
7825   else
7826     switch (DstTy.getSimpleVT().SimpleTy) {
7827     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7828     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7829     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7830     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7831     }
7832
7833   SDValue Chain = DAG.getEntryNode();
7834   SDValue Value = Op.getOperand(0);
7835   EVT TheVT = Op.getOperand(0).getValueType();
7836   // FIXME This causes a redundant load/store if the SSE-class value is already
7837   // in memory, such as if it is on the callstack.
7838   if (isScalarFPTypeInSSEReg(TheVT)) {
7839     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7840     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7841                          MachinePointerInfo::getFixedStack(SSFI),
7842                          false, false, 0);
7843     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7844     SDValue Ops[] = {
7845       Chain, StackSlot, DAG.getValueType(TheVT)
7846     };
7847
7848     MachineMemOperand *MMO =
7849       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7850                               MachineMemOperand::MOLoad, MemSize, MemSize);
7851     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7852                                     DstTy, MMO);
7853     Chain = Value.getValue(1);
7854     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7855     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7856   }
7857
7858   MachineMemOperand *MMO =
7859     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7860                             MachineMemOperand::MOStore, MemSize, MemSize);
7861
7862   if (Opc != X86ISD::WIN_FTOL) {
7863     // Build the FP_TO_INT*_IN_MEM
7864     SDValue Ops[] = { Chain, Value, StackSlot };
7865     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7866                                            Ops, 3, DstTy, MMO);
7867     return std::make_pair(FIST, StackSlot);
7868   } else {
7869     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
7870       DAG.getVTList(MVT::Other, MVT::Glue),
7871       Chain, Value);
7872     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
7873       MVT::i32, ftol.getValue(1));
7874     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
7875       MVT::i32, eax.getValue(2));
7876     SDValue Ops[] = { eax, edx };
7877     SDValue pair = IsReplace
7878       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
7879       : DAG.getMergeValues(Ops, 2, DL);
7880     return std::make_pair(pair, SDValue());
7881   }
7882 }
7883
7884 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7885                                            SelectionDAG &DAG) const {
7886   if (Op.getValueType().isVector())
7887     return SDValue();
7888
7889   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7890     /*IsSigned=*/ true, /*IsReplace=*/ false);
7891   SDValue FIST = Vals.first, StackSlot = Vals.second;
7892   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7893   if (FIST.getNode() == 0) return Op;
7894
7895   if (StackSlot.getNode())
7896     // Load the result.
7897     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7898                        FIST, StackSlot, MachinePointerInfo(),
7899                        false, false, false, 0);
7900
7901   // The node is the result.
7902   return FIST;
7903 }
7904
7905 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7906                                            SelectionDAG &DAG) const {
7907   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7908     /*IsSigned=*/ false, /*IsReplace=*/ false);
7909   SDValue FIST = Vals.first, StackSlot = Vals.second;
7910   assert(FIST.getNode() && "Unexpected failure");
7911
7912   if (StackSlot.getNode())
7913     // Load the result.
7914     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7915                        FIST, StackSlot, MachinePointerInfo(),
7916                        false, false, false, 0);
7917
7918   // The node is the result.
7919   return FIST;
7920 }
7921
7922 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7923                                      SelectionDAG &DAG) const {
7924   LLVMContext *Context = DAG.getContext();
7925   DebugLoc dl = Op.getDebugLoc();
7926   EVT VT = Op.getValueType();
7927   EVT EltVT = VT;
7928   if (VT.isVector())
7929     EltVT = VT.getVectorElementType();
7930   Constant *C;
7931   if (EltVT == MVT::f64) {
7932     C = ConstantVector::getSplat(2, 
7933                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7934   } else {
7935     C = ConstantVector::getSplat(4,
7936                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7937   }
7938   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7939   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7940                              MachinePointerInfo::getConstantPool(),
7941                              false, false, false, 16);
7942   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7943 }
7944
7945 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7946   LLVMContext *Context = DAG.getContext();
7947   DebugLoc dl = Op.getDebugLoc();
7948   EVT VT = Op.getValueType();
7949   EVT EltVT = VT;
7950   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7951   if (VT.isVector()) {
7952     EltVT = VT.getVectorElementType();
7953     NumElts = VT.getVectorNumElements();
7954   }
7955   Constant *C;
7956   if (EltVT == MVT::f64)
7957     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7958   else
7959     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7960   C = ConstantVector::getSplat(NumElts, C);
7961   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7962   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7963                              MachinePointerInfo::getConstantPool(),
7964                              false, false, false, 16);
7965   if (VT.isVector()) {
7966     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7967     return DAG.getNode(ISD::BITCAST, dl, VT,
7968                        DAG.getNode(ISD::XOR, dl, XORVT,
7969                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
7970                                                Op.getOperand(0)),
7971                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7972   }
7973
7974   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7975 }
7976
7977 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7978   LLVMContext *Context = DAG.getContext();
7979   SDValue Op0 = Op.getOperand(0);
7980   SDValue Op1 = Op.getOperand(1);
7981   DebugLoc dl = Op.getDebugLoc();
7982   EVT VT = Op.getValueType();
7983   EVT SrcVT = Op1.getValueType();
7984
7985   // If second operand is smaller, extend it first.
7986   if (SrcVT.bitsLT(VT)) {
7987     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7988     SrcVT = VT;
7989   }
7990   // And if it is bigger, shrink it first.
7991   if (SrcVT.bitsGT(VT)) {
7992     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7993     SrcVT = VT;
7994   }
7995
7996   // At this point the operands and the result should have the same
7997   // type, and that won't be f80 since that is not custom lowered.
7998
7999   // First get the sign bit of second operand.
8000   SmallVector<Constant*,4> CV;
8001   if (SrcVT == MVT::f64) {
8002     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8003     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8004   } else {
8005     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8006     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8007     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8008     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8009   }
8010   Constant *C = ConstantVector::get(CV);
8011   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8012   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8013                               MachinePointerInfo::getConstantPool(),
8014                               false, false, false, 16);
8015   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8016
8017   // Shift sign bit right or left if the two operands have different types.
8018   if (SrcVT.bitsGT(VT)) {
8019     // Op0 is MVT::f32, Op1 is MVT::f64.
8020     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8021     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8022                           DAG.getConstant(32, MVT::i32));
8023     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8024     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8025                           DAG.getIntPtrConstant(0));
8026   }
8027
8028   // Clear first operand sign bit.
8029   CV.clear();
8030   if (VT == MVT::f64) {
8031     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8032     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8033   } else {
8034     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8035     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8036     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8037     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8038   }
8039   C = ConstantVector::get(CV);
8040   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8041   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8042                               MachinePointerInfo::getConstantPool(),
8043                               false, false, false, 16);
8044   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8045
8046   // Or the value with the sign bit.
8047   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8048 }
8049
8050 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8051   SDValue N0 = Op.getOperand(0);
8052   DebugLoc dl = Op.getDebugLoc();
8053   EVT VT = Op.getValueType();
8054
8055   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8056   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8057                                   DAG.getConstant(1, VT));
8058   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8059 }
8060
8061 /// Emit nodes that will be selected as "test Op0,Op0", or something
8062 /// equivalent.
8063 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8064                                     SelectionDAG &DAG) const {
8065   DebugLoc dl = Op.getDebugLoc();
8066
8067   // CF and OF aren't always set the way we want. Determine which
8068   // of these we need.
8069   bool NeedCF = false;
8070   bool NeedOF = false;
8071   switch (X86CC) {
8072   default: break;
8073   case X86::COND_A: case X86::COND_AE:
8074   case X86::COND_B: case X86::COND_BE:
8075     NeedCF = true;
8076     break;
8077   case X86::COND_G: case X86::COND_GE:
8078   case X86::COND_L: case X86::COND_LE:
8079   case X86::COND_O: case X86::COND_NO:
8080     NeedOF = true;
8081     break;
8082   }
8083
8084   // See if we can use the EFLAGS value from the operand instead of
8085   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8086   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8087   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8088     // Emit a CMP with 0, which is the TEST pattern.
8089     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8090                        DAG.getConstant(0, Op.getValueType()));
8091
8092   unsigned Opcode = 0;
8093   unsigned NumOperands = 0;
8094   switch (Op.getNode()->getOpcode()) {
8095   case ISD::ADD:
8096     // Due to an isel shortcoming, be conservative if this add is likely to be
8097     // selected as part of a load-modify-store instruction. When the root node
8098     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8099     // uses of other nodes in the match, such as the ADD in this case. This
8100     // leads to the ADD being left around and reselected, with the result being
8101     // two adds in the output.  Alas, even if none our users are stores, that
8102     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8103     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8104     // climbing the DAG back to the root, and it doesn't seem to be worth the
8105     // effort.
8106     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8107          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8108       if (UI->getOpcode() != ISD::CopyToReg &&
8109           UI->getOpcode() != ISD::SETCC &&
8110           UI->getOpcode() != ISD::STORE)
8111         goto default_case;
8112
8113     if (ConstantSDNode *C =
8114         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8115       // An add of one will be selected as an INC.
8116       if (C->getAPIntValue() == 1) {
8117         Opcode = X86ISD::INC;
8118         NumOperands = 1;
8119         break;
8120       }
8121
8122       // An add of negative one (subtract of one) will be selected as a DEC.
8123       if (C->getAPIntValue().isAllOnesValue()) {
8124         Opcode = X86ISD::DEC;
8125         NumOperands = 1;
8126         break;
8127       }
8128     }
8129
8130     // Otherwise use a regular EFLAGS-setting add.
8131     Opcode = X86ISD::ADD;
8132     NumOperands = 2;
8133     break;
8134   case ISD::AND: {
8135     // If the primary and result isn't used, don't bother using X86ISD::AND,
8136     // because a TEST instruction will be better.
8137     bool NonFlagUse = false;
8138     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8139            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8140       SDNode *User = *UI;
8141       unsigned UOpNo = UI.getOperandNo();
8142       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8143         // Look pass truncate.
8144         UOpNo = User->use_begin().getOperandNo();
8145         User = *User->use_begin();
8146       }
8147
8148       if (User->getOpcode() != ISD::BRCOND &&
8149           User->getOpcode() != ISD::SETCC &&
8150           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8151         NonFlagUse = true;
8152         break;
8153       }
8154     }
8155
8156     if (!NonFlagUse)
8157       break;
8158   }
8159     // FALL THROUGH
8160   case ISD::SUB:
8161   case ISD::OR:
8162   case ISD::XOR:
8163     // Due to the ISEL shortcoming noted above, be conservative if this op is
8164     // likely to be selected as part of a load-modify-store instruction.
8165     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8166            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8167       if (UI->getOpcode() == ISD::STORE)
8168         goto default_case;
8169
8170     // Otherwise use a regular EFLAGS-setting instruction.
8171     switch (Op.getNode()->getOpcode()) {
8172     default: llvm_unreachable("unexpected operator!");
8173     case ISD::SUB: Opcode = X86ISD::SUB; break;
8174     case ISD::OR:  Opcode = X86ISD::OR;  break;
8175     case ISD::XOR: Opcode = X86ISD::XOR; break;
8176     case ISD::AND: Opcode = X86ISD::AND; break;
8177     }
8178
8179     NumOperands = 2;
8180     break;
8181   case X86ISD::ADD:
8182   case X86ISD::SUB:
8183   case X86ISD::INC:
8184   case X86ISD::DEC:
8185   case X86ISD::OR:
8186   case X86ISD::XOR:
8187   case X86ISD::AND:
8188     return SDValue(Op.getNode(), 1);
8189   default:
8190   default_case:
8191     break;
8192   }
8193
8194   if (Opcode == 0)
8195     // Emit a CMP with 0, which is the TEST pattern.
8196     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8197                        DAG.getConstant(0, Op.getValueType()));
8198
8199   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8200   SmallVector<SDValue, 4> Ops;
8201   for (unsigned i = 0; i != NumOperands; ++i)
8202     Ops.push_back(Op.getOperand(i));
8203
8204   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8205   DAG.ReplaceAllUsesWith(Op, New);
8206   return SDValue(New.getNode(), 1);
8207 }
8208
8209 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8210 /// equivalent.
8211 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8212                                    SelectionDAG &DAG) const {
8213   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8214     if (C->getAPIntValue() == 0)
8215       return EmitTest(Op0, X86CC, DAG);
8216
8217   DebugLoc dl = Op0.getDebugLoc();
8218   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8219 }
8220
8221 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8222 /// if it's possible.
8223 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8224                                      DebugLoc dl, SelectionDAG &DAG) const {
8225   SDValue Op0 = And.getOperand(0);
8226   SDValue Op1 = And.getOperand(1);
8227   if (Op0.getOpcode() == ISD::TRUNCATE)
8228     Op0 = Op0.getOperand(0);
8229   if (Op1.getOpcode() == ISD::TRUNCATE)
8230     Op1 = Op1.getOperand(0);
8231
8232   SDValue LHS, RHS;
8233   if (Op1.getOpcode() == ISD::SHL)
8234     std::swap(Op0, Op1);
8235   if (Op0.getOpcode() == ISD::SHL) {
8236     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8237       if (And00C->getZExtValue() == 1) {
8238         // If we looked past a truncate, check that it's only truncating away
8239         // known zeros.
8240         unsigned BitWidth = Op0.getValueSizeInBits();
8241         unsigned AndBitWidth = And.getValueSizeInBits();
8242         if (BitWidth > AndBitWidth) {
8243           APInt Zeros, Ones;
8244           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8245           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8246             return SDValue();
8247         }
8248         LHS = Op1;
8249         RHS = Op0.getOperand(1);
8250       }
8251   } else if (Op1.getOpcode() == ISD::Constant) {
8252     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8253     uint64_t AndRHSVal = AndRHS->getZExtValue();
8254     SDValue AndLHS = Op0;
8255
8256     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8257       LHS = AndLHS.getOperand(0);
8258       RHS = AndLHS.getOperand(1);
8259     }
8260
8261     // Use BT if the immediate can't be encoded in a TEST instruction.
8262     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8263       LHS = AndLHS;
8264       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8265     }
8266   }
8267
8268   if (LHS.getNode()) {
8269     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8270     // instruction.  Since the shift amount is in-range-or-undefined, we know
8271     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8272     // the encoding for the i16 version is larger than the i32 version.
8273     // Also promote i16 to i32 for performance / code size reason.
8274     if (LHS.getValueType() == MVT::i8 ||
8275         LHS.getValueType() == MVT::i16)
8276       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8277
8278     // If the operand types disagree, extend the shift amount to match.  Since
8279     // BT ignores high bits (like shifts) we can use anyextend.
8280     if (LHS.getValueType() != RHS.getValueType())
8281       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8282
8283     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8284     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8285     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8286                        DAG.getConstant(Cond, MVT::i8), BT);
8287   }
8288
8289   return SDValue();
8290 }
8291
8292 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8293
8294   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8295
8296   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8297   SDValue Op0 = Op.getOperand(0);
8298   SDValue Op1 = Op.getOperand(1);
8299   DebugLoc dl = Op.getDebugLoc();
8300   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8301
8302   // Optimize to BT if possible.
8303   // Lower (X & (1 << N)) == 0 to BT(X, N).
8304   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8305   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8306   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8307       Op1.getOpcode() == ISD::Constant &&
8308       cast<ConstantSDNode>(Op1)->isNullValue() &&
8309       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8310     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8311     if (NewSetCC.getNode())
8312       return NewSetCC;
8313   }
8314
8315   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8316   // these.
8317   if (Op1.getOpcode() == ISD::Constant &&
8318       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8319        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8320       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8321
8322     // If the input is a setcc, then reuse the input setcc or use a new one with
8323     // the inverted condition.
8324     if (Op0.getOpcode() == X86ISD::SETCC) {
8325       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8326       bool Invert = (CC == ISD::SETNE) ^
8327         cast<ConstantSDNode>(Op1)->isNullValue();
8328       if (!Invert) return Op0;
8329
8330       CCode = X86::GetOppositeBranchCondition(CCode);
8331       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8332                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8333     }
8334   }
8335
8336   bool isFP = Op1.getValueType().isFloatingPoint();
8337   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8338   if (X86CC == X86::COND_INVALID)
8339     return SDValue();
8340
8341   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8342   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8343                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8344 }
8345
8346 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8347 // ones, and then concatenate the result back.
8348 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8349   EVT VT = Op.getValueType();
8350
8351   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8352          "Unsupported value type for operation");
8353
8354   int NumElems = VT.getVectorNumElements();
8355   DebugLoc dl = Op.getDebugLoc();
8356   SDValue CC = Op.getOperand(2);
8357
8358   // Extract the LHS vectors
8359   SDValue LHS = Op.getOperand(0);
8360   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8361   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8362
8363   // Extract the RHS vectors
8364   SDValue RHS = Op.getOperand(1);
8365   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8366   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8367
8368   // Issue the operation on the smaller types and concatenate the result back
8369   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8370   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8371   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8372                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8373                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8374 }
8375
8376
8377 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8378   SDValue Cond;
8379   SDValue Op0 = Op.getOperand(0);
8380   SDValue Op1 = Op.getOperand(1);
8381   SDValue CC = Op.getOperand(2);
8382   EVT VT = Op.getValueType();
8383   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8384   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8385   DebugLoc dl = Op.getDebugLoc();
8386
8387   if (isFP) {
8388     unsigned SSECC = 8;
8389     EVT EltVT = Op0.getValueType().getVectorElementType();
8390     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8391
8392     bool Swap = false;
8393
8394     // SSE Condition code mapping:
8395     //  0 - EQ
8396     //  1 - LT
8397     //  2 - LE
8398     //  3 - UNORD
8399     //  4 - NEQ
8400     //  5 - NLT
8401     //  6 - NLE
8402     //  7 - ORD
8403     switch (SetCCOpcode) {
8404     default: break;
8405     case ISD::SETOEQ:
8406     case ISD::SETEQ:  SSECC = 0; break;
8407     case ISD::SETOGT:
8408     case ISD::SETGT: Swap = true; // Fallthrough
8409     case ISD::SETLT:
8410     case ISD::SETOLT: SSECC = 1; break;
8411     case ISD::SETOGE:
8412     case ISD::SETGE: Swap = true; // Fallthrough
8413     case ISD::SETLE:
8414     case ISD::SETOLE: SSECC = 2; break;
8415     case ISD::SETUO:  SSECC = 3; break;
8416     case ISD::SETUNE:
8417     case ISD::SETNE:  SSECC = 4; break;
8418     case ISD::SETULE: Swap = true;
8419     case ISD::SETUGE: SSECC = 5; break;
8420     case ISD::SETULT: Swap = true;
8421     case ISD::SETUGT: SSECC = 6; break;
8422     case ISD::SETO:   SSECC = 7; break;
8423     }
8424     if (Swap)
8425       std::swap(Op0, Op1);
8426
8427     // In the two special cases we can't handle, emit two comparisons.
8428     if (SSECC == 8) {
8429       if (SetCCOpcode == ISD::SETUEQ) {
8430         SDValue UNORD, EQ;
8431         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8432                             DAG.getConstant(3, MVT::i8));
8433         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8434                          DAG.getConstant(0, MVT::i8));
8435         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8436       }
8437       if (SetCCOpcode == ISD::SETONE) {
8438         SDValue ORD, NEQ;
8439         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8440                           DAG.getConstant(7, MVT::i8));
8441         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8442                           DAG.getConstant(4, MVT::i8));
8443         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8444       }
8445       llvm_unreachable("Illegal FP comparison");
8446     }
8447     // Handle all other FP comparisons here.
8448     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8449                        DAG.getConstant(SSECC, MVT::i8));
8450   }
8451
8452   // Break 256-bit integer vector compare into smaller ones.
8453   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8454     return Lower256IntVSETCC(Op, DAG);
8455
8456   // We are handling one of the integer comparisons here.  Since SSE only has
8457   // GT and EQ comparisons for integer, swapping operands and multiple
8458   // operations may be required for some comparisons.
8459   unsigned Opc = 0;
8460   bool Swap = false, Invert = false, FlipSigns = false;
8461
8462   switch (SetCCOpcode) {
8463   default: break;
8464   case ISD::SETNE:  Invert = true;
8465   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8466   case ISD::SETLT:  Swap = true;
8467   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8468   case ISD::SETGE:  Swap = true;
8469   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8470   case ISD::SETULT: Swap = true;
8471   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8472   case ISD::SETUGE: Swap = true;
8473   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8474   }
8475   if (Swap)
8476     std::swap(Op0, Op1);
8477
8478   // Check that the operation in question is available (most are plain SSE2,
8479   // but PCMPGTQ and PCMPEQQ have different requirements).
8480   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8481     return SDValue();
8482   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8483     return SDValue();
8484
8485   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8486   // bits of the inputs before performing those operations.
8487   if (FlipSigns) {
8488     EVT EltVT = VT.getVectorElementType();
8489     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8490                                       EltVT);
8491     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8492     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8493                                     SignBits.size());
8494     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8495     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8496   }
8497
8498   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8499
8500   // If the logical-not of the result is required, perform that now.
8501   if (Invert)
8502     Result = DAG.getNOT(dl, Result, VT);
8503
8504   return Result;
8505 }
8506
8507 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8508 static bool isX86LogicalCmp(SDValue Op) {
8509   unsigned Opc = Op.getNode()->getOpcode();
8510   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8511     return true;
8512   if (Op.getResNo() == 1 &&
8513       (Opc == X86ISD::ADD ||
8514        Opc == X86ISD::SUB ||
8515        Opc == X86ISD::ADC ||
8516        Opc == X86ISD::SBB ||
8517        Opc == X86ISD::SMUL ||
8518        Opc == X86ISD::UMUL ||
8519        Opc == X86ISD::INC ||
8520        Opc == X86ISD::DEC ||
8521        Opc == X86ISD::OR ||
8522        Opc == X86ISD::XOR ||
8523        Opc == X86ISD::AND))
8524     return true;
8525
8526   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8527     return true;
8528
8529   return false;
8530 }
8531
8532 static bool isZero(SDValue V) {
8533   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8534   return C && C->isNullValue();
8535 }
8536
8537 static bool isAllOnes(SDValue V) {
8538   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8539   return C && C->isAllOnesValue();
8540 }
8541
8542 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8543   bool addTest = true;
8544   SDValue Cond  = Op.getOperand(0);
8545   SDValue Op1 = Op.getOperand(1);
8546   SDValue Op2 = Op.getOperand(2);
8547   DebugLoc DL = Op.getDebugLoc();
8548   SDValue CC;
8549
8550   if (Cond.getOpcode() == ISD::SETCC) {
8551     SDValue NewCond = LowerSETCC(Cond, DAG);
8552     if (NewCond.getNode())
8553       Cond = NewCond;
8554   }
8555
8556   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8557   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8558   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8559   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8560   if (Cond.getOpcode() == X86ISD::SETCC &&
8561       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8562       isZero(Cond.getOperand(1).getOperand(1))) {
8563     SDValue Cmp = Cond.getOperand(1);
8564
8565     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8566
8567     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8568         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8569       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8570
8571       SDValue CmpOp0 = Cmp.getOperand(0);
8572       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8573                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8574
8575       SDValue Res =   // Res = 0 or -1.
8576         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8577                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8578
8579       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8580         Res = DAG.getNOT(DL, Res, Res.getValueType());
8581
8582       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8583       if (N2C == 0 || !N2C->isNullValue())
8584         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8585       return Res;
8586     }
8587   }
8588
8589   // Look past (and (setcc_carry (cmp ...)), 1).
8590   if (Cond.getOpcode() == ISD::AND &&
8591       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8592     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8593     if (C && C->getAPIntValue() == 1)
8594       Cond = Cond.getOperand(0);
8595   }
8596
8597   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8598   // setting operand in place of the X86ISD::SETCC.
8599   unsigned CondOpcode = Cond.getOpcode();
8600   if (CondOpcode == X86ISD::SETCC ||
8601       CondOpcode == X86ISD::SETCC_CARRY) {
8602     CC = Cond.getOperand(0);
8603
8604     SDValue Cmp = Cond.getOperand(1);
8605     unsigned Opc = Cmp.getOpcode();
8606     EVT VT = Op.getValueType();
8607
8608     bool IllegalFPCMov = false;
8609     if (VT.isFloatingPoint() && !VT.isVector() &&
8610         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8611       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8612
8613     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8614         Opc == X86ISD::BT) { // FIXME
8615       Cond = Cmp;
8616       addTest = false;
8617     }
8618   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8619              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8620              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8621               Cond.getOperand(0).getValueType() != MVT::i8)) {
8622     SDValue LHS = Cond.getOperand(0);
8623     SDValue RHS = Cond.getOperand(1);
8624     unsigned X86Opcode;
8625     unsigned X86Cond;
8626     SDVTList VTs;
8627     switch (CondOpcode) {
8628     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8629     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8630     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8631     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8632     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8633     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8634     default: llvm_unreachable("unexpected overflowing operator");
8635     }
8636     if (CondOpcode == ISD::UMULO)
8637       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8638                           MVT::i32);
8639     else
8640       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8641
8642     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8643
8644     if (CondOpcode == ISD::UMULO)
8645       Cond = X86Op.getValue(2);
8646     else
8647       Cond = X86Op.getValue(1);
8648
8649     CC = DAG.getConstant(X86Cond, MVT::i8);
8650     addTest = false;
8651   }
8652
8653   if (addTest) {
8654     // Look pass the truncate.
8655     if (Cond.getOpcode() == ISD::TRUNCATE)
8656       Cond = Cond.getOperand(0);
8657
8658     // We know the result of AND is compared against zero. Try to match
8659     // it to BT.
8660     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8661       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8662       if (NewSetCC.getNode()) {
8663         CC = NewSetCC.getOperand(0);
8664         Cond = NewSetCC.getOperand(1);
8665         addTest = false;
8666       }
8667     }
8668   }
8669
8670   if (addTest) {
8671     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8672     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8673   }
8674
8675   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8676   // a <  b ?  0 : -1 -> RES = setcc_carry
8677   // a >= b ? -1 :  0 -> RES = setcc_carry
8678   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8679   if (Cond.getOpcode() == X86ISD::CMP) {
8680     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8681
8682     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8683         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8684       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8685                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8686       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8687         return DAG.getNOT(DL, Res, Res.getValueType());
8688       return Res;
8689     }
8690   }
8691
8692   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8693   // condition is true.
8694   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8695   SDValue Ops[] = { Op2, Op1, CC, Cond };
8696   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8697 }
8698
8699 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8700 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8701 // from the AND / OR.
8702 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8703   Opc = Op.getOpcode();
8704   if (Opc != ISD::OR && Opc != ISD::AND)
8705     return false;
8706   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8707           Op.getOperand(0).hasOneUse() &&
8708           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8709           Op.getOperand(1).hasOneUse());
8710 }
8711
8712 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8713 // 1 and that the SETCC node has a single use.
8714 static bool isXor1OfSetCC(SDValue Op) {
8715   if (Op.getOpcode() != ISD::XOR)
8716     return false;
8717   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8718   if (N1C && N1C->getAPIntValue() == 1) {
8719     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8720       Op.getOperand(0).hasOneUse();
8721   }
8722   return false;
8723 }
8724
8725 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8726   bool addTest = true;
8727   SDValue Chain = Op.getOperand(0);
8728   SDValue Cond  = Op.getOperand(1);
8729   SDValue Dest  = Op.getOperand(2);
8730   DebugLoc dl = Op.getDebugLoc();
8731   SDValue CC;
8732   bool Inverted = false;
8733
8734   if (Cond.getOpcode() == ISD::SETCC) {
8735     // Check for setcc([su]{add,sub,mul}o == 0).
8736     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8737         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8738         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8739         Cond.getOperand(0).getResNo() == 1 &&
8740         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8741          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8742          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8743          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8744          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8745          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8746       Inverted = true;
8747       Cond = Cond.getOperand(0);
8748     } else {
8749       SDValue NewCond = LowerSETCC(Cond, DAG);
8750       if (NewCond.getNode())
8751         Cond = NewCond;
8752     }
8753   }
8754 #if 0
8755   // FIXME: LowerXALUO doesn't handle these!!
8756   else if (Cond.getOpcode() == X86ISD::ADD  ||
8757            Cond.getOpcode() == X86ISD::SUB  ||
8758            Cond.getOpcode() == X86ISD::SMUL ||
8759            Cond.getOpcode() == X86ISD::UMUL)
8760     Cond = LowerXALUO(Cond, DAG);
8761 #endif
8762
8763   // Look pass (and (setcc_carry (cmp ...)), 1).
8764   if (Cond.getOpcode() == ISD::AND &&
8765       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8766     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8767     if (C && C->getAPIntValue() == 1)
8768       Cond = Cond.getOperand(0);
8769   }
8770
8771   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8772   // setting operand in place of the X86ISD::SETCC.
8773   unsigned CondOpcode = Cond.getOpcode();
8774   if (CondOpcode == X86ISD::SETCC ||
8775       CondOpcode == X86ISD::SETCC_CARRY) {
8776     CC = Cond.getOperand(0);
8777
8778     SDValue Cmp = Cond.getOperand(1);
8779     unsigned Opc = Cmp.getOpcode();
8780     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8781     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8782       Cond = Cmp;
8783       addTest = false;
8784     } else {
8785       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8786       default: break;
8787       case X86::COND_O:
8788       case X86::COND_B:
8789         // These can only come from an arithmetic instruction with overflow,
8790         // e.g. SADDO, UADDO.
8791         Cond = Cond.getNode()->getOperand(1);
8792         addTest = false;
8793         break;
8794       }
8795     }
8796   }
8797   CondOpcode = Cond.getOpcode();
8798   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8799       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8800       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8801        Cond.getOperand(0).getValueType() != MVT::i8)) {
8802     SDValue LHS = Cond.getOperand(0);
8803     SDValue RHS = Cond.getOperand(1);
8804     unsigned X86Opcode;
8805     unsigned X86Cond;
8806     SDVTList VTs;
8807     switch (CondOpcode) {
8808     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8809     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8810     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8811     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8812     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8813     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8814     default: llvm_unreachable("unexpected overflowing operator");
8815     }
8816     if (Inverted)
8817       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8818     if (CondOpcode == ISD::UMULO)
8819       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8820                           MVT::i32);
8821     else
8822       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8823
8824     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8825
8826     if (CondOpcode == ISD::UMULO)
8827       Cond = X86Op.getValue(2);
8828     else
8829       Cond = X86Op.getValue(1);
8830
8831     CC = DAG.getConstant(X86Cond, MVT::i8);
8832     addTest = false;
8833   } else {
8834     unsigned CondOpc;
8835     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8836       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8837       if (CondOpc == ISD::OR) {
8838         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8839         // two branches instead of an explicit OR instruction with a
8840         // separate test.
8841         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8842             isX86LogicalCmp(Cmp)) {
8843           CC = Cond.getOperand(0).getOperand(0);
8844           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8845                               Chain, Dest, CC, Cmp);
8846           CC = Cond.getOperand(1).getOperand(0);
8847           Cond = Cmp;
8848           addTest = false;
8849         }
8850       } else { // ISD::AND
8851         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8852         // two branches instead of an explicit AND instruction with a
8853         // separate test. However, we only do this if this block doesn't
8854         // have a fall-through edge, because this requires an explicit
8855         // jmp when the condition is false.
8856         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8857             isX86LogicalCmp(Cmp) &&
8858             Op.getNode()->hasOneUse()) {
8859           X86::CondCode CCode =
8860             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8861           CCode = X86::GetOppositeBranchCondition(CCode);
8862           CC = DAG.getConstant(CCode, MVT::i8);
8863           SDNode *User = *Op.getNode()->use_begin();
8864           // Look for an unconditional branch following this conditional branch.
8865           // We need this because we need to reverse the successors in order
8866           // to implement FCMP_OEQ.
8867           if (User->getOpcode() == ISD::BR) {
8868             SDValue FalseBB = User->getOperand(1);
8869             SDNode *NewBR =
8870               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8871             assert(NewBR == User);
8872             (void)NewBR;
8873             Dest = FalseBB;
8874
8875             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8876                                 Chain, Dest, CC, Cmp);
8877             X86::CondCode CCode =
8878               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8879             CCode = X86::GetOppositeBranchCondition(CCode);
8880             CC = DAG.getConstant(CCode, MVT::i8);
8881             Cond = Cmp;
8882             addTest = false;
8883           }
8884         }
8885       }
8886     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8887       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8888       // It should be transformed during dag combiner except when the condition
8889       // is set by a arithmetics with overflow node.
8890       X86::CondCode CCode =
8891         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8892       CCode = X86::GetOppositeBranchCondition(CCode);
8893       CC = DAG.getConstant(CCode, MVT::i8);
8894       Cond = Cond.getOperand(0).getOperand(1);
8895       addTest = false;
8896     } else if (Cond.getOpcode() == ISD::SETCC &&
8897                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8898       // For FCMP_OEQ, we can emit
8899       // two branches instead of an explicit AND instruction with a
8900       // separate test. However, we only do this if this block doesn't
8901       // have a fall-through edge, because this requires an explicit
8902       // jmp when the condition is false.
8903       if (Op.getNode()->hasOneUse()) {
8904         SDNode *User = *Op.getNode()->use_begin();
8905         // Look for an unconditional branch following this conditional branch.
8906         // We need this because we need to reverse the successors in order
8907         // to implement FCMP_OEQ.
8908         if (User->getOpcode() == ISD::BR) {
8909           SDValue FalseBB = User->getOperand(1);
8910           SDNode *NewBR =
8911             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8912           assert(NewBR == User);
8913           (void)NewBR;
8914           Dest = FalseBB;
8915
8916           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8917                                     Cond.getOperand(0), Cond.getOperand(1));
8918           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8919           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8920                               Chain, Dest, CC, Cmp);
8921           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8922           Cond = Cmp;
8923           addTest = false;
8924         }
8925       }
8926     } else if (Cond.getOpcode() == ISD::SETCC &&
8927                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8928       // For FCMP_UNE, we can emit
8929       // two branches instead of an explicit AND instruction with a
8930       // separate test. However, we only do this if this block doesn't
8931       // have a fall-through edge, because this requires an explicit
8932       // jmp when the condition is false.
8933       if (Op.getNode()->hasOneUse()) {
8934         SDNode *User = *Op.getNode()->use_begin();
8935         // Look for an unconditional branch following this conditional branch.
8936         // We need this because we need to reverse the successors in order
8937         // to implement FCMP_UNE.
8938         if (User->getOpcode() == ISD::BR) {
8939           SDValue FalseBB = User->getOperand(1);
8940           SDNode *NewBR =
8941             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8942           assert(NewBR == User);
8943           (void)NewBR;
8944
8945           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8946                                     Cond.getOperand(0), Cond.getOperand(1));
8947           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8948           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8949                               Chain, Dest, CC, Cmp);
8950           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8951           Cond = Cmp;
8952           addTest = false;
8953           Dest = FalseBB;
8954         }
8955       }
8956     }
8957   }
8958
8959   if (addTest) {
8960     // Look pass the truncate.
8961     if (Cond.getOpcode() == ISD::TRUNCATE)
8962       Cond = Cond.getOperand(0);
8963
8964     // We know the result of AND is compared against zero. Try to match
8965     // it to BT.
8966     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8967       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8968       if (NewSetCC.getNode()) {
8969         CC = NewSetCC.getOperand(0);
8970         Cond = NewSetCC.getOperand(1);
8971         addTest = false;
8972       }
8973     }
8974   }
8975
8976   if (addTest) {
8977     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8978     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8979   }
8980   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8981                      Chain, Dest, CC, Cond);
8982 }
8983
8984
8985 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8986 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8987 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8988 // that the guard pages used by the OS virtual memory manager are allocated in
8989 // correct sequence.
8990 SDValue
8991 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8992                                            SelectionDAG &DAG) const {
8993   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8994           getTargetMachine().Options.EnableSegmentedStacks) &&
8995          "This should be used only on Windows targets or when segmented stacks "
8996          "are being used");
8997   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8998   DebugLoc dl = Op.getDebugLoc();
8999
9000   // Get the inputs.
9001   SDValue Chain = Op.getOperand(0);
9002   SDValue Size  = Op.getOperand(1);
9003   // FIXME: Ensure alignment here
9004
9005   bool Is64Bit = Subtarget->is64Bit();
9006   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9007
9008   if (getTargetMachine().Options.EnableSegmentedStacks) {
9009     MachineFunction &MF = DAG.getMachineFunction();
9010     MachineRegisterInfo &MRI = MF.getRegInfo();
9011
9012     if (Is64Bit) {
9013       // The 64 bit implementation of segmented stacks needs to clobber both r10
9014       // r11. This makes it impossible to use it along with nested parameters.
9015       const Function *F = MF.getFunction();
9016
9017       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9018            I != E; I++)
9019         if (I->hasNestAttr())
9020           report_fatal_error("Cannot use segmented stacks with functions that "
9021                              "have nested arguments.");
9022     }
9023
9024     const TargetRegisterClass *AddrRegClass =
9025       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9026     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9027     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9028     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9029                                 DAG.getRegister(Vreg, SPTy));
9030     SDValue Ops1[2] = { Value, Chain };
9031     return DAG.getMergeValues(Ops1, 2, dl);
9032   } else {
9033     SDValue Flag;
9034     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9035
9036     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9037     Flag = Chain.getValue(1);
9038     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9039
9040     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9041     Flag = Chain.getValue(1);
9042
9043     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9044
9045     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9046     return DAG.getMergeValues(Ops1, 2, dl);
9047   }
9048 }
9049
9050 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9051   MachineFunction &MF = DAG.getMachineFunction();
9052   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9053
9054   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9055   DebugLoc DL = Op.getDebugLoc();
9056
9057   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9058     // vastart just stores the address of the VarArgsFrameIndex slot into the
9059     // memory location argument.
9060     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9061                                    getPointerTy());
9062     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9063                         MachinePointerInfo(SV), false, false, 0);
9064   }
9065
9066   // __va_list_tag:
9067   //   gp_offset         (0 - 6 * 8)
9068   //   fp_offset         (48 - 48 + 8 * 16)
9069   //   overflow_arg_area (point to parameters coming in memory).
9070   //   reg_save_area
9071   SmallVector<SDValue, 8> MemOps;
9072   SDValue FIN = Op.getOperand(1);
9073   // Store gp_offset
9074   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9075                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9076                                                MVT::i32),
9077                                FIN, MachinePointerInfo(SV), false, false, 0);
9078   MemOps.push_back(Store);
9079
9080   // Store fp_offset
9081   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9082                     FIN, DAG.getIntPtrConstant(4));
9083   Store = DAG.getStore(Op.getOperand(0), DL,
9084                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9085                                        MVT::i32),
9086                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9087   MemOps.push_back(Store);
9088
9089   // Store ptr to overflow_arg_area
9090   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9091                     FIN, DAG.getIntPtrConstant(4));
9092   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9093                                     getPointerTy());
9094   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9095                        MachinePointerInfo(SV, 8),
9096                        false, false, 0);
9097   MemOps.push_back(Store);
9098
9099   // Store ptr to reg_save_area.
9100   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9101                     FIN, DAG.getIntPtrConstant(8));
9102   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9103                                     getPointerTy());
9104   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9105                        MachinePointerInfo(SV, 16), false, false, 0);
9106   MemOps.push_back(Store);
9107   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9108                      &MemOps[0], MemOps.size());
9109 }
9110
9111 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9112   assert(Subtarget->is64Bit() &&
9113          "LowerVAARG only handles 64-bit va_arg!");
9114   assert((Subtarget->isTargetLinux() ||
9115           Subtarget->isTargetDarwin()) &&
9116           "Unhandled target in LowerVAARG");
9117   assert(Op.getNode()->getNumOperands() == 4);
9118   SDValue Chain = Op.getOperand(0);
9119   SDValue SrcPtr = Op.getOperand(1);
9120   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9121   unsigned Align = Op.getConstantOperandVal(3);
9122   DebugLoc dl = Op.getDebugLoc();
9123
9124   EVT ArgVT = Op.getNode()->getValueType(0);
9125   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9126   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9127   uint8_t ArgMode;
9128
9129   // Decide which area this value should be read from.
9130   // TODO: Implement the AMD64 ABI in its entirety. This simple
9131   // selection mechanism works only for the basic types.
9132   if (ArgVT == MVT::f80) {
9133     llvm_unreachable("va_arg for f80 not yet implemented");
9134   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9135     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9136   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9137     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9138   } else {
9139     llvm_unreachable("Unhandled argument type in LowerVAARG");
9140   }
9141
9142   if (ArgMode == 2) {
9143     // Sanity Check: Make sure using fp_offset makes sense.
9144     assert(!getTargetMachine().Options.UseSoftFloat &&
9145            !(DAG.getMachineFunction()
9146                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9147            Subtarget->hasSSE1());
9148   }
9149
9150   // Insert VAARG_64 node into the DAG
9151   // VAARG_64 returns two values: Variable Argument Address, Chain
9152   SmallVector<SDValue, 11> InstOps;
9153   InstOps.push_back(Chain);
9154   InstOps.push_back(SrcPtr);
9155   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9156   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9157   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9158   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9159   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9160                                           VTs, &InstOps[0], InstOps.size(),
9161                                           MVT::i64,
9162                                           MachinePointerInfo(SV),
9163                                           /*Align=*/0,
9164                                           /*Volatile=*/false,
9165                                           /*ReadMem=*/true,
9166                                           /*WriteMem=*/true);
9167   Chain = VAARG.getValue(1);
9168
9169   // Load the next argument and return it
9170   return DAG.getLoad(ArgVT, dl,
9171                      Chain,
9172                      VAARG,
9173                      MachinePointerInfo(),
9174                      false, false, false, 0);
9175 }
9176
9177 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9178   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9179   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9180   SDValue Chain = Op.getOperand(0);
9181   SDValue DstPtr = Op.getOperand(1);
9182   SDValue SrcPtr = Op.getOperand(2);
9183   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9184   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9185   DebugLoc DL = Op.getDebugLoc();
9186
9187   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9188                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9189                        false,
9190                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9191 }
9192
9193 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9194 // may or may not be a constant. Takes immediate version of shift as input.
9195 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9196                                    SDValue SrcOp, SDValue ShAmt,
9197                                    SelectionDAG &DAG) {
9198   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9199
9200   if (isa<ConstantSDNode>(ShAmt)) {
9201     switch (Opc) {
9202       default: llvm_unreachable("Unknown target vector shift node");
9203       case X86ISD::VSHLI:
9204       case X86ISD::VSRLI:
9205       case X86ISD::VSRAI:
9206         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9207     }
9208   }
9209
9210   // Change opcode to non-immediate version
9211   switch (Opc) {
9212     default: llvm_unreachable("Unknown target vector shift node");
9213     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9214     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9215     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9216   }
9217
9218   // Need to build a vector containing shift amount
9219   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9220   SDValue ShOps[4];
9221   ShOps[0] = ShAmt;
9222   ShOps[1] = DAG.getConstant(0, MVT::i32);
9223   ShOps[2] = DAG.getUNDEF(MVT::i32);
9224   ShOps[3] = DAG.getUNDEF(MVT::i32);
9225   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9226   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9227   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9228 }
9229
9230 SDValue
9231 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9232   DebugLoc dl = Op.getDebugLoc();
9233   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9234   switch (IntNo) {
9235   default: return SDValue();    // Don't custom lower most intrinsics.
9236   // Comparison intrinsics.
9237   case Intrinsic::x86_sse_comieq_ss:
9238   case Intrinsic::x86_sse_comilt_ss:
9239   case Intrinsic::x86_sse_comile_ss:
9240   case Intrinsic::x86_sse_comigt_ss:
9241   case Intrinsic::x86_sse_comige_ss:
9242   case Intrinsic::x86_sse_comineq_ss:
9243   case Intrinsic::x86_sse_ucomieq_ss:
9244   case Intrinsic::x86_sse_ucomilt_ss:
9245   case Intrinsic::x86_sse_ucomile_ss:
9246   case Intrinsic::x86_sse_ucomigt_ss:
9247   case Intrinsic::x86_sse_ucomige_ss:
9248   case Intrinsic::x86_sse_ucomineq_ss:
9249   case Intrinsic::x86_sse2_comieq_sd:
9250   case Intrinsic::x86_sse2_comilt_sd:
9251   case Intrinsic::x86_sse2_comile_sd:
9252   case Intrinsic::x86_sse2_comigt_sd:
9253   case Intrinsic::x86_sse2_comige_sd:
9254   case Intrinsic::x86_sse2_comineq_sd:
9255   case Intrinsic::x86_sse2_ucomieq_sd:
9256   case Intrinsic::x86_sse2_ucomilt_sd:
9257   case Intrinsic::x86_sse2_ucomile_sd:
9258   case Intrinsic::x86_sse2_ucomigt_sd:
9259   case Intrinsic::x86_sse2_ucomige_sd:
9260   case Intrinsic::x86_sse2_ucomineq_sd: {
9261     unsigned Opc = 0;
9262     ISD::CondCode CC = ISD::SETCC_INVALID;
9263     switch (IntNo) {
9264     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9265     case Intrinsic::x86_sse_comieq_ss:
9266     case Intrinsic::x86_sse2_comieq_sd:
9267       Opc = X86ISD::COMI;
9268       CC = ISD::SETEQ;
9269       break;
9270     case Intrinsic::x86_sse_comilt_ss:
9271     case Intrinsic::x86_sse2_comilt_sd:
9272       Opc = X86ISD::COMI;
9273       CC = ISD::SETLT;
9274       break;
9275     case Intrinsic::x86_sse_comile_ss:
9276     case Intrinsic::x86_sse2_comile_sd:
9277       Opc = X86ISD::COMI;
9278       CC = ISD::SETLE;
9279       break;
9280     case Intrinsic::x86_sse_comigt_ss:
9281     case Intrinsic::x86_sse2_comigt_sd:
9282       Opc = X86ISD::COMI;
9283       CC = ISD::SETGT;
9284       break;
9285     case Intrinsic::x86_sse_comige_ss:
9286     case Intrinsic::x86_sse2_comige_sd:
9287       Opc = X86ISD::COMI;
9288       CC = ISD::SETGE;
9289       break;
9290     case Intrinsic::x86_sse_comineq_ss:
9291     case Intrinsic::x86_sse2_comineq_sd:
9292       Opc = X86ISD::COMI;
9293       CC = ISD::SETNE;
9294       break;
9295     case Intrinsic::x86_sse_ucomieq_ss:
9296     case Intrinsic::x86_sse2_ucomieq_sd:
9297       Opc = X86ISD::UCOMI;
9298       CC = ISD::SETEQ;
9299       break;
9300     case Intrinsic::x86_sse_ucomilt_ss:
9301     case Intrinsic::x86_sse2_ucomilt_sd:
9302       Opc = X86ISD::UCOMI;
9303       CC = ISD::SETLT;
9304       break;
9305     case Intrinsic::x86_sse_ucomile_ss:
9306     case Intrinsic::x86_sse2_ucomile_sd:
9307       Opc = X86ISD::UCOMI;
9308       CC = ISD::SETLE;
9309       break;
9310     case Intrinsic::x86_sse_ucomigt_ss:
9311     case Intrinsic::x86_sse2_ucomigt_sd:
9312       Opc = X86ISD::UCOMI;
9313       CC = ISD::SETGT;
9314       break;
9315     case Intrinsic::x86_sse_ucomige_ss:
9316     case Intrinsic::x86_sse2_ucomige_sd:
9317       Opc = X86ISD::UCOMI;
9318       CC = ISD::SETGE;
9319       break;
9320     case Intrinsic::x86_sse_ucomineq_ss:
9321     case Intrinsic::x86_sse2_ucomineq_sd:
9322       Opc = X86ISD::UCOMI;
9323       CC = ISD::SETNE;
9324       break;
9325     }
9326
9327     SDValue LHS = Op.getOperand(1);
9328     SDValue RHS = Op.getOperand(2);
9329     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9330     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9331     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9332     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9333                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9334     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9335   }
9336   // XOP comparison intrinsics
9337   case Intrinsic::x86_xop_vpcomltb:
9338   case Intrinsic::x86_xop_vpcomltw:
9339   case Intrinsic::x86_xop_vpcomltd:
9340   case Intrinsic::x86_xop_vpcomltq:
9341   case Intrinsic::x86_xop_vpcomltub:
9342   case Intrinsic::x86_xop_vpcomltuw:
9343   case Intrinsic::x86_xop_vpcomltud:
9344   case Intrinsic::x86_xop_vpcomltuq:
9345   case Intrinsic::x86_xop_vpcomleb:
9346   case Intrinsic::x86_xop_vpcomlew:
9347   case Intrinsic::x86_xop_vpcomled:
9348   case Intrinsic::x86_xop_vpcomleq:
9349   case Intrinsic::x86_xop_vpcomleub:
9350   case Intrinsic::x86_xop_vpcomleuw:
9351   case Intrinsic::x86_xop_vpcomleud:
9352   case Intrinsic::x86_xop_vpcomleuq:
9353   case Intrinsic::x86_xop_vpcomgtb:
9354   case Intrinsic::x86_xop_vpcomgtw:
9355   case Intrinsic::x86_xop_vpcomgtd:
9356   case Intrinsic::x86_xop_vpcomgtq:
9357   case Intrinsic::x86_xop_vpcomgtub:
9358   case Intrinsic::x86_xop_vpcomgtuw:
9359   case Intrinsic::x86_xop_vpcomgtud:
9360   case Intrinsic::x86_xop_vpcomgtuq:
9361   case Intrinsic::x86_xop_vpcomgeb:
9362   case Intrinsic::x86_xop_vpcomgew:
9363   case Intrinsic::x86_xop_vpcomged:
9364   case Intrinsic::x86_xop_vpcomgeq:
9365   case Intrinsic::x86_xop_vpcomgeub:
9366   case Intrinsic::x86_xop_vpcomgeuw:
9367   case Intrinsic::x86_xop_vpcomgeud:
9368   case Intrinsic::x86_xop_vpcomgeuq:
9369   case Intrinsic::x86_xop_vpcomeqb:
9370   case Intrinsic::x86_xop_vpcomeqw:
9371   case Intrinsic::x86_xop_vpcomeqd:
9372   case Intrinsic::x86_xop_vpcomeqq:
9373   case Intrinsic::x86_xop_vpcomequb:
9374   case Intrinsic::x86_xop_vpcomequw:
9375   case Intrinsic::x86_xop_vpcomequd:
9376   case Intrinsic::x86_xop_vpcomequq:
9377   case Intrinsic::x86_xop_vpcomneb:
9378   case Intrinsic::x86_xop_vpcomnew:
9379   case Intrinsic::x86_xop_vpcomned:
9380   case Intrinsic::x86_xop_vpcomneq:
9381   case Intrinsic::x86_xop_vpcomneub:
9382   case Intrinsic::x86_xop_vpcomneuw:
9383   case Intrinsic::x86_xop_vpcomneud:
9384   case Intrinsic::x86_xop_vpcomneuq:
9385   case Intrinsic::x86_xop_vpcomfalseb:
9386   case Intrinsic::x86_xop_vpcomfalsew:
9387   case Intrinsic::x86_xop_vpcomfalsed:
9388   case Intrinsic::x86_xop_vpcomfalseq:
9389   case Intrinsic::x86_xop_vpcomfalseub:
9390   case Intrinsic::x86_xop_vpcomfalseuw:
9391   case Intrinsic::x86_xop_vpcomfalseud:
9392   case Intrinsic::x86_xop_vpcomfalseuq:
9393   case Intrinsic::x86_xop_vpcomtrueb:
9394   case Intrinsic::x86_xop_vpcomtruew:
9395   case Intrinsic::x86_xop_vpcomtrued:
9396   case Intrinsic::x86_xop_vpcomtrueq:
9397   case Intrinsic::x86_xop_vpcomtrueub:
9398   case Intrinsic::x86_xop_vpcomtrueuw:
9399   case Intrinsic::x86_xop_vpcomtrueud:
9400   case Intrinsic::x86_xop_vpcomtrueuq: {
9401     unsigned CC = 0;
9402     unsigned Opc = 0;
9403
9404     switch (IntNo) {
9405     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9406     case Intrinsic::x86_xop_vpcomltb:
9407     case Intrinsic::x86_xop_vpcomltw:
9408     case Intrinsic::x86_xop_vpcomltd:
9409     case Intrinsic::x86_xop_vpcomltq:
9410       CC = 0;
9411       Opc = X86ISD::VPCOM;
9412       break;
9413     case Intrinsic::x86_xop_vpcomltub:
9414     case Intrinsic::x86_xop_vpcomltuw:
9415     case Intrinsic::x86_xop_vpcomltud:
9416     case Intrinsic::x86_xop_vpcomltuq:
9417       CC = 0;
9418       Opc = X86ISD::VPCOMU;
9419       break;
9420     case Intrinsic::x86_xop_vpcomleb:
9421     case Intrinsic::x86_xop_vpcomlew:
9422     case Intrinsic::x86_xop_vpcomled:
9423     case Intrinsic::x86_xop_vpcomleq:
9424       CC = 1;
9425       Opc = X86ISD::VPCOM;
9426       break;
9427     case Intrinsic::x86_xop_vpcomleub:
9428     case Intrinsic::x86_xop_vpcomleuw:
9429     case Intrinsic::x86_xop_vpcomleud:
9430     case Intrinsic::x86_xop_vpcomleuq:
9431       CC = 1;
9432       Opc = X86ISD::VPCOMU;
9433       break;
9434     case Intrinsic::x86_xop_vpcomgtb:
9435     case Intrinsic::x86_xop_vpcomgtw:
9436     case Intrinsic::x86_xop_vpcomgtd:
9437     case Intrinsic::x86_xop_vpcomgtq:
9438       CC = 2;
9439       Opc = X86ISD::VPCOM;
9440       break;
9441     case Intrinsic::x86_xop_vpcomgtub:
9442     case Intrinsic::x86_xop_vpcomgtuw:
9443     case Intrinsic::x86_xop_vpcomgtud:
9444     case Intrinsic::x86_xop_vpcomgtuq:
9445       CC = 2;
9446       Opc = X86ISD::VPCOMU;
9447       break;
9448     case Intrinsic::x86_xop_vpcomgeb:
9449     case Intrinsic::x86_xop_vpcomgew:
9450     case Intrinsic::x86_xop_vpcomged:
9451     case Intrinsic::x86_xop_vpcomgeq:
9452       CC = 3;
9453       Opc = X86ISD::VPCOM;
9454       break;
9455     case Intrinsic::x86_xop_vpcomgeub:
9456     case Intrinsic::x86_xop_vpcomgeuw:
9457     case Intrinsic::x86_xop_vpcomgeud:
9458     case Intrinsic::x86_xop_vpcomgeuq:
9459       CC = 3;
9460       Opc = X86ISD::VPCOMU;
9461       break;
9462     case Intrinsic::x86_xop_vpcomeqb:
9463     case Intrinsic::x86_xop_vpcomeqw:
9464     case Intrinsic::x86_xop_vpcomeqd:
9465     case Intrinsic::x86_xop_vpcomeqq:
9466       CC = 4;
9467       Opc = X86ISD::VPCOM;
9468       break;
9469     case Intrinsic::x86_xop_vpcomequb:
9470     case Intrinsic::x86_xop_vpcomequw:
9471     case Intrinsic::x86_xop_vpcomequd:
9472     case Intrinsic::x86_xop_vpcomequq:
9473       CC = 4;
9474       Opc = X86ISD::VPCOMU;
9475       break;
9476     case Intrinsic::x86_xop_vpcomneb:
9477     case Intrinsic::x86_xop_vpcomnew:
9478     case Intrinsic::x86_xop_vpcomned:
9479     case Intrinsic::x86_xop_vpcomneq:
9480       CC = 5;
9481       Opc = X86ISD::VPCOM;
9482       break;
9483     case Intrinsic::x86_xop_vpcomneub:
9484     case Intrinsic::x86_xop_vpcomneuw:
9485     case Intrinsic::x86_xop_vpcomneud:
9486     case Intrinsic::x86_xop_vpcomneuq:
9487       CC = 5;
9488       Opc = X86ISD::VPCOMU;
9489       break;
9490     case Intrinsic::x86_xop_vpcomfalseb:
9491     case Intrinsic::x86_xop_vpcomfalsew:
9492     case Intrinsic::x86_xop_vpcomfalsed:
9493     case Intrinsic::x86_xop_vpcomfalseq:
9494       CC = 6;
9495       Opc = X86ISD::VPCOM;
9496       break;
9497     case Intrinsic::x86_xop_vpcomfalseub:
9498     case Intrinsic::x86_xop_vpcomfalseuw:
9499     case Intrinsic::x86_xop_vpcomfalseud:
9500     case Intrinsic::x86_xop_vpcomfalseuq:
9501       CC = 6;
9502       Opc = X86ISD::VPCOMU;
9503       break;
9504     case Intrinsic::x86_xop_vpcomtrueb:
9505     case Intrinsic::x86_xop_vpcomtruew:
9506     case Intrinsic::x86_xop_vpcomtrued:
9507     case Intrinsic::x86_xop_vpcomtrueq:
9508       CC = 7;
9509       Opc = X86ISD::VPCOM;
9510       break;
9511     case Intrinsic::x86_xop_vpcomtrueub:
9512     case Intrinsic::x86_xop_vpcomtrueuw:
9513     case Intrinsic::x86_xop_vpcomtrueud:
9514     case Intrinsic::x86_xop_vpcomtrueuq:
9515       CC = 7;
9516       Opc = X86ISD::VPCOMU;
9517       break;
9518     }
9519
9520     SDValue LHS = Op.getOperand(1);
9521     SDValue RHS = Op.getOperand(2);
9522     return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
9523                        DAG.getConstant(CC, MVT::i8));
9524   }
9525
9526   // Arithmetic intrinsics.
9527   case Intrinsic::x86_sse2_pmulu_dq:
9528   case Intrinsic::x86_avx2_pmulu_dq:
9529     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9530                        Op.getOperand(1), Op.getOperand(2));
9531   case Intrinsic::x86_sse3_hadd_ps:
9532   case Intrinsic::x86_sse3_hadd_pd:
9533   case Intrinsic::x86_avx_hadd_ps_256:
9534   case Intrinsic::x86_avx_hadd_pd_256:
9535     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9536                        Op.getOperand(1), Op.getOperand(2));
9537   case Intrinsic::x86_sse3_hsub_ps:
9538   case Intrinsic::x86_sse3_hsub_pd:
9539   case Intrinsic::x86_avx_hsub_ps_256:
9540   case Intrinsic::x86_avx_hsub_pd_256:
9541     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9542                        Op.getOperand(1), Op.getOperand(2));
9543   case Intrinsic::x86_ssse3_phadd_w_128:
9544   case Intrinsic::x86_ssse3_phadd_d_128:
9545   case Intrinsic::x86_avx2_phadd_w:
9546   case Intrinsic::x86_avx2_phadd_d:
9547     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9548                        Op.getOperand(1), Op.getOperand(2));
9549   case Intrinsic::x86_ssse3_phsub_w_128:
9550   case Intrinsic::x86_ssse3_phsub_d_128:
9551   case Intrinsic::x86_avx2_phsub_w:
9552   case Intrinsic::x86_avx2_phsub_d:
9553     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9554                        Op.getOperand(1), Op.getOperand(2));
9555   case Intrinsic::x86_avx2_psllv_d:
9556   case Intrinsic::x86_avx2_psllv_q:
9557   case Intrinsic::x86_avx2_psllv_d_256:
9558   case Intrinsic::x86_avx2_psllv_q_256:
9559     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9560                       Op.getOperand(1), Op.getOperand(2));
9561   case Intrinsic::x86_avx2_psrlv_d:
9562   case Intrinsic::x86_avx2_psrlv_q:
9563   case Intrinsic::x86_avx2_psrlv_d_256:
9564   case Intrinsic::x86_avx2_psrlv_q_256:
9565     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9566                       Op.getOperand(1), Op.getOperand(2));
9567   case Intrinsic::x86_avx2_psrav_d:
9568   case Intrinsic::x86_avx2_psrav_d_256:
9569     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9570                       Op.getOperand(1), Op.getOperand(2));
9571   case Intrinsic::x86_ssse3_pshuf_b_128:
9572   case Intrinsic::x86_avx2_pshuf_b:
9573     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9574                        Op.getOperand(1), Op.getOperand(2));
9575   case Intrinsic::x86_ssse3_psign_b_128:
9576   case Intrinsic::x86_ssse3_psign_w_128:
9577   case Intrinsic::x86_ssse3_psign_d_128:
9578   case Intrinsic::x86_avx2_psign_b:
9579   case Intrinsic::x86_avx2_psign_w:
9580   case Intrinsic::x86_avx2_psign_d:
9581     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9582                        Op.getOperand(1), Op.getOperand(2));
9583   case Intrinsic::x86_sse41_insertps:
9584     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9585                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9586   case Intrinsic::x86_avx_vperm2f128_ps_256:
9587   case Intrinsic::x86_avx_vperm2f128_pd_256:
9588   case Intrinsic::x86_avx_vperm2f128_si_256:
9589   case Intrinsic::x86_avx2_vperm2i128:
9590     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9591                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9592   case Intrinsic::x86_avx2_permd:
9593   case Intrinsic::x86_avx2_permps:
9594     // Operands intentionally swapped. Mask is last operand to intrinsic,
9595     // but second operand for node/intruction.
9596     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9597                        Op.getOperand(2), Op.getOperand(1));
9598
9599   // ptest and testp intrinsics. The intrinsic these come from are designed to
9600   // return an integer value, not just an instruction so lower it to the ptest
9601   // or testp pattern and a setcc for the result.
9602   case Intrinsic::x86_sse41_ptestz:
9603   case Intrinsic::x86_sse41_ptestc:
9604   case Intrinsic::x86_sse41_ptestnzc:
9605   case Intrinsic::x86_avx_ptestz_256:
9606   case Intrinsic::x86_avx_ptestc_256:
9607   case Intrinsic::x86_avx_ptestnzc_256:
9608   case Intrinsic::x86_avx_vtestz_ps:
9609   case Intrinsic::x86_avx_vtestc_ps:
9610   case Intrinsic::x86_avx_vtestnzc_ps:
9611   case Intrinsic::x86_avx_vtestz_pd:
9612   case Intrinsic::x86_avx_vtestc_pd:
9613   case Intrinsic::x86_avx_vtestnzc_pd:
9614   case Intrinsic::x86_avx_vtestz_ps_256:
9615   case Intrinsic::x86_avx_vtestc_ps_256:
9616   case Intrinsic::x86_avx_vtestnzc_ps_256:
9617   case Intrinsic::x86_avx_vtestz_pd_256:
9618   case Intrinsic::x86_avx_vtestc_pd_256:
9619   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9620     bool IsTestPacked = false;
9621     unsigned X86CC = 0;
9622     switch (IntNo) {
9623     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9624     case Intrinsic::x86_avx_vtestz_ps:
9625     case Intrinsic::x86_avx_vtestz_pd:
9626     case Intrinsic::x86_avx_vtestz_ps_256:
9627     case Intrinsic::x86_avx_vtestz_pd_256:
9628       IsTestPacked = true; // Fallthrough
9629     case Intrinsic::x86_sse41_ptestz:
9630     case Intrinsic::x86_avx_ptestz_256:
9631       // ZF = 1
9632       X86CC = X86::COND_E;
9633       break;
9634     case Intrinsic::x86_avx_vtestc_ps:
9635     case Intrinsic::x86_avx_vtestc_pd:
9636     case Intrinsic::x86_avx_vtestc_ps_256:
9637     case Intrinsic::x86_avx_vtestc_pd_256:
9638       IsTestPacked = true; // Fallthrough
9639     case Intrinsic::x86_sse41_ptestc:
9640     case Intrinsic::x86_avx_ptestc_256:
9641       // CF = 1
9642       X86CC = X86::COND_B;
9643       break;
9644     case Intrinsic::x86_avx_vtestnzc_ps:
9645     case Intrinsic::x86_avx_vtestnzc_pd:
9646     case Intrinsic::x86_avx_vtestnzc_ps_256:
9647     case Intrinsic::x86_avx_vtestnzc_pd_256:
9648       IsTestPacked = true; // Fallthrough
9649     case Intrinsic::x86_sse41_ptestnzc:
9650     case Intrinsic::x86_avx_ptestnzc_256:
9651       // ZF and CF = 0
9652       X86CC = X86::COND_A;
9653       break;
9654     }
9655
9656     SDValue LHS = Op.getOperand(1);
9657     SDValue RHS = Op.getOperand(2);
9658     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9659     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9660     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9661     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9662     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9663   }
9664
9665   // SSE/AVX shift intrinsics
9666   case Intrinsic::x86_sse2_psll_w:
9667   case Intrinsic::x86_sse2_psll_d:
9668   case Intrinsic::x86_sse2_psll_q:
9669   case Intrinsic::x86_avx2_psll_w:
9670   case Intrinsic::x86_avx2_psll_d:
9671   case Intrinsic::x86_avx2_psll_q:
9672     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9673                        Op.getOperand(1), Op.getOperand(2));
9674   case Intrinsic::x86_sse2_psrl_w:
9675   case Intrinsic::x86_sse2_psrl_d:
9676   case Intrinsic::x86_sse2_psrl_q:
9677   case Intrinsic::x86_avx2_psrl_w:
9678   case Intrinsic::x86_avx2_psrl_d:
9679   case Intrinsic::x86_avx2_psrl_q:
9680     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9681                        Op.getOperand(1), Op.getOperand(2));
9682   case Intrinsic::x86_sse2_psra_w:
9683   case Intrinsic::x86_sse2_psra_d:
9684   case Intrinsic::x86_avx2_psra_w:
9685   case Intrinsic::x86_avx2_psra_d:
9686     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9687                        Op.getOperand(1), Op.getOperand(2));
9688   case Intrinsic::x86_sse2_pslli_w:
9689   case Intrinsic::x86_sse2_pslli_d:
9690   case Intrinsic::x86_sse2_pslli_q:
9691   case Intrinsic::x86_avx2_pslli_w:
9692   case Intrinsic::x86_avx2_pslli_d:
9693   case Intrinsic::x86_avx2_pslli_q:
9694     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9695                                Op.getOperand(1), Op.getOperand(2), DAG);
9696   case Intrinsic::x86_sse2_psrli_w:
9697   case Intrinsic::x86_sse2_psrli_d:
9698   case Intrinsic::x86_sse2_psrli_q:
9699   case Intrinsic::x86_avx2_psrli_w:
9700   case Intrinsic::x86_avx2_psrli_d:
9701   case Intrinsic::x86_avx2_psrli_q:
9702     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9703                                Op.getOperand(1), Op.getOperand(2), DAG);
9704   case Intrinsic::x86_sse2_psrai_w:
9705   case Intrinsic::x86_sse2_psrai_d:
9706   case Intrinsic::x86_avx2_psrai_w:
9707   case Intrinsic::x86_avx2_psrai_d:
9708     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9709                                Op.getOperand(1), Op.getOperand(2), DAG);
9710   // Fix vector shift instructions where the last operand is a non-immediate
9711   // i32 value.
9712   case Intrinsic::x86_mmx_pslli_w:
9713   case Intrinsic::x86_mmx_pslli_d:
9714   case Intrinsic::x86_mmx_pslli_q:
9715   case Intrinsic::x86_mmx_psrli_w:
9716   case Intrinsic::x86_mmx_psrli_d:
9717   case Intrinsic::x86_mmx_psrli_q:
9718   case Intrinsic::x86_mmx_psrai_w:
9719   case Intrinsic::x86_mmx_psrai_d: {
9720     SDValue ShAmt = Op.getOperand(2);
9721     if (isa<ConstantSDNode>(ShAmt))
9722       return SDValue();
9723
9724     unsigned NewIntNo = 0;
9725     switch (IntNo) {
9726     case Intrinsic::x86_mmx_pslli_w:
9727       NewIntNo = Intrinsic::x86_mmx_psll_w;
9728       break;
9729     case Intrinsic::x86_mmx_pslli_d:
9730       NewIntNo = Intrinsic::x86_mmx_psll_d;
9731       break;
9732     case Intrinsic::x86_mmx_pslli_q:
9733       NewIntNo = Intrinsic::x86_mmx_psll_q;
9734       break;
9735     case Intrinsic::x86_mmx_psrli_w:
9736       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9737       break;
9738     case Intrinsic::x86_mmx_psrli_d:
9739       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9740       break;
9741     case Intrinsic::x86_mmx_psrli_q:
9742       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9743       break;
9744     case Intrinsic::x86_mmx_psrai_w:
9745       NewIntNo = Intrinsic::x86_mmx_psra_w;
9746       break;
9747     case Intrinsic::x86_mmx_psrai_d:
9748       NewIntNo = Intrinsic::x86_mmx_psra_d;
9749       break;
9750     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9751     }
9752
9753     // The vector shift intrinsics with scalars uses 32b shift amounts but
9754     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9755     // to be zero.
9756     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9757                          DAG.getConstant(0, MVT::i32));
9758 // FIXME this must be lowered to get rid of the invalid type.
9759
9760     EVT VT = Op.getValueType();
9761     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9762     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9763                        DAG.getConstant(NewIntNo, MVT::i32),
9764                        Op.getOperand(1), ShAmt);
9765   }
9766   }
9767 }
9768
9769 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9770                                            SelectionDAG &DAG) const {
9771   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9772   MFI->setReturnAddressIsTaken(true);
9773
9774   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9775   DebugLoc dl = Op.getDebugLoc();
9776
9777   if (Depth > 0) {
9778     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9779     SDValue Offset =
9780       DAG.getConstant(TD->getPointerSize(),
9781                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9782     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9783                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9784                                    FrameAddr, Offset),
9785                        MachinePointerInfo(), false, false, false, 0);
9786   }
9787
9788   // Just load the return address.
9789   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9790   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9791                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9792 }
9793
9794 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9795   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9796   MFI->setFrameAddressIsTaken(true);
9797
9798   EVT VT = Op.getValueType();
9799   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9800   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9801   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9802   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9803   while (Depth--)
9804     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9805                             MachinePointerInfo(),
9806                             false, false, false, 0);
9807   return FrameAddr;
9808 }
9809
9810 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9811                                                      SelectionDAG &DAG) const {
9812   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9813 }
9814
9815 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9816   MachineFunction &MF = DAG.getMachineFunction();
9817   SDValue Chain     = Op.getOperand(0);
9818   SDValue Offset    = Op.getOperand(1);
9819   SDValue Handler   = Op.getOperand(2);
9820   DebugLoc dl       = Op.getDebugLoc();
9821
9822   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9823                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9824                                      getPointerTy());
9825   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9826
9827   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9828                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9829   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9830   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9831                        false, false, 0);
9832   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9833   MF.getRegInfo().addLiveOut(StoreAddrReg);
9834
9835   return DAG.getNode(X86ISD::EH_RETURN, dl,
9836                      MVT::Other,
9837                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9838 }
9839
9840 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9841                                                   SelectionDAG &DAG) const {
9842   return Op.getOperand(0);
9843 }
9844
9845 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9846                                                 SelectionDAG &DAG) const {
9847   SDValue Root = Op.getOperand(0);
9848   SDValue Trmp = Op.getOperand(1); // trampoline
9849   SDValue FPtr = Op.getOperand(2); // nested function
9850   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9851   DebugLoc dl  = Op.getDebugLoc();
9852
9853   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9854
9855   if (Subtarget->is64Bit()) {
9856     SDValue OutChains[6];
9857
9858     // Large code-model.
9859     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9860     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9861
9862     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9863     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9864
9865     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9866
9867     // Load the pointer to the nested function into R11.
9868     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9869     SDValue Addr = Trmp;
9870     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9871                                 Addr, MachinePointerInfo(TrmpAddr),
9872                                 false, false, 0);
9873
9874     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9875                        DAG.getConstant(2, MVT::i64));
9876     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9877                                 MachinePointerInfo(TrmpAddr, 2),
9878                                 false, false, 2);
9879
9880     // Load the 'nest' parameter value into R10.
9881     // R10 is specified in X86CallingConv.td
9882     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9883     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9884                        DAG.getConstant(10, MVT::i64));
9885     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9886                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9887                                 false, false, 0);
9888
9889     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9890                        DAG.getConstant(12, MVT::i64));
9891     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9892                                 MachinePointerInfo(TrmpAddr, 12),
9893                                 false, false, 2);
9894
9895     // Jump to the nested function.
9896     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9897     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9898                        DAG.getConstant(20, MVT::i64));
9899     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9900                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9901                                 false, false, 0);
9902
9903     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9904     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9905                        DAG.getConstant(22, MVT::i64));
9906     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9907                                 MachinePointerInfo(TrmpAddr, 22),
9908                                 false, false, 0);
9909
9910     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9911   } else {
9912     const Function *Func =
9913       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9914     CallingConv::ID CC = Func->getCallingConv();
9915     unsigned NestReg;
9916
9917     switch (CC) {
9918     default:
9919       llvm_unreachable("Unsupported calling convention");
9920     case CallingConv::C:
9921     case CallingConv::X86_StdCall: {
9922       // Pass 'nest' parameter in ECX.
9923       // Must be kept in sync with X86CallingConv.td
9924       NestReg = X86::ECX;
9925
9926       // Check that ECX wasn't needed by an 'inreg' parameter.
9927       FunctionType *FTy = Func->getFunctionType();
9928       const AttrListPtr &Attrs = Func->getAttributes();
9929
9930       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9931         unsigned InRegCount = 0;
9932         unsigned Idx = 1;
9933
9934         for (FunctionType::param_iterator I = FTy->param_begin(),
9935              E = FTy->param_end(); I != E; ++I, ++Idx)
9936           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9937             // FIXME: should only count parameters that are lowered to integers.
9938             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9939
9940         if (InRegCount > 2) {
9941           report_fatal_error("Nest register in use - reduce number of inreg"
9942                              " parameters!");
9943         }
9944       }
9945       break;
9946     }
9947     case CallingConv::X86_FastCall:
9948     case CallingConv::X86_ThisCall:
9949     case CallingConv::Fast:
9950       // Pass 'nest' parameter in EAX.
9951       // Must be kept in sync with X86CallingConv.td
9952       NestReg = X86::EAX;
9953       break;
9954     }
9955
9956     SDValue OutChains[4];
9957     SDValue Addr, Disp;
9958
9959     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9960                        DAG.getConstant(10, MVT::i32));
9961     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9962
9963     // This is storing the opcode for MOV32ri.
9964     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9965     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9966     OutChains[0] = DAG.getStore(Root, dl,
9967                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9968                                 Trmp, MachinePointerInfo(TrmpAddr),
9969                                 false, false, 0);
9970
9971     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9972                        DAG.getConstant(1, MVT::i32));
9973     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9974                                 MachinePointerInfo(TrmpAddr, 1),
9975                                 false, false, 1);
9976
9977     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9978     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9979                        DAG.getConstant(5, MVT::i32));
9980     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9981                                 MachinePointerInfo(TrmpAddr, 5),
9982                                 false, false, 1);
9983
9984     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9985                        DAG.getConstant(6, MVT::i32));
9986     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9987                                 MachinePointerInfo(TrmpAddr, 6),
9988                                 false, false, 1);
9989
9990     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9991   }
9992 }
9993
9994 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9995                                             SelectionDAG &DAG) const {
9996   /*
9997    The rounding mode is in bits 11:10 of FPSR, and has the following
9998    settings:
9999      00 Round to nearest
10000      01 Round to -inf
10001      10 Round to +inf
10002      11 Round to 0
10003
10004   FLT_ROUNDS, on the other hand, expects the following:
10005     -1 Undefined
10006      0 Round to 0
10007      1 Round to nearest
10008      2 Round to +inf
10009      3 Round to -inf
10010
10011   To perform the conversion, we do:
10012     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10013   */
10014
10015   MachineFunction &MF = DAG.getMachineFunction();
10016   const TargetMachine &TM = MF.getTarget();
10017   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10018   unsigned StackAlignment = TFI.getStackAlignment();
10019   EVT VT = Op.getValueType();
10020   DebugLoc DL = Op.getDebugLoc();
10021
10022   // Save FP Control Word to stack slot
10023   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10024   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10025
10026
10027   MachineMemOperand *MMO =
10028    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10029                            MachineMemOperand::MOStore, 2, 2);
10030
10031   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10032   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10033                                           DAG.getVTList(MVT::Other),
10034                                           Ops, 2, MVT::i16, MMO);
10035
10036   // Load FP Control Word from stack slot
10037   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10038                             MachinePointerInfo(), false, false, false, 0);
10039
10040   // Transform as necessary
10041   SDValue CWD1 =
10042     DAG.getNode(ISD::SRL, DL, MVT::i16,
10043                 DAG.getNode(ISD::AND, DL, MVT::i16,
10044                             CWD, DAG.getConstant(0x800, MVT::i16)),
10045                 DAG.getConstant(11, MVT::i8));
10046   SDValue CWD2 =
10047     DAG.getNode(ISD::SRL, DL, MVT::i16,
10048                 DAG.getNode(ISD::AND, DL, MVT::i16,
10049                             CWD, DAG.getConstant(0x400, MVT::i16)),
10050                 DAG.getConstant(9, MVT::i8));
10051
10052   SDValue RetVal =
10053     DAG.getNode(ISD::AND, DL, MVT::i16,
10054                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10055                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10056                             DAG.getConstant(1, MVT::i16)),
10057                 DAG.getConstant(3, MVT::i16));
10058
10059
10060   return DAG.getNode((VT.getSizeInBits() < 16 ?
10061                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10062 }
10063
10064 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10065   EVT VT = Op.getValueType();
10066   EVT OpVT = VT;
10067   unsigned NumBits = VT.getSizeInBits();
10068   DebugLoc dl = Op.getDebugLoc();
10069
10070   Op = Op.getOperand(0);
10071   if (VT == MVT::i8) {
10072     // Zero extend to i32 since there is not an i8 bsr.
10073     OpVT = MVT::i32;
10074     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10075   }
10076
10077   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10078   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10079   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10080
10081   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10082   SDValue Ops[] = {
10083     Op,
10084     DAG.getConstant(NumBits+NumBits-1, OpVT),
10085     DAG.getConstant(X86::COND_E, MVT::i8),
10086     Op.getValue(1)
10087   };
10088   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10089
10090   // Finally xor with NumBits-1.
10091   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10092
10093   if (VT == MVT::i8)
10094     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10095   return Op;
10096 }
10097
10098 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10099                                                 SelectionDAG &DAG) const {
10100   EVT VT = Op.getValueType();
10101   EVT OpVT = VT;
10102   unsigned NumBits = VT.getSizeInBits();
10103   DebugLoc dl = Op.getDebugLoc();
10104
10105   Op = Op.getOperand(0);
10106   if (VT == MVT::i8) {
10107     // Zero extend to i32 since there is not an i8 bsr.
10108     OpVT = MVT::i32;
10109     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10110   }
10111
10112   // Issue a bsr (scan bits in reverse).
10113   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10114   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10115
10116   // And xor with NumBits-1.
10117   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10118
10119   if (VT == MVT::i8)
10120     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10121   return Op;
10122 }
10123
10124 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10125   EVT VT = Op.getValueType();
10126   unsigned NumBits = VT.getSizeInBits();
10127   DebugLoc dl = Op.getDebugLoc();
10128   Op = Op.getOperand(0);
10129
10130   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10131   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10132   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10133
10134   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10135   SDValue Ops[] = {
10136     Op,
10137     DAG.getConstant(NumBits, VT),
10138     DAG.getConstant(X86::COND_E, MVT::i8),
10139     Op.getValue(1)
10140   };
10141   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10142 }
10143
10144 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10145 // ones, and then concatenate the result back.
10146 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10147   EVT VT = Op.getValueType();
10148
10149   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10150          "Unsupported value type for operation");
10151
10152   int NumElems = VT.getVectorNumElements();
10153   DebugLoc dl = Op.getDebugLoc();
10154
10155   // Extract the LHS vectors
10156   SDValue LHS = Op.getOperand(0);
10157   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10158   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10159
10160   // Extract the RHS vectors
10161   SDValue RHS = Op.getOperand(1);
10162   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10163   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10164
10165   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10166   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10167
10168   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10169                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10170                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10171 }
10172
10173 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10174   assert(Op.getValueType().getSizeInBits() == 256 &&
10175          Op.getValueType().isInteger() &&
10176          "Only handle AVX 256-bit vector integer operation");
10177   return Lower256IntArith(Op, DAG);
10178 }
10179
10180 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10181   assert(Op.getValueType().getSizeInBits() == 256 &&
10182          Op.getValueType().isInteger() &&
10183          "Only handle AVX 256-bit vector integer operation");
10184   return Lower256IntArith(Op, DAG);
10185 }
10186
10187 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10188   EVT VT = Op.getValueType();
10189
10190   // Decompose 256-bit ops into smaller 128-bit ops.
10191   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10192     return Lower256IntArith(Op, DAG);
10193
10194   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10195          "Only know how to lower V2I64/V4I64 multiply");
10196
10197   DebugLoc dl = Op.getDebugLoc();
10198
10199   //  Ahi = psrlqi(a, 32);
10200   //  Bhi = psrlqi(b, 32);
10201   //
10202   //  AloBlo = pmuludq(a, b);
10203   //  AloBhi = pmuludq(a, Bhi);
10204   //  AhiBlo = pmuludq(Ahi, b);
10205
10206   //  AloBhi = psllqi(AloBhi, 32);
10207   //  AhiBlo = psllqi(AhiBlo, 32);
10208   //  return AloBlo + AloBhi + AhiBlo;
10209
10210   SDValue A = Op.getOperand(0);
10211   SDValue B = Op.getOperand(1);
10212
10213   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10214
10215   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10216   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10217
10218   // Bit cast to 32-bit vectors for MULUDQ
10219   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10220   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10221   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10222   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10223   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10224
10225   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10226   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10227   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10228
10229   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10230   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10231
10232   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10233   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10234 }
10235
10236 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10237
10238   EVT VT = Op.getValueType();
10239   DebugLoc dl = Op.getDebugLoc();
10240   SDValue R = Op.getOperand(0);
10241   SDValue Amt = Op.getOperand(1);
10242   LLVMContext *Context = DAG.getContext();
10243
10244   if (!Subtarget->hasSSE2())
10245     return SDValue();
10246
10247   // Optimize shl/srl/sra with constant shift amount.
10248   if (isSplatVector(Amt.getNode())) {
10249     SDValue SclrAmt = Amt->getOperand(0);
10250     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10251       uint64_t ShiftAmt = C->getZExtValue();
10252
10253       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10254           (Subtarget->hasAVX2() &&
10255            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10256         if (Op.getOpcode() == ISD::SHL)
10257           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10258                              DAG.getConstant(ShiftAmt, MVT::i32));
10259         if (Op.getOpcode() == ISD::SRL)
10260           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10261                              DAG.getConstant(ShiftAmt, MVT::i32));
10262         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10263           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10264                              DAG.getConstant(ShiftAmt, MVT::i32));
10265       }
10266
10267       if (VT == MVT::v16i8) {
10268         if (Op.getOpcode() == ISD::SHL) {
10269           // Make a large shift.
10270           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10271                                     DAG.getConstant(ShiftAmt, MVT::i32));
10272           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10273           // Zero out the rightmost bits.
10274           SmallVector<SDValue, 16> V(16,
10275                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10276                                                      MVT::i8));
10277           return DAG.getNode(ISD::AND, dl, VT, SHL,
10278                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10279         }
10280         if (Op.getOpcode() == ISD::SRL) {
10281           // Make a large shift.
10282           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10283                                     DAG.getConstant(ShiftAmt, MVT::i32));
10284           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10285           // Zero out the leftmost bits.
10286           SmallVector<SDValue, 16> V(16,
10287                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10288                                                      MVT::i8));
10289           return DAG.getNode(ISD::AND, dl, VT, SRL,
10290                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10291         }
10292         if (Op.getOpcode() == ISD::SRA) {
10293           if (ShiftAmt == 7) {
10294             // R s>> 7  ===  R s< 0
10295             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10296             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10297           }
10298
10299           // R s>> a === ((R u>> a) ^ m) - m
10300           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10301           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10302                                                          MVT::i8));
10303           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10304           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10305           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10306           return Res;
10307         }
10308         llvm_unreachable("Unknown shift opcode.");
10309       }
10310
10311       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10312         if (Op.getOpcode() == ISD::SHL) {
10313           // Make a large shift.
10314           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10315                                     DAG.getConstant(ShiftAmt, MVT::i32));
10316           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10317           // Zero out the rightmost bits.
10318           SmallVector<SDValue, 32> V(32,
10319                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10320                                                      MVT::i8));
10321           return DAG.getNode(ISD::AND, dl, VT, SHL,
10322                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10323         }
10324         if (Op.getOpcode() == ISD::SRL) {
10325           // Make a large shift.
10326           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10327                                     DAG.getConstant(ShiftAmt, MVT::i32));
10328           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10329           // Zero out the leftmost bits.
10330           SmallVector<SDValue, 32> V(32,
10331                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10332                                                      MVT::i8));
10333           return DAG.getNode(ISD::AND, dl, VT, SRL,
10334                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10335         }
10336         if (Op.getOpcode() == ISD::SRA) {
10337           if (ShiftAmt == 7) {
10338             // R s>> 7  ===  R s< 0
10339             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10340             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10341           }
10342
10343           // R s>> a === ((R u>> a) ^ m) - m
10344           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10345           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10346                                                          MVT::i8));
10347           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10348           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10349           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10350           return Res;
10351         }
10352         llvm_unreachable("Unknown shift opcode.");
10353       }
10354     }
10355   }
10356
10357   // Lower SHL with variable shift amount.
10358   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10359     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10360                      DAG.getConstant(23, MVT::i32));
10361
10362     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10363     Constant *C = ConstantDataVector::get(*Context, CV);
10364     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10365     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10366                                  MachinePointerInfo::getConstantPool(),
10367                                  false, false, false, 16);
10368
10369     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10370     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10371     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10372     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10373   }
10374   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10375     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10376
10377     // a = a << 5;
10378     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10379                      DAG.getConstant(5, MVT::i32));
10380     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10381
10382     // Turn 'a' into a mask suitable for VSELECT
10383     SDValue VSelM = DAG.getConstant(0x80, VT);
10384     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10385     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10386
10387     SDValue CM1 = DAG.getConstant(0x0f, VT);
10388     SDValue CM2 = DAG.getConstant(0x3f, VT);
10389
10390     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10391     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10392     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10393                             DAG.getConstant(4, MVT::i32), DAG);
10394     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10395     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10396
10397     // a += a
10398     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10399     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10400     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10401
10402     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10403     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10404     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10405                             DAG.getConstant(2, MVT::i32), DAG);
10406     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10407     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10408
10409     // a += a
10410     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10411     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10412     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10413
10414     // return VSELECT(r, r+r, a);
10415     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10416                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10417     return R;
10418   }
10419
10420   // Decompose 256-bit shifts into smaller 128-bit shifts.
10421   if (VT.getSizeInBits() == 256) {
10422     unsigned NumElems = VT.getVectorNumElements();
10423     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10424     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10425
10426     // Extract the two vectors
10427     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10428     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10429
10430     // Recreate the shift amount vectors
10431     SDValue Amt1, Amt2;
10432     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10433       // Constant shift amount
10434       SmallVector<SDValue, 4> Amt1Csts;
10435       SmallVector<SDValue, 4> Amt2Csts;
10436       for (unsigned i = 0; i != NumElems/2; ++i)
10437         Amt1Csts.push_back(Amt->getOperand(i));
10438       for (unsigned i = NumElems/2; i != NumElems; ++i)
10439         Amt2Csts.push_back(Amt->getOperand(i));
10440
10441       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10442                                  &Amt1Csts[0], NumElems/2);
10443       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10444                                  &Amt2Csts[0], NumElems/2);
10445     } else {
10446       // Variable shift amount
10447       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10448       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10449     }
10450
10451     // Issue new vector shifts for the smaller types
10452     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10453     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10454
10455     // Concatenate the result back
10456     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10457   }
10458
10459   return SDValue();
10460 }
10461
10462 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10463   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10464   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10465   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10466   // has only one use.
10467   SDNode *N = Op.getNode();
10468   SDValue LHS = N->getOperand(0);
10469   SDValue RHS = N->getOperand(1);
10470   unsigned BaseOp = 0;
10471   unsigned Cond = 0;
10472   DebugLoc DL = Op.getDebugLoc();
10473   switch (Op.getOpcode()) {
10474   default: llvm_unreachable("Unknown ovf instruction!");
10475   case ISD::SADDO:
10476     // A subtract of one will be selected as a INC. Note that INC doesn't
10477     // set CF, so we can't do this for UADDO.
10478     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10479       if (C->isOne()) {
10480         BaseOp = X86ISD::INC;
10481         Cond = X86::COND_O;
10482         break;
10483       }
10484     BaseOp = X86ISD::ADD;
10485     Cond = X86::COND_O;
10486     break;
10487   case ISD::UADDO:
10488     BaseOp = X86ISD::ADD;
10489     Cond = X86::COND_B;
10490     break;
10491   case ISD::SSUBO:
10492     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10493     // set CF, so we can't do this for USUBO.
10494     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10495       if (C->isOne()) {
10496         BaseOp = X86ISD::DEC;
10497         Cond = X86::COND_O;
10498         break;
10499       }
10500     BaseOp = X86ISD::SUB;
10501     Cond = X86::COND_O;
10502     break;
10503   case ISD::USUBO:
10504     BaseOp = X86ISD::SUB;
10505     Cond = X86::COND_B;
10506     break;
10507   case ISD::SMULO:
10508     BaseOp = X86ISD::SMUL;
10509     Cond = X86::COND_O;
10510     break;
10511   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10512     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10513                                  MVT::i32);
10514     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10515
10516     SDValue SetCC =
10517       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10518                   DAG.getConstant(X86::COND_O, MVT::i32),
10519                   SDValue(Sum.getNode(), 2));
10520
10521     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10522   }
10523   }
10524
10525   // Also sets EFLAGS.
10526   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10527   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10528
10529   SDValue SetCC =
10530     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10531                 DAG.getConstant(Cond, MVT::i32),
10532                 SDValue(Sum.getNode(), 1));
10533
10534   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10535 }
10536
10537 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10538                                                   SelectionDAG &DAG) const {
10539   DebugLoc dl = Op.getDebugLoc();
10540   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10541   EVT VT = Op.getValueType();
10542
10543   if (!Subtarget->hasSSE2() || !VT.isVector())
10544     return SDValue();
10545
10546   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10547                       ExtraVT.getScalarType().getSizeInBits();
10548   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10549
10550   switch (VT.getSimpleVT().SimpleTy) {
10551     default: return SDValue();
10552     case MVT::v8i32:
10553     case MVT::v16i16:
10554       if (!Subtarget->hasAVX())
10555         return SDValue();
10556       if (!Subtarget->hasAVX2()) {
10557         // needs to be split
10558         int NumElems = VT.getVectorNumElements();
10559
10560         // Extract the LHS vectors
10561         SDValue LHS = Op.getOperand(0);
10562         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10563         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10564
10565         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10566         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10567
10568         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10569         int ExtraNumElems = ExtraVT.getVectorNumElements();
10570         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10571                                    ExtraNumElems/2);
10572         SDValue Extra = DAG.getValueType(ExtraVT);
10573
10574         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10575         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10576
10577         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10578       }
10579       // fall through
10580     case MVT::v4i32:
10581     case MVT::v8i16: {
10582       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10583                                          Op.getOperand(0), ShAmt, DAG);
10584       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10585     }
10586   }
10587 }
10588
10589
10590 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10591   DebugLoc dl = Op.getDebugLoc();
10592
10593   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10594   // There isn't any reason to disable it if the target processor supports it.
10595   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10596     SDValue Chain = Op.getOperand(0);
10597     SDValue Zero = DAG.getConstant(0, MVT::i32);
10598     SDValue Ops[] = {
10599       DAG.getRegister(X86::ESP, MVT::i32), // Base
10600       DAG.getTargetConstant(1, MVT::i8),   // Scale
10601       DAG.getRegister(0, MVT::i32),        // Index
10602       DAG.getTargetConstant(0, MVT::i32),  // Disp
10603       DAG.getRegister(0, MVT::i32),        // Segment.
10604       Zero,
10605       Chain
10606     };
10607     SDNode *Res =
10608       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10609                           array_lengthof(Ops));
10610     return SDValue(Res, 0);
10611   }
10612
10613   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10614   if (!isDev)
10615     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10616
10617   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10618   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10619   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10620   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10621
10622   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10623   if (!Op1 && !Op2 && !Op3 && Op4)
10624     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10625
10626   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10627   if (Op1 && !Op2 && !Op3 && !Op4)
10628     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10629
10630   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10631   //           (MFENCE)>;
10632   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10633 }
10634
10635 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10636                                              SelectionDAG &DAG) const {
10637   DebugLoc dl = Op.getDebugLoc();
10638   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10639     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10640   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10641     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10642
10643   // The only fence that needs an instruction is a sequentially-consistent
10644   // cross-thread fence.
10645   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10646     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10647     // no-sse2). There isn't any reason to disable it if the target processor
10648     // supports it.
10649     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10650       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10651
10652     SDValue Chain = Op.getOperand(0);
10653     SDValue Zero = DAG.getConstant(0, MVT::i32);
10654     SDValue Ops[] = {
10655       DAG.getRegister(X86::ESP, MVT::i32), // Base
10656       DAG.getTargetConstant(1, MVT::i8),   // Scale
10657       DAG.getRegister(0, MVT::i32),        // Index
10658       DAG.getTargetConstant(0, MVT::i32),  // Disp
10659       DAG.getRegister(0, MVT::i32),        // Segment.
10660       Zero,
10661       Chain
10662     };
10663     SDNode *Res =
10664       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10665                          array_lengthof(Ops));
10666     return SDValue(Res, 0);
10667   }
10668
10669   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10670   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10671 }
10672
10673
10674 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10675   EVT T = Op.getValueType();
10676   DebugLoc DL = Op.getDebugLoc();
10677   unsigned Reg = 0;
10678   unsigned size = 0;
10679   switch(T.getSimpleVT().SimpleTy) {
10680   default: llvm_unreachable("Invalid value type!");
10681   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10682   case MVT::i16: Reg = X86::AX;  size = 2; break;
10683   case MVT::i32: Reg = X86::EAX; size = 4; break;
10684   case MVT::i64:
10685     assert(Subtarget->is64Bit() && "Node not type legal!");
10686     Reg = X86::RAX; size = 8;
10687     break;
10688   }
10689   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10690                                     Op.getOperand(2), SDValue());
10691   SDValue Ops[] = { cpIn.getValue(0),
10692                     Op.getOperand(1),
10693                     Op.getOperand(3),
10694                     DAG.getTargetConstant(size, MVT::i8),
10695                     cpIn.getValue(1) };
10696   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10697   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10698   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10699                                            Ops, 5, T, MMO);
10700   SDValue cpOut =
10701     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10702   return cpOut;
10703 }
10704
10705 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10706                                                  SelectionDAG &DAG) const {
10707   assert(Subtarget->is64Bit() && "Result not type legalized?");
10708   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10709   SDValue TheChain = Op.getOperand(0);
10710   DebugLoc dl = Op.getDebugLoc();
10711   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10712   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10713   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10714                                    rax.getValue(2));
10715   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10716                             DAG.getConstant(32, MVT::i8));
10717   SDValue Ops[] = {
10718     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10719     rdx.getValue(1)
10720   };
10721   return DAG.getMergeValues(Ops, 2, dl);
10722 }
10723
10724 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10725                                             SelectionDAG &DAG) const {
10726   EVT SrcVT = Op.getOperand(0).getValueType();
10727   EVT DstVT = Op.getValueType();
10728   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10729          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10730   assert((DstVT == MVT::i64 ||
10731           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10732          "Unexpected custom BITCAST");
10733   // i64 <=> MMX conversions are Legal.
10734   if (SrcVT==MVT::i64 && DstVT.isVector())
10735     return Op;
10736   if (DstVT==MVT::i64 && SrcVT.isVector())
10737     return Op;
10738   // MMX <=> MMX conversions are Legal.
10739   if (SrcVT.isVector() && DstVT.isVector())
10740     return Op;
10741   // All other conversions need to be expanded.
10742   return SDValue();
10743 }
10744
10745 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10746   SDNode *Node = Op.getNode();
10747   DebugLoc dl = Node->getDebugLoc();
10748   EVT T = Node->getValueType(0);
10749   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10750                               DAG.getConstant(0, T), Node->getOperand(2));
10751   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10752                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10753                        Node->getOperand(0),
10754                        Node->getOperand(1), negOp,
10755                        cast<AtomicSDNode>(Node)->getSrcValue(),
10756                        cast<AtomicSDNode>(Node)->getAlignment(),
10757                        cast<AtomicSDNode>(Node)->getOrdering(),
10758                        cast<AtomicSDNode>(Node)->getSynchScope());
10759 }
10760
10761 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10762   SDNode *Node = Op.getNode();
10763   DebugLoc dl = Node->getDebugLoc();
10764   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10765
10766   // Convert seq_cst store -> xchg
10767   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10768   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10769   //        (The only way to get a 16-byte store is cmpxchg16b)
10770   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10771   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10772       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10773     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10774                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10775                                  Node->getOperand(0),
10776                                  Node->getOperand(1), Node->getOperand(2),
10777                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10778                                  cast<AtomicSDNode>(Node)->getOrdering(),
10779                                  cast<AtomicSDNode>(Node)->getSynchScope());
10780     return Swap.getValue(1);
10781   }
10782   // Other atomic stores have a simple pattern.
10783   return Op;
10784 }
10785
10786 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10787   EVT VT = Op.getNode()->getValueType(0);
10788
10789   // Let legalize expand this if it isn't a legal type yet.
10790   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10791     return SDValue();
10792
10793   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10794
10795   unsigned Opc;
10796   bool ExtraOp = false;
10797   switch (Op.getOpcode()) {
10798   default: llvm_unreachable("Invalid code");
10799   case ISD::ADDC: Opc = X86ISD::ADD; break;
10800   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10801   case ISD::SUBC: Opc = X86ISD::SUB; break;
10802   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10803   }
10804
10805   if (!ExtraOp)
10806     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10807                        Op.getOperand(1));
10808   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10809                      Op.getOperand(1), Op.getOperand(2));
10810 }
10811
10812 /// LowerOperation - Provide custom lowering hooks for some operations.
10813 ///
10814 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10815   switch (Op.getOpcode()) {
10816   default: llvm_unreachable("Should not custom lower this!");
10817   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10818   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10819   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10820   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10821   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10822   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10823   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10824   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10825   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10826   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10827   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10828   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10829   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10830   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10831   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10832   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10833   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10834   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10835   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10836   case ISD::SHL_PARTS:
10837   case ISD::SRA_PARTS:
10838   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10839   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10840   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10841   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10842   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10843   case ISD::FABS:               return LowerFABS(Op, DAG);
10844   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10845   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10846   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10847   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10848   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10849   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10850   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10851   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10852   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10853   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10854   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10855   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10856   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10857   case ISD::FRAME_TO_ARGS_OFFSET:
10858                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10859   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10860   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10861   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10862   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10863   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10864   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10865   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10866   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10867   case ISD::MUL:                return LowerMUL(Op, DAG);
10868   case ISD::SRA:
10869   case ISD::SRL:
10870   case ISD::SHL:                return LowerShift(Op, DAG);
10871   case ISD::SADDO:
10872   case ISD::UADDO:
10873   case ISD::SSUBO:
10874   case ISD::USUBO:
10875   case ISD::SMULO:
10876   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10877   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10878   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10879   case ISD::ADDC:
10880   case ISD::ADDE:
10881   case ISD::SUBC:
10882   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10883   case ISD::ADD:                return LowerADD(Op, DAG);
10884   case ISD::SUB:                return LowerSUB(Op, DAG);
10885   }
10886 }
10887
10888 static void ReplaceATOMIC_LOAD(SDNode *Node,
10889                                   SmallVectorImpl<SDValue> &Results,
10890                                   SelectionDAG &DAG) {
10891   DebugLoc dl = Node->getDebugLoc();
10892   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10893
10894   // Convert wide load -> cmpxchg8b/cmpxchg16b
10895   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10896   //        (The only way to get a 16-byte load is cmpxchg16b)
10897   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10898   SDValue Zero = DAG.getConstant(0, VT);
10899   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10900                                Node->getOperand(0),
10901                                Node->getOperand(1), Zero, Zero,
10902                                cast<AtomicSDNode>(Node)->getMemOperand(),
10903                                cast<AtomicSDNode>(Node)->getOrdering(),
10904                                cast<AtomicSDNode>(Node)->getSynchScope());
10905   Results.push_back(Swap.getValue(0));
10906   Results.push_back(Swap.getValue(1));
10907 }
10908
10909 void X86TargetLowering::
10910 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10911                         SelectionDAG &DAG, unsigned NewOp) const {
10912   DebugLoc dl = Node->getDebugLoc();
10913   assert (Node->getValueType(0) == MVT::i64 &&
10914           "Only know how to expand i64 atomics");
10915
10916   SDValue Chain = Node->getOperand(0);
10917   SDValue In1 = Node->getOperand(1);
10918   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10919                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10920   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10921                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10922   SDValue Ops[] = { Chain, In1, In2L, In2H };
10923   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10924   SDValue Result =
10925     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10926                             cast<MemSDNode>(Node)->getMemOperand());
10927   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10928   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10929   Results.push_back(Result.getValue(2));
10930 }
10931
10932 /// ReplaceNodeResults - Replace a node with an illegal result type
10933 /// with a new node built out of custom code.
10934 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10935                                            SmallVectorImpl<SDValue>&Results,
10936                                            SelectionDAG &DAG) const {
10937   DebugLoc dl = N->getDebugLoc();
10938   switch (N->getOpcode()) {
10939   default:
10940     llvm_unreachable("Do not know how to custom type legalize this operation!");
10941   case ISD::SIGN_EXTEND_INREG:
10942   case ISD::ADDC:
10943   case ISD::ADDE:
10944   case ISD::SUBC:
10945   case ISD::SUBE:
10946     // We don't want to expand or promote these.
10947     return;
10948   case ISD::FP_TO_SINT:
10949   case ISD::FP_TO_UINT: {
10950     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10951
10952     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
10953       return;
10954
10955     std::pair<SDValue,SDValue> Vals =
10956         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
10957     SDValue FIST = Vals.first, StackSlot = Vals.second;
10958     if (FIST.getNode() != 0) {
10959       EVT VT = N->getValueType(0);
10960       // Return a load from the stack slot.
10961       if (StackSlot.getNode() != 0)
10962         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10963                                       MachinePointerInfo(),
10964                                       false, false, false, 0));
10965       else
10966         Results.push_back(FIST);
10967     }
10968     return;
10969   }
10970   case ISD::READCYCLECOUNTER: {
10971     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10972     SDValue TheChain = N->getOperand(0);
10973     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10974     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10975                                      rd.getValue(1));
10976     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10977                                      eax.getValue(2));
10978     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10979     SDValue Ops[] = { eax, edx };
10980     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10981     Results.push_back(edx.getValue(1));
10982     return;
10983   }
10984   case ISD::ATOMIC_CMP_SWAP: {
10985     EVT T = N->getValueType(0);
10986     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10987     bool Regs64bit = T == MVT::i128;
10988     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10989     SDValue cpInL, cpInH;
10990     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10991                         DAG.getConstant(0, HalfT));
10992     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10993                         DAG.getConstant(1, HalfT));
10994     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10995                              Regs64bit ? X86::RAX : X86::EAX,
10996                              cpInL, SDValue());
10997     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10998                              Regs64bit ? X86::RDX : X86::EDX,
10999                              cpInH, cpInL.getValue(1));
11000     SDValue swapInL, swapInH;
11001     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11002                           DAG.getConstant(0, HalfT));
11003     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11004                           DAG.getConstant(1, HalfT));
11005     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11006                                Regs64bit ? X86::RBX : X86::EBX,
11007                                swapInL, cpInH.getValue(1));
11008     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11009                                Regs64bit ? X86::RCX : X86::ECX, 
11010                                swapInH, swapInL.getValue(1));
11011     SDValue Ops[] = { swapInH.getValue(0),
11012                       N->getOperand(1),
11013                       swapInH.getValue(1) };
11014     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11015     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11016     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11017                                   X86ISD::LCMPXCHG8_DAG;
11018     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11019                                              Ops, 3, T, MMO);
11020     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11021                                         Regs64bit ? X86::RAX : X86::EAX,
11022                                         HalfT, Result.getValue(1));
11023     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11024                                         Regs64bit ? X86::RDX : X86::EDX,
11025                                         HalfT, cpOutL.getValue(2));
11026     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11027     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11028     Results.push_back(cpOutH.getValue(1));
11029     return;
11030   }
11031   case ISD::ATOMIC_LOAD_ADD:
11032     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11033     return;
11034   case ISD::ATOMIC_LOAD_AND:
11035     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11036     return;
11037   case ISD::ATOMIC_LOAD_NAND:
11038     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11039     return;
11040   case ISD::ATOMIC_LOAD_OR:
11041     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11042     return;
11043   case ISD::ATOMIC_LOAD_SUB:
11044     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11045     return;
11046   case ISD::ATOMIC_LOAD_XOR:
11047     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11048     return;
11049   case ISD::ATOMIC_SWAP:
11050     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11051     return;
11052   case ISD::ATOMIC_LOAD:
11053     ReplaceATOMIC_LOAD(N, Results, DAG);
11054   }
11055 }
11056
11057 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11058   switch (Opcode) {
11059   default: return NULL;
11060   case X86ISD::BSF:                return "X86ISD::BSF";
11061   case X86ISD::BSR:                return "X86ISD::BSR";
11062   case X86ISD::SHLD:               return "X86ISD::SHLD";
11063   case X86ISD::SHRD:               return "X86ISD::SHRD";
11064   case X86ISD::FAND:               return "X86ISD::FAND";
11065   case X86ISD::FOR:                return "X86ISD::FOR";
11066   case X86ISD::FXOR:               return "X86ISD::FXOR";
11067   case X86ISD::FSRL:               return "X86ISD::FSRL";
11068   case X86ISD::FILD:               return "X86ISD::FILD";
11069   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11070   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11071   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11072   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11073   case X86ISD::FLD:                return "X86ISD::FLD";
11074   case X86ISD::FST:                return "X86ISD::FST";
11075   case X86ISD::CALL:               return "X86ISD::CALL";
11076   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11077   case X86ISD::BT:                 return "X86ISD::BT";
11078   case X86ISD::CMP:                return "X86ISD::CMP";
11079   case X86ISD::COMI:               return "X86ISD::COMI";
11080   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11081   case X86ISD::SETCC:              return "X86ISD::SETCC";
11082   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11083   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11084   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11085   case X86ISD::CMOV:               return "X86ISD::CMOV";
11086   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11087   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11088   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11089   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11090   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11091   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11092   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11093   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11094   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11095   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11096   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11097   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11098   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11099   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11100   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11101   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11102   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11103   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11104   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11105   case X86ISD::HADD:               return "X86ISD::HADD";
11106   case X86ISD::HSUB:               return "X86ISD::HSUB";
11107   case X86ISD::FHADD:              return "X86ISD::FHADD";
11108   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11109   case X86ISD::FMAX:               return "X86ISD::FMAX";
11110   case X86ISD::FMIN:               return "X86ISD::FMIN";
11111   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11112   case X86ISD::FRCP:               return "X86ISD::FRCP";
11113   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11114   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11115   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11116   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11117   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11118   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11119   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11120   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11121   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11122   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11123   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11124   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11125   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11126   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11127   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11128   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11129   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11130   case X86ISD::VSHL:               return "X86ISD::VSHL";
11131   case X86ISD::VSRL:               return "X86ISD::VSRL";
11132   case X86ISD::VSRA:               return "X86ISD::VSRA";
11133   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11134   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11135   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11136   case X86ISD::CMPP:               return "X86ISD::CMPP";
11137   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11138   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11139   case X86ISD::ADD:                return "X86ISD::ADD";
11140   case X86ISD::SUB:                return "X86ISD::SUB";
11141   case X86ISD::ADC:                return "X86ISD::ADC";
11142   case X86ISD::SBB:                return "X86ISD::SBB";
11143   case X86ISD::SMUL:               return "X86ISD::SMUL";
11144   case X86ISD::UMUL:               return "X86ISD::UMUL";
11145   case X86ISD::INC:                return "X86ISD::INC";
11146   case X86ISD::DEC:                return "X86ISD::DEC";
11147   case X86ISD::OR:                 return "X86ISD::OR";
11148   case X86ISD::XOR:                return "X86ISD::XOR";
11149   case X86ISD::AND:                return "X86ISD::AND";
11150   case X86ISD::ANDN:               return "X86ISD::ANDN";
11151   case X86ISD::BLSI:               return "X86ISD::BLSI";
11152   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11153   case X86ISD::BLSR:               return "X86ISD::BLSR";
11154   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11155   case X86ISD::PTEST:              return "X86ISD::PTEST";
11156   case X86ISD::TESTP:              return "X86ISD::TESTP";
11157   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11158   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11159   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11160   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11161   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11162   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11163   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11164   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11165   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11166   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11167   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11168   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11169   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11170   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11171   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11172   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11173   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11174   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11175   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11176   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11177   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11178   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11179   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11180   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11181   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11182   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11183   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11184   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11185   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11186   }
11187 }
11188
11189 // isLegalAddressingMode - Return true if the addressing mode represented
11190 // by AM is legal for this target, for a load/store of the specified type.
11191 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11192                                               Type *Ty) const {
11193   // X86 supports extremely general addressing modes.
11194   CodeModel::Model M = getTargetMachine().getCodeModel();
11195   Reloc::Model R = getTargetMachine().getRelocationModel();
11196
11197   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11198   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11199     return false;
11200
11201   if (AM.BaseGV) {
11202     unsigned GVFlags =
11203       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11204
11205     // If a reference to this global requires an extra load, we can't fold it.
11206     if (isGlobalStubReference(GVFlags))
11207       return false;
11208
11209     // If BaseGV requires a register for the PIC base, we cannot also have a
11210     // BaseReg specified.
11211     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11212       return false;
11213
11214     // If lower 4G is not available, then we must use rip-relative addressing.
11215     if ((M != CodeModel::Small || R != Reloc::Static) &&
11216         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11217       return false;
11218   }
11219
11220   switch (AM.Scale) {
11221   case 0:
11222   case 1:
11223   case 2:
11224   case 4:
11225   case 8:
11226     // These scales always work.
11227     break;
11228   case 3:
11229   case 5:
11230   case 9:
11231     // These scales are formed with basereg+scalereg.  Only accept if there is
11232     // no basereg yet.
11233     if (AM.HasBaseReg)
11234       return false;
11235     break;
11236   default:  // Other stuff never works.
11237     return false;
11238   }
11239
11240   return true;
11241 }
11242
11243
11244 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11245   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11246     return false;
11247   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11248   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11249   if (NumBits1 <= NumBits2)
11250     return false;
11251   return true;
11252 }
11253
11254 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11255   if (!VT1.isInteger() || !VT2.isInteger())
11256     return false;
11257   unsigned NumBits1 = VT1.getSizeInBits();
11258   unsigned NumBits2 = VT2.getSizeInBits();
11259   if (NumBits1 <= NumBits2)
11260     return false;
11261   return true;
11262 }
11263
11264 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11265   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11266   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11267 }
11268
11269 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11270   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11271   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11272 }
11273
11274 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11275   // i16 instructions are longer (0x66 prefix) and potentially slower.
11276   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11277 }
11278
11279 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11280 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11281 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11282 /// are assumed to be legal.
11283 bool
11284 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11285                                       EVT VT) const {
11286   // Very little shuffling can be done for 64-bit vectors right now.
11287   if (VT.getSizeInBits() == 64)
11288     return false;
11289
11290   // FIXME: pshufb, blends, shifts.
11291   return (VT.getVectorNumElements() == 2 ||
11292           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11293           isMOVLMask(M, VT) ||
11294           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11295           isPSHUFDMask(M, VT) ||
11296           isPSHUFHWMask(M, VT) ||
11297           isPSHUFLWMask(M, VT) ||
11298           isPALIGNRMask(M, VT, Subtarget) ||
11299           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11300           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11301           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11302           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11303 }
11304
11305 bool
11306 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11307                                           EVT VT) const {
11308   unsigned NumElts = VT.getVectorNumElements();
11309   // FIXME: This collection of masks seems suspect.
11310   if (NumElts == 2)
11311     return true;
11312   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11313     return (isMOVLMask(Mask, VT)  ||
11314             isCommutedMOVLMask(Mask, VT, true) ||
11315             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11316             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11317   }
11318   return false;
11319 }
11320
11321 //===----------------------------------------------------------------------===//
11322 //                           X86 Scheduler Hooks
11323 //===----------------------------------------------------------------------===//
11324
11325 // private utility function
11326 MachineBasicBlock *
11327 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11328                                                        MachineBasicBlock *MBB,
11329                                                        unsigned regOpc,
11330                                                        unsigned immOpc,
11331                                                        unsigned LoadOpc,
11332                                                        unsigned CXchgOpc,
11333                                                        unsigned notOpc,
11334                                                        unsigned EAXreg,
11335                                                  const TargetRegisterClass *RC,
11336                                                        bool Invert) const {
11337   // For the atomic bitwise operator, we generate
11338   //   thisMBB:
11339   //   newMBB:
11340   //     ld  t1 = [bitinstr.addr]
11341   //     op  t2 = t1, [bitinstr.val]
11342   //     not t3 = t2  (if Invert)
11343   //     mov EAX = t1
11344   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11345   //     bz  newMBB
11346   //     fallthrough -->nextMBB
11347   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11348   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11349   MachineFunction::iterator MBBIter = MBB;
11350   ++MBBIter;
11351
11352   /// First build the CFG
11353   MachineFunction *F = MBB->getParent();
11354   MachineBasicBlock *thisMBB = MBB;
11355   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11356   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11357   F->insert(MBBIter, newMBB);
11358   F->insert(MBBIter, nextMBB);
11359
11360   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11361   nextMBB->splice(nextMBB->begin(), thisMBB,
11362                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11363                   thisMBB->end());
11364   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11365
11366   // Update thisMBB to fall through to newMBB
11367   thisMBB->addSuccessor(newMBB);
11368
11369   // newMBB jumps to itself and fall through to nextMBB
11370   newMBB->addSuccessor(nextMBB);
11371   newMBB->addSuccessor(newMBB);
11372
11373   // Insert instructions into newMBB based on incoming instruction
11374   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11375          "unexpected number of operands");
11376   DebugLoc dl = bInstr->getDebugLoc();
11377   MachineOperand& destOper = bInstr->getOperand(0);
11378   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11379   int numArgs = bInstr->getNumOperands() - 1;
11380   for (int i=0; i < numArgs; ++i)
11381     argOpers[i] = &bInstr->getOperand(i+1);
11382
11383   // x86 address has 4 operands: base, index, scale, and displacement
11384   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11385   int valArgIndx = lastAddrIndx + 1;
11386
11387   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11388   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11389   for (int i=0; i <= lastAddrIndx; ++i)
11390     (*MIB).addOperand(*argOpers[i]);
11391
11392   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11393   assert((argOpers[valArgIndx]->isReg() ||
11394           argOpers[valArgIndx]->isImm()) &&
11395          "invalid operand");
11396   if (argOpers[valArgIndx]->isReg())
11397     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11398   else
11399     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11400   MIB.addReg(t1);
11401   (*MIB).addOperand(*argOpers[valArgIndx]);
11402
11403   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11404   if (Invert) {
11405     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11406   }
11407   else
11408     t3 = t2;
11409
11410   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11411   MIB.addReg(t1);
11412
11413   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11414   for (int i=0; i <= lastAddrIndx; ++i)
11415     (*MIB).addOperand(*argOpers[i]);
11416   MIB.addReg(t3);
11417   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11418   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11419                     bInstr->memoperands_end());
11420
11421   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11422   MIB.addReg(EAXreg);
11423
11424   // insert branch
11425   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11426
11427   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11428   return nextMBB;
11429 }
11430
11431 // private utility function:  64 bit atomics on 32 bit host.
11432 MachineBasicBlock *
11433 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11434                                                        MachineBasicBlock *MBB,
11435                                                        unsigned regOpcL,
11436                                                        unsigned regOpcH,
11437                                                        unsigned immOpcL,
11438                                                        unsigned immOpcH,
11439                                                        bool Invert) const {
11440   // For the atomic bitwise operator, we generate
11441   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11442   //     ld t1,t2 = [bitinstr.addr]
11443   //   newMBB:
11444   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11445   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11446   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11447   //     neg t7, t8 < t5, t6  (if Invert)
11448   //     mov ECX, EBX <- t5, t6
11449   //     mov EAX, EDX <- t1, t2
11450   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11451   //     mov t3, t4 <- EAX, EDX
11452   //     bz  newMBB
11453   //     result in out1, out2
11454   //     fallthrough -->nextMBB
11455
11456   const TargetRegisterClass *RC = &X86::GR32RegClass;
11457   const unsigned LoadOpc = X86::MOV32rm;
11458   const unsigned NotOpc = X86::NOT32r;
11459   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11460   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11461   MachineFunction::iterator MBBIter = MBB;
11462   ++MBBIter;
11463
11464   /// First build the CFG
11465   MachineFunction *F = MBB->getParent();
11466   MachineBasicBlock *thisMBB = MBB;
11467   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11468   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11469   F->insert(MBBIter, newMBB);
11470   F->insert(MBBIter, nextMBB);
11471
11472   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11473   nextMBB->splice(nextMBB->begin(), thisMBB,
11474                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11475                   thisMBB->end());
11476   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11477
11478   // Update thisMBB to fall through to newMBB
11479   thisMBB->addSuccessor(newMBB);
11480
11481   // newMBB jumps to itself and fall through to nextMBB
11482   newMBB->addSuccessor(nextMBB);
11483   newMBB->addSuccessor(newMBB);
11484
11485   DebugLoc dl = bInstr->getDebugLoc();
11486   // Insert instructions into newMBB based on incoming instruction
11487   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11488   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11489          "unexpected number of operands");
11490   MachineOperand& dest1Oper = bInstr->getOperand(0);
11491   MachineOperand& dest2Oper = bInstr->getOperand(1);
11492   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11493   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11494     argOpers[i] = &bInstr->getOperand(i+2);
11495
11496     // We use some of the operands multiple times, so conservatively just
11497     // clear any kill flags that might be present.
11498     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11499       argOpers[i]->setIsKill(false);
11500   }
11501
11502   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11503   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11504
11505   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11506   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11507   for (int i=0; i <= lastAddrIndx; ++i)
11508     (*MIB).addOperand(*argOpers[i]);
11509   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11510   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11511   // add 4 to displacement.
11512   for (int i=0; i <= lastAddrIndx-2; ++i)
11513     (*MIB).addOperand(*argOpers[i]);
11514   MachineOperand newOp3 = *(argOpers[3]);
11515   if (newOp3.isImm())
11516     newOp3.setImm(newOp3.getImm()+4);
11517   else
11518     newOp3.setOffset(newOp3.getOffset()+4);
11519   (*MIB).addOperand(newOp3);
11520   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11521
11522   // t3/4 are defined later, at the bottom of the loop
11523   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11524   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11525   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11526     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11527   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11528     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11529
11530   // The subsequent operations should be using the destination registers of
11531   // the PHI instructions.
11532   t1 = dest1Oper.getReg();
11533   t2 = dest2Oper.getReg();
11534
11535   int valArgIndx = lastAddrIndx + 1;
11536   assert((argOpers[valArgIndx]->isReg() ||
11537           argOpers[valArgIndx]->isImm()) &&
11538          "invalid operand");
11539   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11540   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11541   if (argOpers[valArgIndx]->isReg())
11542     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11543   else
11544     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11545   if (regOpcL != X86::MOV32rr)
11546     MIB.addReg(t1);
11547   (*MIB).addOperand(*argOpers[valArgIndx]);
11548   assert(argOpers[valArgIndx + 1]->isReg() ==
11549          argOpers[valArgIndx]->isReg());
11550   assert(argOpers[valArgIndx + 1]->isImm() ==
11551          argOpers[valArgIndx]->isImm());
11552   if (argOpers[valArgIndx + 1]->isReg())
11553     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11554   else
11555     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11556   if (regOpcH != X86::MOV32rr)
11557     MIB.addReg(t2);
11558   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11559
11560   unsigned t7, t8;
11561   if (Invert) {
11562     t7 = F->getRegInfo().createVirtualRegister(RC);
11563     t8 = F->getRegInfo().createVirtualRegister(RC);
11564     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11565     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11566   } else {
11567     t7 = t5;
11568     t8 = t6;
11569   }
11570
11571   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11572   MIB.addReg(t1);
11573   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11574   MIB.addReg(t2);
11575
11576   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11577   MIB.addReg(t7);
11578   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11579   MIB.addReg(t8);
11580
11581   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11582   for (int i=0; i <= lastAddrIndx; ++i)
11583     (*MIB).addOperand(*argOpers[i]);
11584
11585   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11586   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11587                     bInstr->memoperands_end());
11588
11589   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11590   MIB.addReg(X86::EAX);
11591   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11592   MIB.addReg(X86::EDX);
11593
11594   // insert branch
11595   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11596
11597   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11598   return nextMBB;
11599 }
11600
11601 // private utility function
11602 MachineBasicBlock *
11603 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11604                                                       MachineBasicBlock *MBB,
11605                                                       unsigned cmovOpc) const {
11606   // For the atomic min/max operator, we generate
11607   //   thisMBB:
11608   //   newMBB:
11609   //     ld t1 = [min/max.addr]
11610   //     mov t2 = [min/max.val]
11611   //     cmp  t1, t2
11612   //     cmov[cond] t2 = t1
11613   //     mov EAX = t1
11614   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11615   //     bz   newMBB
11616   //     fallthrough -->nextMBB
11617   //
11618   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11619   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11620   MachineFunction::iterator MBBIter = MBB;
11621   ++MBBIter;
11622
11623   /// First build the CFG
11624   MachineFunction *F = MBB->getParent();
11625   MachineBasicBlock *thisMBB = MBB;
11626   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11627   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11628   F->insert(MBBIter, newMBB);
11629   F->insert(MBBIter, nextMBB);
11630
11631   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11632   nextMBB->splice(nextMBB->begin(), thisMBB,
11633                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11634                   thisMBB->end());
11635   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11636
11637   // Update thisMBB to fall through to newMBB
11638   thisMBB->addSuccessor(newMBB);
11639
11640   // newMBB jumps to newMBB and fall through to nextMBB
11641   newMBB->addSuccessor(nextMBB);
11642   newMBB->addSuccessor(newMBB);
11643
11644   DebugLoc dl = mInstr->getDebugLoc();
11645   // Insert instructions into newMBB based on incoming instruction
11646   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11647          "unexpected number of operands");
11648   MachineOperand& destOper = mInstr->getOperand(0);
11649   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11650   int numArgs = mInstr->getNumOperands() - 1;
11651   for (int i=0; i < numArgs; ++i)
11652     argOpers[i] = &mInstr->getOperand(i+1);
11653
11654   // x86 address has 4 operands: base, index, scale, and displacement
11655   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11656   int valArgIndx = lastAddrIndx + 1;
11657
11658   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11659   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11660   for (int i=0; i <= lastAddrIndx; ++i)
11661     (*MIB).addOperand(*argOpers[i]);
11662
11663   // We only support register and immediate values
11664   assert((argOpers[valArgIndx]->isReg() ||
11665           argOpers[valArgIndx]->isImm()) &&
11666          "invalid operand");
11667
11668   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11669   if (argOpers[valArgIndx]->isReg())
11670     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11671   else
11672     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11673   (*MIB).addOperand(*argOpers[valArgIndx]);
11674
11675   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11676   MIB.addReg(t1);
11677
11678   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11679   MIB.addReg(t1);
11680   MIB.addReg(t2);
11681
11682   // Generate movc
11683   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11684   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11685   MIB.addReg(t2);
11686   MIB.addReg(t1);
11687
11688   // Cmp and exchange if none has modified the memory location
11689   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11690   for (int i=0; i <= lastAddrIndx; ++i)
11691     (*MIB).addOperand(*argOpers[i]);
11692   MIB.addReg(t3);
11693   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11694   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11695                     mInstr->memoperands_end());
11696
11697   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11698   MIB.addReg(X86::EAX);
11699
11700   // insert branch
11701   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11702
11703   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11704   return nextMBB;
11705 }
11706
11707 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11708 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11709 // in the .td file.
11710 MachineBasicBlock *
11711 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11712                             unsigned numArgs, bool memArg) const {
11713   assert(Subtarget->hasSSE42() &&
11714          "Target must have SSE4.2 or AVX features enabled");
11715
11716   DebugLoc dl = MI->getDebugLoc();
11717   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11718   unsigned Opc;
11719   if (!Subtarget->hasAVX()) {
11720     if (memArg)
11721       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11722     else
11723       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11724   } else {
11725     if (memArg)
11726       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11727     else
11728       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11729   }
11730
11731   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11732   for (unsigned i = 0; i < numArgs; ++i) {
11733     MachineOperand &Op = MI->getOperand(i+1);
11734     if (!(Op.isReg() && Op.isImplicit()))
11735       MIB.addOperand(Op);
11736   }
11737   BuildMI(*BB, MI, dl,
11738     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11739              MI->getOperand(0).getReg())
11740     .addReg(X86::XMM0);
11741
11742   MI->eraseFromParent();
11743   return BB;
11744 }
11745
11746 MachineBasicBlock *
11747 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11748   DebugLoc dl = MI->getDebugLoc();
11749   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11750
11751   // Address into RAX/EAX, other two args into ECX, EDX.
11752   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11753   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11754   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11755   for (int i = 0; i < X86::AddrNumOperands; ++i)
11756     MIB.addOperand(MI->getOperand(i));
11757
11758   unsigned ValOps = X86::AddrNumOperands;
11759   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11760     .addReg(MI->getOperand(ValOps).getReg());
11761   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11762     .addReg(MI->getOperand(ValOps+1).getReg());
11763
11764   // The instruction doesn't actually take any operands though.
11765   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11766
11767   MI->eraseFromParent(); // The pseudo is gone now.
11768   return BB;
11769 }
11770
11771 MachineBasicBlock *
11772 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11773   DebugLoc dl = MI->getDebugLoc();
11774   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11775
11776   // First arg in ECX, the second in EAX.
11777   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11778     .addReg(MI->getOperand(0).getReg());
11779   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11780     .addReg(MI->getOperand(1).getReg());
11781
11782   // The instruction doesn't actually take any operands though.
11783   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11784
11785   MI->eraseFromParent(); // The pseudo is gone now.
11786   return BB;
11787 }
11788
11789 MachineBasicBlock *
11790 X86TargetLowering::EmitVAARG64WithCustomInserter(
11791                    MachineInstr *MI,
11792                    MachineBasicBlock *MBB) const {
11793   // Emit va_arg instruction on X86-64.
11794
11795   // Operands to this pseudo-instruction:
11796   // 0  ) Output        : destination address (reg)
11797   // 1-5) Input         : va_list address (addr, i64mem)
11798   // 6  ) ArgSize       : Size (in bytes) of vararg type
11799   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11800   // 8  ) Align         : Alignment of type
11801   // 9  ) EFLAGS (implicit-def)
11802
11803   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11804   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11805
11806   unsigned DestReg = MI->getOperand(0).getReg();
11807   MachineOperand &Base = MI->getOperand(1);
11808   MachineOperand &Scale = MI->getOperand(2);
11809   MachineOperand &Index = MI->getOperand(3);
11810   MachineOperand &Disp = MI->getOperand(4);
11811   MachineOperand &Segment = MI->getOperand(5);
11812   unsigned ArgSize = MI->getOperand(6).getImm();
11813   unsigned ArgMode = MI->getOperand(7).getImm();
11814   unsigned Align = MI->getOperand(8).getImm();
11815
11816   // Memory Reference
11817   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11818   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11819   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11820
11821   // Machine Information
11822   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11823   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11824   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11825   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11826   DebugLoc DL = MI->getDebugLoc();
11827
11828   // struct va_list {
11829   //   i32   gp_offset
11830   //   i32   fp_offset
11831   //   i64   overflow_area (address)
11832   //   i64   reg_save_area (address)
11833   // }
11834   // sizeof(va_list) = 24
11835   // alignment(va_list) = 8
11836
11837   unsigned TotalNumIntRegs = 6;
11838   unsigned TotalNumXMMRegs = 8;
11839   bool UseGPOffset = (ArgMode == 1);
11840   bool UseFPOffset = (ArgMode == 2);
11841   unsigned MaxOffset = TotalNumIntRegs * 8 +
11842                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11843
11844   /* Align ArgSize to a multiple of 8 */
11845   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11846   bool NeedsAlign = (Align > 8);
11847
11848   MachineBasicBlock *thisMBB = MBB;
11849   MachineBasicBlock *overflowMBB;
11850   MachineBasicBlock *offsetMBB;
11851   MachineBasicBlock *endMBB;
11852
11853   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11854   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11855   unsigned OffsetReg = 0;
11856
11857   if (!UseGPOffset && !UseFPOffset) {
11858     // If we only pull from the overflow region, we don't create a branch.
11859     // We don't need to alter control flow.
11860     OffsetDestReg = 0; // unused
11861     OverflowDestReg = DestReg;
11862
11863     offsetMBB = NULL;
11864     overflowMBB = thisMBB;
11865     endMBB = thisMBB;
11866   } else {
11867     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11868     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11869     // If not, pull from overflow_area. (branch to overflowMBB)
11870     //
11871     //       thisMBB
11872     //         |     .
11873     //         |        .
11874     //     offsetMBB   overflowMBB
11875     //         |        .
11876     //         |     .
11877     //        endMBB
11878
11879     // Registers for the PHI in endMBB
11880     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11881     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11882
11883     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11884     MachineFunction *MF = MBB->getParent();
11885     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11886     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11887     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11888
11889     MachineFunction::iterator MBBIter = MBB;
11890     ++MBBIter;
11891
11892     // Insert the new basic blocks
11893     MF->insert(MBBIter, offsetMBB);
11894     MF->insert(MBBIter, overflowMBB);
11895     MF->insert(MBBIter, endMBB);
11896
11897     // Transfer the remainder of MBB and its successor edges to endMBB.
11898     endMBB->splice(endMBB->begin(), thisMBB,
11899                     llvm::next(MachineBasicBlock::iterator(MI)),
11900                     thisMBB->end());
11901     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11902
11903     // Make offsetMBB and overflowMBB successors of thisMBB
11904     thisMBB->addSuccessor(offsetMBB);
11905     thisMBB->addSuccessor(overflowMBB);
11906
11907     // endMBB is a successor of both offsetMBB and overflowMBB
11908     offsetMBB->addSuccessor(endMBB);
11909     overflowMBB->addSuccessor(endMBB);
11910
11911     // Load the offset value into a register
11912     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11913     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11914       .addOperand(Base)
11915       .addOperand(Scale)
11916       .addOperand(Index)
11917       .addDisp(Disp, UseFPOffset ? 4 : 0)
11918       .addOperand(Segment)
11919       .setMemRefs(MMOBegin, MMOEnd);
11920
11921     // Check if there is enough room left to pull this argument.
11922     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11923       .addReg(OffsetReg)
11924       .addImm(MaxOffset + 8 - ArgSizeA8);
11925
11926     // Branch to "overflowMBB" if offset >= max
11927     // Fall through to "offsetMBB" otherwise
11928     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11929       .addMBB(overflowMBB);
11930   }
11931
11932   // In offsetMBB, emit code to use the reg_save_area.
11933   if (offsetMBB) {
11934     assert(OffsetReg != 0);
11935
11936     // Read the reg_save_area address.
11937     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11938     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11939       .addOperand(Base)
11940       .addOperand(Scale)
11941       .addOperand(Index)
11942       .addDisp(Disp, 16)
11943       .addOperand(Segment)
11944       .setMemRefs(MMOBegin, MMOEnd);
11945
11946     // Zero-extend the offset
11947     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11948       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11949         .addImm(0)
11950         .addReg(OffsetReg)
11951         .addImm(X86::sub_32bit);
11952
11953     // Add the offset to the reg_save_area to get the final address.
11954     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11955       .addReg(OffsetReg64)
11956       .addReg(RegSaveReg);
11957
11958     // Compute the offset for the next argument
11959     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11960     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11961       .addReg(OffsetReg)
11962       .addImm(UseFPOffset ? 16 : 8);
11963
11964     // Store it back into the va_list.
11965     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11966       .addOperand(Base)
11967       .addOperand(Scale)
11968       .addOperand(Index)
11969       .addDisp(Disp, UseFPOffset ? 4 : 0)
11970       .addOperand(Segment)
11971       .addReg(NextOffsetReg)
11972       .setMemRefs(MMOBegin, MMOEnd);
11973
11974     // Jump to endMBB
11975     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11976       .addMBB(endMBB);
11977   }
11978
11979   //
11980   // Emit code to use overflow area
11981   //
11982
11983   // Load the overflow_area address into a register.
11984   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11985   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11986     .addOperand(Base)
11987     .addOperand(Scale)
11988     .addOperand(Index)
11989     .addDisp(Disp, 8)
11990     .addOperand(Segment)
11991     .setMemRefs(MMOBegin, MMOEnd);
11992
11993   // If we need to align it, do so. Otherwise, just copy the address
11994   // to OverflowDestReg.
11995   if (NeedsAlign) {
11996     // Align the overflow address
11997     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11998     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11999
12000     // aligned_addr = (addr + (align-1)) & ~(align-1)
12001     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12002       .addReg(OverflowAddrReg)
12003       .addImm(Align-1);
12004
12005     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12006       .addReg(TmpReg)
12007       .addImm(~(uint64_t)(Align-1));
12008   } else {
12009     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12010       .addReg(OverflowAddrReg);
12011   }
12012
12013   // Compute the next overflow address after this argument.
12014   // (the overflow address should be kept 8-byte aligned)
12015   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12016   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12017     .addReg(OverflowDestReg)
12018     .addImm(ArgSizeA8);
12019
12020   // Store the new overflow address.
12021   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12022     .addOperand(Base)
12023     .addOperand(Scale)
12024     .addOperand(Index)
12025     .addDisp(Disp, 8)
12026     .addOperand(Segment)
12027     .addReg(NextAddrReg)
12028     .setMemRefs(MMOBegin, MMOEnd);
12029
12030   // If we branched, emit the PHI to the front of endMBB.
12031   if (offsetMBB) {
12032     BuildMI(*endMBB, endMBB->begin(), DL,
12033             TII->get(X86::PHI), DestReg)
12034       .addReg(OffsetDestReg).addMBB(offsetMBB)
12035       .addReg(OverflowDestReg).addMBB(overflowMBB);
12036   }
12037
12038   // Erase the pseudo instruction
12039   MI->eraseFromParent();
12040
12041   return endMBB;
12042 }
12043
12044 MachineBasicBlock *
12045 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12046                                                  MachineInstr *MI,
12047                                                  MachineBasicBlock *MBB) const {
12048   // Emit code to save XMM registers to the stack. The ABI says that the
12049   // number of registers to save is given in %al, so it's theoretically
12050   // possible to do an indirect jump trick to avoid saving all of them,
12051   // however this code takes a simpler approach and just executes all
12052   // of the stores if %al is non-zero. It's less code, and it's probably
12053   // easier on the hardware branch predictor, and stores aren't all that
12054   // expensive anyway.
12055
12056   // Create the new basic blocks. One block contains all the XMM stores,
12057   // and one block is the final destination regardless of whether any
12058   // stores were performed.
12059   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12060   MachineFunction *F = MBB->getParent();
12061   MachineFunction::iterator MBBIter = MBB;
12062   ++MBBIter;
12063   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12064   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12065   F->insert(MBBIter, XMMSaveMBB);
12066   F->insert(MBBIter, EndMBB);
12067
12068   // Transfer the remainder of MBB and its successor edges to EndMBB.
12069   EndMBB->splice(EndMBB->begin(), MBB,
12070                  llvm::next(MachineBasicBlock::iterator(MI)),
12071                  MBB->end());
12072   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12073
12074   // The original block will now fall through to the XMM save block.
12075   MBB->addSuccessor(XMMSaveMBB);
12076   // The XMMSaveMBB will fall through to the end block.
12077   XMMSaveMBB->addSuccessor(EndMBB);
12078
12079   // Now add the instructions.
12080   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12081   DebugLoc DL = MI->getDebugLoc();
12082
12083   unsigned CountReg = MI->getOperand(0).getReg();
12084   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12085   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12086
12087   if (!Subtarget->isTargetWin64()) {
12088     // If %al is 0, branch around the XMM save block.
12089     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12090     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12091     MBB->addSuccessor(EndMBB);
12092   }
12093
12094   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12095   // In the XMM save block, save all the XMM argument registers.
12096   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12097     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12098     MachineMemOperand *MMO =
12099       F->getMachineMemOperand(
12100           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12101         MachineMemOperand::MOStore,
12102         /*Size=*/16, /*Align=*/16);
12103     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12104       .addFrameIndex(RegSaveFrameIndex)
12105       .addImm(/*Scale=*/1)
12106       .addReg(/*IndexReg=*/0)
12107       .addImm(/*Disp=*/Offset)
12108       .addReg(/*Segment=*/0)
12109       .addReg(MI->getOperand(i).getReg())
12110       .addMemOperand(MMO);
12111   }
12112
12113   MI->eraseFromParent();   // The pseudo instruction is gone now.
12114
12115   return EndMBB;
12116 }
12117
12118 // The EFLAGS operand of SelectItr might be missing a kill marker
12119 // because there were multiple uses of EFLAGS, and ISel didn't know
12120 // which to mark. Figure out whether SelectItr should have had a
12121 // kill marker, and set it if it should. Returns the correct kill
12122 // marker value.
12123 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12124                                      MachineBasicBlock* BB,
12125                                      const TargetRegisterInfo* TRI) {
12126   // Scan forward through BB for a use/def of EFLAGS.
12127   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12128   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12129     const MachineInstr& mi = *miI;
12130     if (mi.readsRegister(X86::EFLAGS))
12131       return false;
12132     if (mi.definesRegister(X86::EFLAGS))
12133       break; // Should have kill-flag - update below.
12134   }
12135
12136   // If we hit the end of the block, check whether EFLAGS is live into a
12137   // successor.
12138   if (miI == BB->end()) {
12139     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12140                                           sEnd = BB->succ_end();
12141          sItr != sEnd; ++sItr) {
12142       MachineBasicBlock* succ = *sItr;
12143       if (succ->isLiveIn(X86::EFLAGS))
12144         return false;
12145     }
12146   }
12147
12148   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12149   // out. SelectMI should have a kill flag on EFLAGS.
12150   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12151   return true;
12152 }
12153
12154 MachineBasicBlock *
12155 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12156                                      MachineBasicBlock *BB) const {
12157   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12158   DebugLoc DL = MI->getDebugLoc();
12159
12160   // To "insert" a SELECT_CC instruction, we actually have to insert the
12161   // diamond control-flow pattern.  The incoming instruction knows the
12162   // destination vreg to set, the condition code register to branch on, the
12163   // true/false values to select between, and a branch opcode to use.
12164   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12165   MachineFunction::iterator It = BB;
12166   ++It;
12167
12168   //  thisMBB:
12169   //  ...
12170   //   TrueVal = ...
12171   //   cmpTY ccX, r1, r2
12172   //   bCC copy1MBB
12173   //   fallthrough --> copy0MBB
12174   MachineBasicBlock *thisMBB = BB;
12175   MachineFunction *F = BB->getParent();
12176   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12177   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12178   F->insert(It, copy0MBB);
12179   F->insert(It, sinkMBB);
12180
12181   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12182   // live into the sink and copy blocks.
12183   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12184   if (!MI->killsRegister(X86::EFLAGS) &&
12185       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12186     copy0MBB->addLiveIn(X86::EFLAGS);
12187     sinkMBB->addLiveIn(X86::EFLAGS);
12188   }
12189
12190   // Transfer the remainder of BB and its successor edges to sinkMBB.
12191   sinkMBB->splice(sinkMBB->begin(), BB,
12192                   llvm::next(MachineBasicBlock::iterator(MI)),
12193                   BB->end());
12194   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12195
12196   // Add the true and fallthrough blocks as its successors.
12197   BB->addSuccessor(copy0MBB);
12198   BB->addSuccessor(sinkMBB);
12199
12200   // Create the conditional branch instruction.
12201   unsigned Opc =
12202     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12203   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12204
12205   //  copy0MBB:
12206   //   %FalseValue = ...
12207   //   # fallthrough to sinkMBB
12208   copy0MBB->addSuccessor(sinkMBB);
12209
12210   //  sinkMBB:
12211   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12212   //  ...
12213   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12214           TII->get(X86::PHI), MI->getOperand(0).getReg())
12215     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12216     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12217
12218   MI->eraseFromParent();   // The pseudo instruction is gone now.
12219   return sinkMBB;
12220 }
12221
12222 MachineBasicBlock *
12223 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12224                                         bool Is64Bit) const {
12225   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12226   DebugLoc DL = MI->getDebugLoc();
12227   MachineFunction *MF = BB->getParent();
12228   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12229
12230   assert(getTargetMachine().Options.EnableSegmentedStacks);
12231
12232   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12233   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12234
12235   // BB:
12236   //  ... [Till the alloca]
12237   // If stacklet is not large enough, jump to mallocMBB
12238   //
12239   // bumpMBB:
12240   //  Allocate by subtracting from RSP
12241   //  Jump to continueMBB
12242   //
12243   // mallocMBB:
12244   //  Allocate by call to runtime
12245   //
12246   // continueMBB:
12247   //  ...
12248   //  [rest of original BB]
12249   //
12250
12251   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12252   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12253   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12254
12255   MachineRegisterInfo &MRI = MF->getRegInfo();
12256   const TargetRegisterClass *AddrRegClass =
12257     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12258
12259   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12260     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12261     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12262     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12263     sizeVReg = MI->getOperand(1).getReg(),
12264     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12265
12266   MachineFunction::iterator MBBIter = BB;
12267   ++MBBIter;
12268
12269   MF->insert(MBBIter, bumpMBB);
12270   MF->insert(MBBIter, mallocMBB);
12271   MF->insert(MBBIter, continueMBB);
12272
12273   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12274                       (MachineBasicBlock::iterator(MI)), BB->end());
12275   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12276
12277   // Add code to the main basic block to check if the stack limit has been hit,
12278   // and if so, jump to mallocMBB otherwise to bumpMBB.
12279   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12280   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12281     .addReg(tmpSPVReg).addReg(sizeVReg);
12282   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12283     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12284     .addReg(SPLimitVReg);
12285   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12286
12287   // bumpMBB simply decreases the stack pointer, since we know the current
12288   // stacklet has enough space.
12289   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12290     .addReg(SPLimitVReg);
12291   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12292     .addReg(SPLimitVReg);
12293   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12294
12295   // Calls into a routine in libgcc to allocate more space from the heap.
12296   const uint32_t *RegMask =
12297     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12298   if (Is64Bit) {
12299     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12300       .addReg(sizeVReg);
12301     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12302       .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12303       .addRegMask(RegMask)
12304       .addReg(X86::RAX, RegState::ImplicitDefine);
12305   } else {
12306     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12307       .addImm(12);
12308     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12309     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12310       .addExternalSymbol("__morestack_allocate_stack_space")
12311       .addRegMask(RegMask)
12312       .addReg(X86::EAX, RegState::ImplicitDefine);
12313   }
12314
12315   if (!Is64Bit)
12316     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12317       .addImm(16);
12318
12319   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12320     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12321   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12322
12323   // Set up the CFG correctly.
12324   BB->addSuccessor(bumpMBB);
12325   BB->addSuccessor(mallocMBB);
12326   mallocMBB->addSuccessor(continueMBB);
12327   bumpMBB->addSuccessor(continueMBB);
12328
12329   // Take care of the PHI nodes.
12330   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12331           MI->getOperand(0).getReg())
12332     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12333     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12334
12335   // Delete the original pseudo instruction.
12336   MI->eraseFromParent();
12337
12338   // And we're done.
12339   return continueMBB;
12340 }
12341
12342 MachineBasicBlock *
12343 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12344                                           MachineBasicBlock *BB) const {
12345   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12346   DebugLoc DL = MI->getDebugLoc();
12347
12348   assert(!Subtarget->isTargetEnvMacho());
12349
12350   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12351   // non-trivial part is impdef of ESP.
12352
12353   if (Subtarget->isTargetWin64()) {
12354     if (Subtarget->isTargetCygMing()) {
12355       // ___chkstk(Mingw64):
12356       // Clobbers R10, R11, RAX and EFLAGS.
12357       // Updates RSP.
12358       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12359         .addExternalSymbol("___chkstk")
12360         .addReg(X86::RAX, RegState::Implicit)
12361         .addReg(X86::RSP, RegState::Implicit)
12362         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12363         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12364         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12365     } else {
12366       // __chkstk(MSVCRT): does not update stack pointer.
12367       // Clobbers R10, R11 and EFLAGS.
12368       // FIXME: RAX(allocated size) might be reused and not killed.
12369       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12370         .addExternalSymbol("__chkstk")
12371         .addReg(X86::RAX, RegState::Implicit)
12372         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12373       // RAX has the offset to subtracted from RSP.
12374       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12375         .addReg(X86::RSP)
12376         .addReg(X86::RAX);
12377     }
12378   } else {
12379     const char *StackProbeSymbol =
12380       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12381
12382     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12383       .addExternalSymbol(StackProbeSymbol)
12384       .addReg(X86::EAX, RegState::Implicit)
12385       .addReg(X86::ESP, RegState::Implicit)
12386       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12387       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12388       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12389   }
12390
12391   MI->eraseFromParent();   // The pseudo instruction is gone now.
12392   return BB;
12393 }
12394
12395 MachineBasicBlock *
12396 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12397                                       MachineBasicBlock *BB) const {
12398   // This is pretty easy.  We're taking the value that we received from
12399   // our load from the relocation, sticking it in either RDI (x86-64)
12400   // or EAX and doing an indirect call.  The return value will then
12401   // be in the normal return register.
12402   const X86InstrInfo *TII
12403     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12404   DebugLoc DL = MI->getDebugLoc();
12405   MachineFunction *F = BB->getParent();
12406
12407   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12408   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12409
12410   // Get a register mask for the lowered call.
12411   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12412   // proper register mask.
12413   const uint32_t *RegMask =
12414     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12415   if (Subtarget->is64Bit()) {
12416     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12417                                       TII->get(X86::MOV64rm), X86::RDI)
12418     .addReg(X86::RIP)
12419     .addImm(0).addReg(0)
12420     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12421                       MI->getOperand(3).getTargetFlags())
12422     .addReg(0);
12423     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12424     addDirectMem(MIB, X86::RDI);
12425     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12426   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12427     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12428                                       TII->get(X86::MOV32rm), X86::EAX)
12429     .addReg(0)
12430     .addImm(0).addReg(0)
12431     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12432                       MI->getOperand(3).getTargetFlags())
12433     .addReg(0);
12434     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12435     addDirectMem(MIB, X86::EAX);
12436     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12437   } else {
12438     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12439                                       TII->get(X86::MOV32rm), X86::EAX)
12440     .addReg(TII->getGlobalBaseReg(F))
12441     .addImm(0).addReg(0)
12442     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12443                       MI->getOperand(3).getTargetFlags())
12444     .addReg(0);
12445     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12446     addDirectMem(MIB, X86::EAX);
12447     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12448   }
12449
12450   MI->eraseFromParent(); // The pseudo instruction is gone now.
12451   return BB;
12452 }
12453
12454 MachineBasicBlock *
12455 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12456                                                MachineBasicBlock *BB) const {
12457   switch (MI->getOpcode()) {
12458   default: llvm_unreachable("Unexpected instr type to insert");
12459   case X86::TAILJMPd64:
12460   case X86::TAILJMPr64:
12461   case X86::TAILJMPm64:
12462     llvm_unreachable("TAILJMP64 would not be touched here.");
12463   case X86::TCRETURNdi64:
12464   case X86::TCRETURNri64:
12465   case X86::TCRETURNmi64:
12466     return BB;
12467   case X86::WIN_ALLOCA:
12468     return EmitLoweredWinAlloca(MI, BB);
12469   case X86::SEG_ALLOCA_32:
12470     return EmitLoweredSegAlloca(MI, BB, false);
12471   case X86::SEG_ALLOCA_64:
12472     return EmitLoweredSegAlloca(MI, BB, true);
12473   case X86::TLSCall_32:
12474   case X86::TLSCall_64:
12475     return EmitLoweredTLSCall(MI, BB);
12476   case X86::CMOV_GR8:
12477   case X86::CMOV_FR32:
12478   case X86::CMOV_FR64:
12479   case X86::CMOV_V4F32:
12480   case X86::CMOV_V2F64:
12481   case X86::CMOV_V2I64:
12482   case X86::CMOV_V8F32:
12483   case X86::CMOV_V4F64:
12484   case X86::CMOV_V4I64:
12485   case X86::CMOV_GR16:
12486   case X86::CMOV_GR32:
12487   case X86::CMOV_RFP32:
12488   case X86::CMOV_RFP64:
12489   case X86::CMOV_RFP80:
12490     return EmitLoweredSelect(MI, BB);
12491
12492   case X86::FP32_TO_INT16_IN_MEM:
12493   case X86::FP32_TO_INT32_IN_MEM:
12494   case X86::FP32_TO_INT64_IN_MEM:
12495   case X86::FP64_TO_INT16_IN_MEM:
12496   case X86::FP64_TO_INT32_IN_MEM:
12497   case X86::FP64_TO_INT64_IN_MEM:
12498   case X86::FP80_TO_INT16_IN_MEM:
12499   case X86::FP80_TO_INT32_IN_MEM:
12500   case X86::FP80_TO_INT64_IN_MEM: {
12501     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12502     DebugLoc DL = MI->getDebugLoc();
12503
12504     // Change the floating point control register to use "round towards zero"
12505     // mode when truncating to an integer value.
12506     MachineFunction *F = BB->getParent();
12507     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12508     addFrameReference(BuildMI(*BB, MI, DL,
12509                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12510
12511     // Load the old value of the high byte of the control word...
12512     unsigned OldCW =
12513       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12514     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12515                       CWFrameIdx);
12516
12517     // Set the high part to be round to zero...
12518     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12519       .addImm(0xC7F);
12520
12521     // Reload the modified control word now...
12522     addFrameReference(BuildMI(*BB, MI, DL,
12523                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12524
12525     // Restore the memory image of control word to original value
12526     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12527       .addReg(OldCW);
12528
12529     // Get the X86 opcode to use.
12530     unsigned Opc;
12531     switch (MI->getOpcode()) {
12532     default: llvm_unreachable("illegal opcode!");
12533     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12534     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12535     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12536     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12537     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12538     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12539     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12540     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12541     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12542     }
12543
12544     X86AddressMode AM;
12545     MachineOperand &Op = MI->getOperand(0);
12546     if (Op.isReg()) {
12547       AM.BaseType = X86AddressMode::RegBase;
12548       AM.Base.Reg = Op.getReg();
12549     } else {
12550       AM.BaseType = X86AddressMode::FrameIndexBase;
12551       AM.Base.FrameIndex = Op.getIndex();
12552     }
12553     Op = MI->getOperand(1);
12554     if (Op.isImm())
12555       AM.Scale = Op.getImm();
12556     Op = MI->getOperand(2);
12557     if (Op.isImm())
12558       AM.IndexReg = Op.getImm();
12559     Op = MI->getOperand(3);
12560     if (Op.isGlobal()) {
12561       AM.GV = Op.getGlobal();
12562     } else {
12563       AM.Disp = Op.getImm();
12564     }
12565     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12566                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12567
12568     // Reload the original control word now.
12569     addFrameReference(BuildMI(*BB, MI, DL,
12570                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12571
12572     MI->eraseFromParent();   // The pseudo instruction is gone now.
12573     return BB;
12574   }
12575     // String/text processing lowering.
12576   case X86::PCMPISTRM128REG:
12577   case X86::VPCMPISTRM128REG:
12578     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12579   case X86::PCMPISTRM128MEM:
12580   case X86::VPCMPISTRM128MEM:
12581     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12582   case X86::PCMPESTRM128REG:
12583   case X86::VPCMPESTRM128REG:
12584     return EmitPCMP(MI, BB, 5, false /* in mem */);
12585   case X86::PCMPESTRM128MEM:
12586   case X86::VPCMPESTRM128MEM:
12587     return EmitPCMP(MI, BB, 5, true /* in mem */);
12588
12589     // Thread synchronization.
12590   case X86::MONITOR:
12591     return EmitMonitor(MI, BB);
12592   case X86::MWAIT:
12593     return EmitMwait(MI, BB);
12594
12595     // Atomic Lowering.
12596   case X86::ATOMAND32:
12597     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12598                                                X86::AND32ri, X86::MOV32rm,
12599                                                X86::LCMPXCHG32,
12600                                                X86::NOT32r, X86::EAX,
12601                                                &X86::GR32RegClass);
12602   case X86::ATOMOR32:
12603     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12604                                                X86::OR32ri, X86::MOV32rm,
12605                                                X86::LCMPXCHG32,
12606                                                X86::NOT32r, X86::EAX,
12607                                                &X86::GR32RegClass);
12608   case X86::ATOMXOR32:
12609     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12610                                                X86::XOR32ri, X86::MOV32rm,
12611                                                X86::LCMPXCHG32,
12612                                                X86::NOT32r, X86::EAX,
12613                                                &X86::GR32RegClass);
12614   case X86::ATOMNAND32:
12615     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12616                                                X86::AND32ri, X86::MOV32rm,
12617                                                X86::LCMPXCHG32,
12618                                                X86::NOT32r, X86::EAX,
12619                                                &X86::GR32RegClass, true);
12620   case X86::ATOMMIN32:
12621     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12622   case X86::ATOMMAX32:
12623     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12624   case X86::ATOMUMIN32:
12625     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12626   case X86::ATOMUMAX32:
12627     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12628
12629   case X86::ATOMAND16:
12630     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12631                                                X86::AND16ri, X86::MOV16rm,
12632                                                X86::LCMPXCHG16,
12633                                                X86::NOT16r, X86::AX,
12634                                                &X86::GR16RegClass);
12635   case X86::ATOMOR16:
12636     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12637                                                X86::OR16ri, X86::MOV16rm,
12638                                                X86::LCMPXCHG16,
12639                                                X86::NOT16r, X86::AX,
12640                                                &X86::GR16RegClass);
12641   case X86::ATOMXOR16:
12642     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12643                                                X86::XOR16ri, X86::MOV16rm,
12644                                                X86::LCMPXCHG16,
12645                                                X86::NOT16r, X86::AX,
12646                                                &X86::GR16RegClass);
12647   case X86::ATOMNAND16:
12648     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12649                                                X86::AND16ri, X86::MOV16rm,
12650                                                X86::LCMPXCHG16,
12651                                                X86::NOT16r, X86::AX,
12652                                                &X86::GR16RegClass, true);
12653   case X86::ATOMMIN16:
12654     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12655   case X86::ATOMMAX16:
12656     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12657   case X86::ATOMUMIN16:
12658     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12659   case X86::ATOMUMAX16:
12660     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12661
12662   case X86::ATOMAND8:
12663     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12664                                                X86::AND8ri, X86::MOV8rm,
12665                                                X86::LCMPXCHG8,
12666                                                X86::NOT8r, X86::AL,
12667                                                &X86::GR8RegClass);
12668   case X86::ATOMOR8:
12669     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12670                                                X86::OR8ri, X86::MOV8rm,
12671                                                X86::LCMPXCHG8,
12672                                                X86::NOT8r, X86::AL,
12673                                                &X86::GR8RegClass);
12674   case X86::ATOMXOR8:
12675     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12676                                                X86::XOR8ri, X86::MOV8rm,
12677                                                X86::LCMPXCHG8,
12678                                                X86::NOT8r, X86::AL,
12679                                                &X86::GR8RegClass);
12680   case X86::ATOMNAND8:
12681     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12682                                                X86::AND8ri, X86::MOV8rm,
12683                                                X86::LCMPXCHG8,
12684                                                X86::NOT8r, X86::AL,
12685                                                &X86::GR8RegClass, true);
12686   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12687   // This group is for 64-bit host.
12688   case X86::ATOMAND64:
12689     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12690                                                X86::AND64ri32, X86::MOV64rm,
12691                                                X86::LCMPXCHG64,
12692                                                X86::NOT64r, X86::RAX,
12693                                                &X86::GR64RegClass);
12694   case X86::ATOMOR64:
12695     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12696                                                X86::OR64ri32, X86::MOV64rm,
12697                                                X86::LCMPXCHG64,
12698                                                X86::NOT64r, X86::RAX,
12699                                                &X86::GR64RegClass);
12700   case X86::ATOMXOR64:
12701     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12702                                                X86::XOR64ri32, X86::MOV64rm,
12703                                                X86::LCMPXCHG64,
12704                                                X86::NOT64r, X86::RAX,
12705                                                &X86::GR64RegClass);
12706   case X86::ATOMNAND64:
12707     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12708                                                X86::AND64ri32, X86::MOV64rm,
12709                                                X86::LCMPXCHG64,
12710                                                X86::NOT64r, X86::RAX,
12711                                                &X86::GR64RegClass, true);
12712   case X86::ATOMMIN64:
12713     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12714   case X86::ATOMMAX64:
12715     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12716   case X86::ATOMUMIN64:
12717     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12718   case X86::ATOMUMAX64:
12719     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12720
12721   // This group does 64-bit operations on a 32-bit host.
12722   case X86::ATOMAND6432:
12723     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12724                                                X86::AND32rr, X86::AND32rr,
12725                                                X86::AND32ri, X86::AND32ri,
12726                                                false);
12727   case X86::ATOMOR6432:
12728     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12729                                                X86::OR32rr, X86::OR32rr,
12730                                                X86::OR32ri, X86::OR32ri,
12731                                                false);
12732   case X86::ATOMXOR6432:
12733     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12734                                                X86::XOR32rr, X86::XOR32rr,
12735                                                X86::XOR32ri, X86::XOR32ri,
12736                                                false);
12737   case X86::ATOMNAND6432:
12738     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12739                                                X86::AND32rr, X86::AND32rr,
12740                                                X86::AND32ri, X86::AND32ri,
12741                                                true);
12742   case X86::ATOMADD6432:
12743     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12744                                                X86::ADD32rr, X86::ADC32rr,
12745                                                X86::ADD32ri, X86::ADC32ri,
12746                                                false);
12747   case X86::ATOMSUB6432:
12748     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12749                                                X86::SUB32rr, X86::SBB32rr,
12750                                                X86::SUB32ri, X86::SBB32ri,
12751                                                false);
12752   case X86::ATOMSWAP6432:
12753     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12754                                                X86::MOV32rr, X86::MOV32rr,
12755                                                X86::MOV32ri, X86::MOV32ri,
12756                                                false);
12757   case X86::VASTART_SAVE_XMM_REGS:
12758     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12759
12760   case X86::VAARG_64:
12761     return EmitVAARG64WithCustomInserter(MI, BB);
12762   }
12763 }
12764
12765 //===----------------------------------------------------------------------===//
12766 //                           X86 Optimization Hooks
12767 //===----------------------------------------------------------------------===//
12768
12769 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12770                                                        APInt &KnownZero,
12771                                                        APInt &KnownOne,
12772                                                        const SelectionDAG &DAG,
12773                                                        unsigned Depth) const {
12774   unsigned BitWidth = KnownZero.getBitWidth();
12775   unsigned Opc = Op.getOpcode();
12776   assert((Opc >= ISD::BUILTIN_OP_END ||
12777           Opc == ISD::INTRINSIC_WO_CHAIN ||
12778           Opc == ISD::INTRINSIC_W_CHAIN ||
12779           Opc == ISD::INTRINSIC_VOID) &&
12780          "Should use MaskedValueIsZero if you don't know whether Op"
12781          " is a target node!");
12782
12783   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12784   switch (Opc) {
12785   default: break;
12786   case X86ISD::ADD:
12787   case X86ISD::SUB:
12788   case X86ISD::ADC:
12789   case X86ISD::SBB:
12790   case X86ISD::SMUL:
12791   case X86ISD::UMUL:
12792   case X86ISD::INC:
12793   case X86ISD::DEC:
12794   case X86ISD::OR:
12795   case X86ISD::XOR:
12796   case X86ISD::AND:
12797     // These nodes' second result is a boolean.
12798     if (Op.getResNo() == 0)
12799       break;
12800     // Fallthrough
12801   case X86ISD::SETCC:
12802     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12803     break;
12804   case ISD::INTRINSIC_WO_CHAIN: {
12805     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12806     unsigned NumLoBits = 0;
12807     switch (IntId) {
12808     default: break;
12809     case Intrinsic::x86_sse_movmsk_ps:
12810     case Intrinsic::x86_avx_movmsk_ps_256:
12811     case Intrinsic::x86_sse2_movmsk_pd:
12812     case Intrinsic::x86_avx_movmsk_pd_256:
12813     case Intrinsic::x86_mmx_pmovmskb:
12814     case Intrinsic::x86_sse2_pmovmskb_128:
12815     case Intrinsic::x86_avx2_pmovmskb: {
12816       // High bits of movmskp{s|d}, pmovmskb are known zero.
12817       switch (IntId) {
12818         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12819         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12820         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12821         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12822         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12823         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12824         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12825         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12826       }
12827       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12828       break;
12829     }
12830     }
12831     break;
12832   }
12833   }
12834 }
12835
12836 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12837                                                          unsigned Depth) const {
12838   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12839   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12840     return Op.getValueType().getScalarType().getSizeInBits();
12841
12842   // Fallback case.
12843   return 1;
12844 }
12845
12846 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12847 /// node is a GlobalAddress + offset.
12848 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12849                                        const GlobalValue* &GA,
12850                                        int64_t &Offset) const {
12851   if (N->getOpcode() == X86ISD::Wrapper) {
12852     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12853       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12854       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12855       return true;
12856     }
12857   }
12858   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12859 }
12860
12861 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12862 /// same as extracting the high 128-bit part of 256-bit vector and then
12863 /// inserting the result into the low part of a new 256-bit vector
12864 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12865   EVT VT = SVOp->getValueType(0);
12866   int NumElems = VT.getVectorNumElements();
12867
12868   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12869   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12870     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12871         SVOp->getMaskElt(j) >= 0)
12872       return false;
12873
12874   return true;
12875 }
12876
12877 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12878 /// same as extracting the low 128-bit part of 256-bit vector and then
12879 /// inserting the result into the high part of a new 256-bit vector
12880 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12881   EVT VT = SVOp->getValueType(0);
12882   int NumElems = VT.getVectorNumElements();
12883
12884   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12885   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12886     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12887         SVOp->getMaskElt(j) >= 0)
12888       return false;
12889
12890   return true;
12891 }
12892
12893 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12894 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12895                                         TargetLowering::DAGCombinerInfo &DCI,
12896                                         const X86Subtarget* Subtarget) {
12897   DebugLoc dl = N->getDebugLoc();
12898   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12899   SDValue V1 = SVOp->getOperand(0);
12900   SDValue V2 = SVOp->getOperand(1);
12901   EVT VT = SVOp->getValueType(0);
12902   int NumElems = VT.getVectorNumElements();
12903
12904   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12905       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12906     //
12907     //                   0,0,0,...
12908     //                      |
12909     //    V      UNDEF    BUILD_VECTOR    UNDEF
12910     //     \      /           \           /
12911     //  CONCAT_VECTOR         CONCAT_VECTOR
12912     //         \                  /
12913     //          \                /
12914     //          RESULT: V + zero extended
12915     //
12916     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12917         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12918         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12919       return SDValue();
12920
12921     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12922       return SDValue();
12923
12924     // To match the shuffle mask, the first half of the mask should
12925     // be exactly the first vector, and all the rest a splat with the
12926     // first element of the second one.
12927     for (int i = 0; i < NumElems/2; ++i)
12928       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12929           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12930         return SDValue();
12931
12932     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12933     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12934       SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
12935       SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
12936       SDValue ResNode =
12937         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
12938                                 Ld->getMemoryVT(),
12939                                 Ld->getPointerInfo(),
12940                                 Ld->getAlignment(),
12941                                 false/*isVolatile*/, true/*ReadMem*/,
12942                                 false/*WriteMem*/);
12943       return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
12944     } 
12945
12946     // Emit a zeroed vector and insert the desired subvector on its
12947     // first half.
12948     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12949     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
12950     return DCI.CombineTo(N, InsV);
12951   }
12952
12953   //===--------------------------------------------------------------------===//
12954   // Combine some shuffles into subvector extracts and inserts:
12955   //
12956
12957   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12958   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12959     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
12960     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
12961     return DCI.CombineTo(N, InsV);
12962   }
12963
12964   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12965   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12966     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
12967     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
12968     return DCI.CombineTo(N, InsV);
12969   }
12970
12971   return SDValue();
12972 }
12973
12974 /// PerformShuffleCombine - Performs several different shuffle combines.
12975 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12976                                      TargetLowering::DAGCombinerInfo &DCI,
12977                                      const X86Subtarget *Subtarget) {
12978   DebugLoc dl = N->getDebugLoc();
12979   EVT VT = N->getValueType(0);
12980
12981   // Don't create instructions with illegal types after legalize types has run.
12982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12983   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12984     return SDValue();
12985
12986   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12987   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12988       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12989     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
12990
12991   // Only handle 128 wide vector from here on.
12992   if (VT.getSizeInBits() != 128)
12993     return SDValue();
12994
12995   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12996   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12997   // consecutive, non-overlapping, and in the right order.
12998   SmallVector<SDValue, 16> Elts;
12999   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13000     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13001
13002   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13003 }
13004
13005
13006 /// PerformTruncateCombine - Converts truncate operation to
13007 /// a sequence of vector shuffle operations.
13008 /// It is possible when we truncate 256-bit vector to 128-bit vector
13009
13010 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13011                                                   DAGCombinerInfo &DCI) const {
13012   if (!DCI.isBeforeLegalizeOps())
13013     return SDValue();
13014
13015   if (!Subtarget->hasAVX()) return SDValue();
13016
13017   EVT VT = N->getValueType(0);
13018   SDValue Op = N->getOperand(0);
13019   EVT OpVT = Op.getValueType();
13020   DebugLoc dl = N->getDebugLoc();
13021
13022   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13023
13024     if (Subtarget->hasAVX2()) {
13025       // AVX2: v4i64 -> v4i32
13026
13027       // VPERMD
13028       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13029
13030       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13031       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13032                                 ShufMask);
13033
13034       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13035                          DAG.getIntPtrConstant(0));
13036     }
13037
13038     // AVX: v4i64 -> v4i32
13039     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13040                                DAG.getIntPtrConstant(0));
13041
13042     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13043                                DAG.getIntPtrConstant(2));
13044
13045     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13046     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13047
13048     // PSHUFD
13049     static const int ShufMask1[] = {0, 2, 0, 0};
13050
13051     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13052     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13053
13054     // MOVLHPS
13055     static const int ShufMask2[] = {0, 1, 4, 5};
13056
13057     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13058   }
13059
13060   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13061
13062     if (Subtarget->hasAVX2()) {
13063       // AVX2: v8i32 -> v8i16
13064
13065       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13066
13067       // PSHUFB
13068       SmallVector<SDValue,32> pshufbMask;
13069       for (unsigned i = 0; i < 2; ++i) {
13070         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13071         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13072         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13073         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13074         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13075         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13076         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13077         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13078         for (unsigned j = 0; j < 8; ++j)
13079           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13080       }
13081       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13082                                &pshufbMask[0], 32);
13083       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13084
13085       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13086
13087       static const int ShufMask[] = {0,  2,  -1,  -1};
13088       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13089                                 &ShufMask[0]);
13090
13091       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13092                        DAG.getIntPtrConstant(0));
13093
13094       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13095     }
13096
13097     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13098                                DAG.getIntPtrConstant(0));
13099
13100     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13101                                DAG.getIntPtrConstant(4));
13102
13103     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13104     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13105
13106     // PSHUFB
13107     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13108                                    -1, -1, -1, -1, -1, -1, -1, -1};
13109
13110     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13111                                 ShufMask1);
13112     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13113                                 ShufMask1);
13114
13115     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13116     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13117
13118     // MOVLHPS
13119     static const int ShufMask2[] = {0, 1, 4, 5};
13120
13121     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13122     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13123   }
13124
13125   return SDValue();
13126 }
13127
13128 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13129 /// specific shuffle of a load can be folded into a single element load.
13130 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13131 /// shuffles have been customed lowered so we need to handle those here.
13132 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13133                                          TargetLowering::DAGCombinerInfo &DCI) {
13134   if (DCI.isBeforeLegalizeOps())
13135     return SDValue();
13136
13137   SDValue InVec = N->getOperand(0);
13138   SDValue EltNo = N->getOperand(1);
13139
13140   if (!isa<ConstantSDNode>(EltNo))
13141     return SDValue();
13142
13143   EVT VT = InVec.getValueType();
13144
13145   bool HasShuffleIntoBitcast = false;
13146   if (InVec.getOpcode() == ISD::BITCAST) {
13147     // Don't duplicate a load with other uses.
13148     if (!InVec.hasOneUse())
13149       return SDValue();
13150     EVT BCVT = InVec.getOperand(0).getValueType();
13151     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13152       return SDValue();
13153     InVec = InVec.getOperand(0);
13154     HasShuffleIntoBitcast = true;
13155   }
13156
13157   if (!isTargetShuffle(InVec.getOpcode()))
13158     return SDValue();
13159
13160   // Don't duplicate a load with other uses.
13161   if (!InVec.hasOneUse())
13162     return SDValue();
13163
13164   SmallVector<int, 16> ShuffleMask;
13165   bool UnaryShuffle;
13166   if (!getTargetShuffleMask(InVec.getNode(), VT, ShuffleMask, UnaryShuffle))
13167     return SDValue();
13168
13169   // Select the input vector, guarding against out of range extract vector.
13170   unsigned NumElems = VT.getVectorNumElements();
13171   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13172   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13173   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13174                                          : InVec.getOperand(1);
13175
13176   // If inputs to shuffle are the same for both ops, then allow 2 uses
13177   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13178
13179   if (LdNode.getOpcode() == ISD::BITCAST) {
13180     // Don't duplicate a load with other uses.
13181     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13182       return SDValue();
13183
13184     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13185     LdNode = LdNode.getOperand(0);
13186   }
13187
13188   if (!ISD::isNormalLoad(LdNode.getNode()))
13189     return SDValue();
13190
13191   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13192
13193   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13194     return SDValue();
13195
13196   if (HasShuffleIntoBitcast) {
13197     // If there's a bitcast before the shuffle, check if the load type and
13198     // alignment is valid.
13199     unsigned Align = LN0->getAlignment();
13200     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13201     unsigned NewAlign = TLI.getTargetData()->
13202       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13203
13204     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13205       return SDValue();
13206   }
13207
13208   // All checks match so transform back to vector_shuffle so that DAG combiner
13209   // can finish the job
13210   DebugLoc dl = N->getDebugLoc();
13211
13212   // Create shuffle node taking into account the case that its a unary shuffle
13213   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13214   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13215                                  InVec.getOperand(0), Shuffle,
13216                                  &ShuffleMask[0]);
13217   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13218   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13219                      EltNo);
13220 }
13221
13222 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13223 /// generation and convert it from being a bunch of shuffles and extracts
13224 /// to a simple store and scalar loads to extract the elements.
13225 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13226                                          TargetLowering::DAGCombinerInfo &DCI) {
13227   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13228   if (NewOp.getNode())
13229     return NewOp;
13230
13231   SDValue InputVector = N->getOperand(0);
13232
13233   // Only operate on vectors of 4 elements, where the alternative shuffling
13234   // gets to be more expensive.
13235   if (InputVector.getValueType() != MVT::v4i32)
13236     return SDValue();
13237
13238   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13239   // single use which is a sign-extend or zero-extend, and all elements are
13240   // used.
13241   SmallVector<SDNode *, 4> Uses;
13242   unsigned ExtractedElements = 0;
13243   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13244        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13245     if (UI.getUse().getResNo() != InputVector.getResNo())
13246       return SDValue();
13247
13248     SDNode *Extract = *UI;
13249     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13250       return SDValue();
13251
13252     if (Extract->getValueType(0) != MVT::i32)
13253       return SDValue();
13254     if (!Extract->hasOneUse())
13255       return SDValue();
13256     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13257         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13258       return SDValue();
13259     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13260       return SDValue();
13261
13262     // Record which element was extracted.
13263     ExtractedElements |=
13264       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13265
13266     Uses.push_back(Extract);
13267   }
13268
13269   // If not all the elements were used, this may not be worthwhile.
13270   if (ExtractedElements != 15)
13271     return SDValue();
13272
13273   // Ok, we've now decided to do the transformation.
13274   DebugLoc dl = InputVector.getDebugLoc();
13275
13276   // Store the value to a temporary stack slot.
13277   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13278   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13279                             MachinePointerInfo(), false, false, 0);
13280
13281   // Replace each use (extract) with a load of the appropriate element.
13282   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13283        UE = Uses.end(); UI != UE; ++UI) {
13284     SDNode *Extract = *UI;
13285
13286     // cOMpute the element's address.
13287     SDValue Idx = Extract->getOperand(1);
13288     unsigned EltSize =
13289         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13290     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13291     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13292     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13293
13294     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13295                                      StackPtr, OffsetVal);
13296
13297     // Load the scalar.
13298     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13299                                      ScalarAddr, MachinePointerInfo(),
13300                                      false, false, false, 0);
13301
13302     // Replace the exact with the load.
13303     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13304   }
13305
13306   // The replacement was made in place; don't return anything.
13307   return SDValue();
13308 }
13309
13310 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13311 /// nodes.
13312 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13313                                     TargetLowering::DAGCombinerInfo &DCI,
13314                                     const X86Subtarget *Subtarget) {
13315
13316
13317   DebugLoc DL = N->getDebugLoc();
13318   SDValue Cond = N->getOperand(0);
13319   // Get the LHS/RHS of the select.
13320   SDValue LHS = N->getOperand(1);
13321   SDValue RHS = N->getOperand(2);
13322   EVT VT = LHS.getValueType();
13323
13324   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13325   // instructions match the semantics of the common C idiom x<y?x:y but not
13326   // x<=y?x:y, because of how they handle negative zero (which can be
13327   // ignored in unsafe-math mode).
13328   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13329       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13330       (Subtarget->hasSSE2() ||
13331        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13332     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13333
13334     unsigned Opcode = 0;
13335     // Check for x CC y ? x : y.
13336     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13337         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13338       switch (CC) {
13339       default: break;
13340       case ISD::SETULT:
13341         // Converting this to a min would handle NaNs incorrectly, and swapping
13342         // the operands would cause it to handle comparisons between positive
13343         // and negative zero incorrectly.
13344         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13345           if (!DAG.getTarget().Options.UnsafeFPMath &&
13346               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13347             break;
13348           std::swap(LHS, RHS);
13349         }
13350         Opcode = X86ISD::FMIN;
13351         break;
13352       case ISD::SETOLE:
13353         // Converting this to a min would handle comparisons between positive
13354         // and negative zero incorrectly.
13355         if (!DAG.getTarget().Options.UnsafeFPMath &&
13356             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13357           break;
13358         Opcode = X86ISD::FMIN;
13359         break;
13360       case ISD::SETULE:
13361         // Converting this to a min would handle both negative zeros and NaNs
13362         // incorrectly, but we can swap the operands to fix both.
13363         std::swap(LHS, RHS);
13364       case ISD::SETOLT:
13365       case ISD::SETLT:
13366       case ISD::SETLE:
13367         Opcode = X86ISD::FMIN;
13368         break;
13369
13370       case ISD::SETOGE:
13371         // Converting this to a max would handle comparisons between positive
13372         // and negative zero incorrectly.
13373         if (!DAG.getTarget().Options.UnsafeFPMath &&
13374             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13375           break;
13376         Opcode = X86ISD::FMAX;
13377         break;
13378       case ISD::SETUGT:
13379         // Converting this to a max would handle NaNs incorrectly, and swapping
13380         // the operands would cause it to handle comparisons between positive
13381         // and negative zero incorrectly.
13382         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13383           if (!DAG.getTarget().Options.UnsafeFPMath &&
13384               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13385             break;
13386           std::swap(LHS, RHS);
13387         }
13388         Opcode = X86ISD::FMAX;
13389         break;
13390       case ISD::SETUGE:
13391         // Converting this to a max would handle both negative zeros and NaNs
13392         // incorrectly, but we can swap the operands to fix both.
13393         std::swap(LHS, RHS);
13394       case ISD::SETOGT:
13395       case ISD::SETGT:
13396       case ISD::SETGE:
13397         Opcode = X86ISD::FMAX;
13398         break;
13399       }
13400     // Check for x CC y ? y : x -- a min/max with reversed arms.
13401     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13402                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13403       switch (CC) {
13404       default: break;
13405       case ISD::SETOGE:
13406         // Converting this to a min would handle comparisons between positive
13407         // and negative zero incorrectly, and swapping the operands would
13408         // cause it to handle NaNs incorrectly.
13409         if (!DAG.getTarget().Options.UnsafeFPMath &&
13410             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13411           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13412             break;
13413           std::swap(LHS, RHS);
13414         }
13415         Opcode = X86ISD::FMIN;
13416         break;
13417       case ISD::SETUGT:
13418         // Converting this to a min would handle NaNs incorrectly.
13419         if (!DAG.getTarget().Options.UnsafeFPMath &&
13420             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13421           break;
13422         Opcode = X86ISD::FMIN;
13423         break;
13424       case ISD::SETUGE:
13425         // Converting this to a min would handle both negative zeros and NaNs
13426         // incorrectly, but we can swap the operands to fix both.
13427         std::swap(LHS, RHS);
13428       case ISD::SETOGT:
13429       case ISD::SETGT:
13430       case ISD::SETGE:
13431         Opcode = X86ISD::FMIN;
13432         break;
13433
13434       case ISD::SETULT:
13435         // Converting this to a max would handle NaNs incorrectly.
13436         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13437           break;
13438         Opcode = X86ISD::FMAX;
13439         break;
13440       case ISD::SETOLE:
13441         // Converting this to a max would handle comparisons between positive
13442         // and negative zero incorrectly, and swapping the operands would
13443         // cause it to handle NaNs incorrectly.
13444         if (!DAG.getTarget().Options.UnsafeFPMath &&
13445             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13446           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13447             break;
13448           std::swap(LHS, RHS);
13449         }
13450         Opcode = X86ISD::FMAX;
13451         break;
13452       case ISD::SETULE:
13453         // Converting this to a max would handle both negative zeros and NaNs
13454         // incorrectly, but we can swap the operands to fix both.
13455         std::swap(LHS, RHS);
13456       case ISD::SETOLT:
13457       case ISD::SETLT:
13458       case ISD::SETLE:
13459         Opcode = X86ISD::FMAX;
13460         break;
13461       }
13462     }
13463
13464     if (Opcode)
13465       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13466   }
13467
13468   // If this is a select between two integer constants, try to do some
13469   // optimizations.
13470   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13471     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13472       // Don't do this for crazy integer types.
13473       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13474         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13475         // so that TrueC (the true value) is larger than FalseC.
13476         bool NeedsCondInvert = false;
13477
13478         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13479             // Efficiently invertible.
13480             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13481              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13482               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13483           NeedsCondInvert = true;
13484           std::swap(TrueC, FalseC);
13485         }
13486
13487         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13488         if (FalseC->getAPIntValue() == 0 &&
13489             TrueC->getAPIntValue().isPowerOf2()) {
13490           if (NeedsCondInvert) // Invert the condition if needed.
13491             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13492                                DAG.getConstant(1, Cond.getValueType()));
13493
13494           // Zero extend the condition if needed.
13495           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13496
13497           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13498           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13499                              DAG.getConstant(ShAmt, MVT::i8));
13500         }
13501
13502         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13503         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13504           if (NeedsCondInvert) // Invert the condition if needed.
13505             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13506                                DAG.getConstant(1, Cond.getValueType()));
13507
13508           // Zero extend the condition if needed.
13509           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13510                              FalseC->getValueType(0), Cond);
13511           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13512                              SDValue(FalseC, 0));
13513         }
13514
13515         // Optimize cases that will turn into an LEA instruction.  This requires
13516         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13517         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13518           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13519           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13520
13521           bool isFastMultiplier = false;
13522           if (Diff < 10) {
13523             switch ((unsigned char)Diff) {
13524               default: break;
13525               case 1:  // result = add base, cond
13526               case 2:  // result = lea base(    , cond*2)
13527               case 3:  // result = lea base(cond, cond*2)
13528               case 4:  // result = lea base(    , cond*4)
13529               case 5:  // result = lea base(cond, cond*4)
13530               case 8:  // result = lea base(    , cond*8)
13531               case 9:  // result = lea base(cond, cond*8)
13532                 isFastMultiplier = true;
13533                 break;
13534             }
13535           }
13536
13537           if (isFastMultiplier) {
13538             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13539             if (NeedsCondInvert) // Invert the condition if needed.
13540               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13541                                  DAG.getConstant(1, Cond.getValueType()));
13542
13543             // Zero extend the condition if needed.
13544             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13545                                Cond);
13546             // Scale the condition by the difference.
13547             if (Diff != 1)
13548               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13549                                  DAG.getConstant(Diff, Cond.getValueType()));
13550
13551             // Add the base if non-zero.
13552             if (FalseC->getAPIntValue() != 0)
13553               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13554                                  SDValue(FalseC, 0));
13555             return Cond;
13556           }
13557         }
13558       }
13559   }
13560
13561   // Canonicalize max and min:
13562   // (x > y) ? x : y -> (x >= y) ? x : y
13563   // (x < y) ? x : y -> (x <= y) ? x : y
13564   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13565   // the need for an extra compare
13566   // against zero. e.g.
13567   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13568   // subl   %esi, %edi
13569   // testl  %edi, %edi
13570   // movl   $0, %eax
13571   // cmovgl %edi, %eax
13572   // =>
13573   // xorl   %eax, %eax
13574   // subl   %esi, $edi
13575   // cmovsl %eax, %edi
13576   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13577       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13578       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13579     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13580     switch (CC) {
13581     default: break;
13582     case ISD::SETLT:
13583     case ISD::SETGT: {
13584       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13585       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13586                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13587       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13588     }
13589     }
13590   }
13591
13592   // If we know that this node is legal then we know that it is going to be
13593   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13594   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13595   // to simplify previous instructions.
13596   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13597   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13598       !DCI.isBeforeLegalize() &&
13599       TLI.isOperationLegal(ISD::VSELECT, VT)) {
13600     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13601     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13602     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13603
13604     APInt KnownZero, KnownOne;
13605     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13606                                           DCI.isBeforeLegalizeOps());
13607     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13608         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13609       DCI.CommitTargetLoweringOpt(TLO);
13610   }
13611
13612   return SDValue();
13613 }
13614
13615 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13616 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13617                                   TargetLowering::DAGCombinerInfo &DCI) {
13618   DebugLoc DL = N->getDebugLoc();
13619
13620   // If the flag operand isn't dead, don't touch this CMOV.
13621   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13622     return SDValue();
13623
13624   SDValue FalseOp = N->getOperand(0);
13625   SDValue TrueOp = N->getOperand(1);
13626   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13627   SDValue Cond = N->getOperand(3);
13628   if (CC == X86::COND_E || CC == X86::COND_NE) {
13629     switch (Cond.getOpcode()) {
13630     default: break;
13631     case X86ISD::BSR:
13632     case X86ISD::BSF:
13633       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13634       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13635         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13636     }
13637   }
13638
13639   // If this is a select between two integer constants, try to do some
13640   // optimizations.  Note that the operands are ordered the opposite of SELECT
13641   // operands.
13642   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13643     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13644       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13645       // larger than FalseC (the false value).
13646       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13647         CC = X86::GetOppositeBranchCondition(CC);
13648         std::swap(TrueC, FalseC);
13649       }
13650
13651       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13652       // This is efficient for any integer data type (including i8/i16) and
13653       // shift amount.
13654       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13655         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13656                            DAG.getConstant(CC, MVT::i8), Cond);
13657
13658         // Zero extend the condition if needed.
13659         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13660
13661         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13662         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13663                            DAG.getConstant(ShAmt, MVT::i8));
13664         if (N->getNumValues() == 2)  // Dead flag value?
13665           return DCI.CombineTo(N, Cond, SDValue());
13666         return Cond;
13667       }
13668
13669       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13670       // for any integer data type, including i8/i16.
13671       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13672         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13673                            DAG.getConstant(CC, MVT::i8), Cond);
13674
13675         // Zero extend the condition if needed.
13676         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13677                            FalseC->getValueType(0), Cond);
13678         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13679                            SDValue(FalseC, 0));
13680
13681         if (N->getNumValues() == 2)  // Dead flag value?
13682           return DCI.CombineTo(N, Cond, SDValue());
13683         return Cond;
13684       }
13685
13686       // Optimize cases that will turn into an LEA instruction.  This requires
13687       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13688       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13689         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13690         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13691
13692         bool isFastMultiplier = false;
13693         if (Diff < 10) {
13694           switch ((unsigned char)Diff) {
13695           default: break;
13696           case 1:  // result = add base, cond
13697           case 2:  // result = lea base(    , cond*2)
13698           case 3:  // result = lea base(cond, cond*2)
13699           case 4:  // result = lea base(    , cond*4)
13700           case 5:  // result = lea base(cond, cond*4)
13701           case 8:  // result = lea base(    , cond*8)
13702           case 9:  // result = lea base(cond, cond*8)
13703             isFastMultiplier = true;
13704             break;
13705           }
13706         }
13707
13708         if (isFastMultiplier) {
13709           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13710           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13711                              DAG.getConstant(CC, MVT::i8), Cond);
13712           // Zero extend the condition if needed.
13713           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13714                              Cond);
13715           // Scale the condition by the difference.
13716           if (Diff != 1)
13717             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13718                                DAG.getConstant(Diff, Cond.getValueType()));
13719
13720           // Add the base if non-zero.
13721           if (FalseC->getAPIntValue() != 0)
13722             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13723                                SDValue(FalseC, 0));
13724           if (N->getNumValues() == 2)  // Dead flag value?
13725             return DCI.CombineTo(N, Cond, SDValue());
13726           return Cond;
13727         }
13728       }
13729     }
13730   }
13731   return SDValue();
13732 }
13733
13734
13735 /// PerformMulCombine - Optimize a single multiply with constant into two
13736 /// in order to implement it with two cheaper instructions, e.g.
13737 /// LEA + SHL, LEA + LEA.
13738 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13739                                  TargetLowering::DAGCombinerInfo &DCI) {
13740   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13741     return SDValue();
13742
13743   EVT VT = N->getValueType(0);
13744   if (VT != MVT::i64)
13745     return SDValue();
13746
13747   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13748   if (!C)
13749     return SDValue();
13750   uint64_t MulAmt = C->getZExtValue();
13751   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13752     return SDValue();
13753
13754   uint64_t MulAmt1 = 0;
13755   uint64_t MulAmt2 = 0;
13756   if ((MulAmt % 9) == 0) {
13757     MulAmt1 = 9;
13758     MulAmt2 = MulAmt / 9;
13759   } else if ((MulAmt % 5) == 0) {
13760     MulAmt1 = 5;
13761     MulAmt2 = MulAmt / 5;
13762   } else if ((MulAmt % 3) == 0) {
13763     MulAmt1 = 3;
13764     MulAmt2 = MulAmt / 3;
13765   }
13766   if (MulAmt2 &&
13767       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13768     DebugLoc DL = N->getDebugLoc();
13769
13770     if (isPowerOf2_64(MulAmt2) &&
13771         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13772       // If second multiplifer is pow2, issue it first. We want the multiply by
13773       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13774       // is an add.
13775       std::swap(MulAmt1, MulAmt2);
13776
13777     SDValue NewMul;
13778     if (isPowerOf2_64(MulAmt1))
13779       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13780                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13781     else
13782       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13783                            DAG.getConstant(MulAmt1, VT));
13784
13785     if (isPowerOf2_64(MulAmt2))
13786       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13787                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13788     else
13789       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13790                            DAG.getConstant(MulAmt2, VT));
13791
13792     // Do not add new nodes to DAG combiner worklist.
13793     DCI.CombineTo(N, NewMul, false);
13794   }
13795   return SDValue();
13796 }
13797
13798 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13799   SDValue N0 = N->getOperand(0);
13800   SDValue N1 = N->getOperand(1);
13801   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13802   EVT VT = N0.getValueType();
13803
13804   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13805   // since the result of setcc_c is all zero's or all ones.
13806   if (VT.isInteger() && !VT.isVector() &&
13807       N1C && N0.getOpcode() == ISD::AND &&
13808       N0.getOperand(1).getOpcode() == ISD::Constant) {
13809     SDValue N00 = N0.getOperand(0);
13810     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13811         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13812           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13813          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13814       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13815       APInt ShAmt = N1C->getAPIntValue();
13816       Mask = Mask.shl(ShAmt);
13817       if (Mask != 0)
13818         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13819                            N00, DAG.getConstant(Mask, VT));
13820     }
13821   }
13822
13823
13824   // Hardware support for vector shifts is sparse which makes us scalarize the
13825   // vector operations in many cases. Also, on sandybridge ADD is faster than
13826   // shl.
13827   // (shl V, 1) -> add V,V
13828   if (isSplatVector(N1.getNode())) {
13829     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13830     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13831     // We shift all of the values by one. In many cases we do not have
13832     // hardware support for this operation. This is better expressed as an ADD
13833     // of two values.
13834     if (N1C && (1 == N1C->getZExtValue())) {
13835       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13836     }
13837   }
13838
13839   return SDValue();
13840 }
13841
13842 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13843 ///                       when possible.
13844 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13845                                    TargetLowering::DAGCombinerInfo &DCI,
13846                                    const X86Subtarget *Subtarget) {
13847   EVT VT = N->getValueType(0);
13848   if (N->getOpcode() == ISD::SHL) {
13849     SDValue V = PerformSHLCombine(N, DAG);
13850     if (V.getNode()) return V;
13851   }
13852
13853   // On X86 with SSE2 support, we can transform this to a vector shift if
13854   // all elements are shifted by the same amount.  We can't do this in legalize
13855   // because the a constant vector is typically transformed to a constant pool
13856   // so we have no knowledge of the shift amount.
13857   if (!Subtarget->hasSSE2())
13858     return SDValue();
13859
13860   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13861       (!Subtarget->hasAVX2() ||
13862        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13863     return SDValue();
13864
13865   SDValue ShAmtOp = N->getOperand(1);
13866   EVT EltVT = VT.getVectorElementType();
13867   DebugLoc DL = N->getDebugLoc();
13868   SDValue BaseShAmt = SDValue();
13869   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13870     unsigned NumElts = VT.getVectorNumElements();
13871     unsigned i = 0;
13872     for (; i != NumElts; ++i) {
13873       SDValue Arg = ShAmtOp.getOperand(i);
13874       if (Arg.getOpcode() == ISD::UNDEF) continue;
13875       BaseShAmt = Arg;
13876       break;
13877     }
13878     // Handle the case where the build_vector is all undef
13879     // FIXME: Should DAG allow this?
13880     if (i == NumElts)
13881       return SDValue();
13882
13883     for (; i != NumElts; ++i) {
13884       SDValue Arg = ShAmtOp.getOperand(i);
13885       if (Arg.getOpcode() == ISD::UNDEF) continue;
13886       if (Arg != BaseShAmt) {
13887         return SDValue();
13888       }
13889     }
13890   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13891              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13892     SDValue InVec = ShAmtOp.getOperand(0);
13893     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13894       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13895       unsigned i = 0;
13896       for (; i != NumElts; ++i) {
13897         SDValue Arg = InVec.getOperand(i);
13898         if (Arg.getOpcode() == ISD::UNDEF) continue;
13899         BaseShAmt = Arg;
13900         break;
13901       }
13902     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13903        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13904          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13905          if (C->getZExtValue() == SplatIdx)
13906            BaseShAmt = InVec.getOperand(1);
13907        }
13908     }
13909     if (BaseShAmt.getNode() == 0) {
13910       // Don't create instructions with illegal types after legalize
13911       // types has run.
13912       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13913           !DCI.isBeforeLegalize())
13914         return SDValue();
13915
13916       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13917                               DAG.getIntPtrConstant(0));
13918     }
13919   } else
13920     return SDValue();
13921
13922   // The shift amount is an i32.
13923   if (EltVT.bitsGT(MVT::i32))
13924     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13925   else if (EltVT.bitsLT(MVT::i32))
13926     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13927
13928   // The shift amount is identical so we can do a vector shift.
13929   SDValue  ValOp = N->getOperand(0);
13930   switch (N->getOpcode()) {
13931   default:
13932     llvm_unreachable("Unknown shift opcode!");
13933   case ISD::SHL:
13934     switch (VT.getSimpleVT().SimpleTy) {
13935     default: return SDValue();
13936     case MVT::v2i64:
13937     case MVT::v4i32:
13938     case MVT::v8i16:
13939     case MVT::v4i64:
13940     case MVT::v8i32:
13941     case MVT::v16i16:
13942       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
13943     }
13944   case ISD::SRA:
13945     switch (VT.getSimpleVT().SimpleTy) {
13946     default: return SDValue();
13947     case MVT::v4i32:
13948     case MVT::v8i16:
13949     case MVT::v8i32:
13950     case MVT::v16i16:
13951       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
13952     }
13953   case ISD::SRL:
13954     switch (VT.getSimpleVT().SimpleTy) {
13955     default: return SDValue();
13956     case MVT::v2i64:
13957     case MVT::v4i32:
13958     case MVT::v8i16:
13959     case MVT::v4i64:
13960     case MVT::v8i32:
13961     case MVT::v16i16:
13962       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
13963     }
13964   }
13965 }
13966
13967
13968 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13969 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13970 // and friends.  Likewise for OR -> CMPNEQSS.
13971 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13972                             TargetLowering::DAGCombinerInfo &DCI,
13973                             const X86Subtarget *Subtarget) {
13974   unsigned opcode;
13975
13976   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13977   // we're requiring SSE2 for both.
13978   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13979     SDValue N0 = N->getOperand(0);
13980     SDValue N1 = N->getOperand(1);
13981     SDValue CMP0 = N0->getOperand(1);
13982     SDValue CMP1 = N1->getOperand(1);
13983     DebugLoc DL = N->getDebugLoc();
13984
13985     // The SETCCs should both refer to the same CMP.
13986     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13987       return SDValue();
13988
13989     SDValue CMP00 = CMP0->getOperand(0);
13990     SDValue CMP01 = CMP0->getOperand(1);
13991     EVT     VT    = CMP00.getValueType();
13992
13993     if (VT == MVT::f32 || VT == MVT::f64) {
13994       bool ExpectingFlags = false;
13995       // Check for any users that want flags:
13996       for (SDNode::use_iterator UI = N->use_begin(),
13997              UE = N->use_end();
13998            !ExpectingFlags && UI != UE; ++UI)
13999         switch (UI->getOpcode()) {
14000         default:
14001         case ISD::BR_CC:
14002         case ISD::BRCOND:
14003         case ISD::SELECT:
14004           ExpectingFlags = true;
14005           break;
14006         case ISD::CopyToReg:
14007         case ISD::SIGN_EXTEND:
14008         case ISD::ZERO_EXTEND:
14009         case ISD::ANY_EXTEND:
14010           break;
14011         }
14012
14013       if (!ExpectingFlags) {
14014         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14015         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14016
14017         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14018           X86::CondCode tmp = cc0;
14019           cc0 = cc1;
14020           cc1 = tmp;
14021         }
14022
14023         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14024             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14025           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14026           X86ISD::NodeType NTOperator = is64BitFP ?
14027             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14028           // FIXME: need symbolic constants for these magic numbers.
14029           // See X86ATTInstPrinter.cpp:printSSECC().
14030           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14031           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14032                                               DAG.getConstant(x86cc, MVT::i8));
14033           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14034                                               OnesOrZeroesF);
14035           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14036                                       DAG.getConstant(1, MVT::i32));
14037           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14038           return OneBitOfTruth;
14039         }
14040       }
14041     }
14042   }
14043   return SDValue();
14044 }
14045
14046 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14047 /// so it can be folded inside ANDNP.
14048 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14049   EVT VT = N->getValueType(0);
14050
14051   // Match direct AllOnes for 128 and 256-bit vectors
14052   if (ISD::isBuildVectorAllOnes(N))
14053     return true;
14054
14055   // Look through a bit convert.
14056   if (N->getOpcode() == ISD::BITCAST)
14057     N = N->getOperand(0).getNode();
14058
14059   // Sometimes the operand may come from a insert_subvector building a 256-bit
14060   // allones vector
14061   if (VT.getSizeInBits() == 256 &&
14062       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14063     SDValue V1 = N->getOperand(0);
14064     SDValue V2 = N->getOperand(1);
14065
14066     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14067         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14068         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14069         ISD::isBuildVectorAllOnes(V2.getNode()))
14070       return true;
14071   }
14072
14073   return false;
14074 }
14075
14076 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14077                                  TargetLowering::DAGCombinerInfo &DCI,
14078                                  const X86Subtarget *Subtarget) {
14079   if (DCI.isBeforeLegalizeOps())
14080     return SDValue();
14081
14082   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14083   if (R.getNode())
14084     return R;
14085
14086   EVT VT = N->getValueType(0);
14087
14088   // Create ANDN, BLSI, and BLSR instructions
14089   // BLSI is X & (-X)
14090   // BLSR is X & (X-1)
14091   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14092     SDValue N0 = N->getOperand(0);
14093     SDValue N1 = N->getOperand(1);
14094     DebugLoc DL = N->getDebugLoc();
14095
14096     // Check LHS for not
14097     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14098       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14099     // Check RHS for not
14100     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14101       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14102
14103     // Check LHS for neg
14104     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14105         isZero(N0.getOperand(0)))
14106       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14107
14108     // Check RHS for neg
14109     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14110         isZero(N1.getOperand(0)))
14111       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14112
14113     // Check LHS for X-1
14114     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14115         isAllOnes(N0.getOperand(1)))
14116       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14117
14118     // Check RHS for X-1
14119     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14120         isAllOnes(N1.getOperand(1)))
14121       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14122
14123     return SDValue();
14124   }
14125
14126   // Want to form ANDNP nodes:
14127   // 1) In the hopes of then easily combining them with OR and AND nodes
14128   //    to form PBLEND/PSIGN.
14129   // 2) To match ANDN packed intrinsics
14130   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14131     return SDValue();
14132
14133   SDValue N0 = N->getOperand(0);
14134   SDValue N1 = N->getOperand(1);
14135   DebugLoc DL = N->getDebugLoc();
14136
14137   // Check LHS for vnot
14138   if (N0.getOpcode() == ISD::XOR &&
14139       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14140       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14141     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14142
14143   // Check RHS for vnot
14144   if (N1.getOpcode() == ISD::XOR &&
14145       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14146       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14147     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14148
14149   return SDValue();
14150 }
14151
14152 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14153                                 TargetLowering::DAGCombinerInfo &DCI,
14154                                 const X86Subtarget *Subtarget) {
14155   if (DCI.isBeforeLegalizeOps())
14156     return SDValue();
14157
14158   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14159   if (R.getNode())
14160     return R;
14161
14162   EVT VT = N->getValueType(0);
14163
14164   SDValue N0 = N->getOperand(0);
14165   SDValue N1 = N->getOperand(1);
14166
14167   // look for psign/blend
14168   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14169     if (!Subtarget->hasSSSE3() ||
14170         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14171       return SDValue();
14172
14173     // Canonicalize pandn to RHS
14174     if (N0.getOpcode() == X86ISD::ANDNP)
14175       std::swap(N0, N1);
14176     // or (and (m, y), (pandn m, x))
14177     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14178       SDValue Mask = N1.getOperand(0);
14179       SDValue X    = N1.getOperand(1);
14180       SDValue Y;
14181       if (N0.getOperand(0) == Mask)
14182         Y = N0.getOperand(1);
14183       if (N0.getOperand(1) == Mask)
14184         Y = N0.getOperand(0);
14185
14186       // Check to see if the mask appeared in both the AND and ANDNP and
14187       if (!Y.getNode())
14188         return SDValue();
14189
14190       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14191       // Look through mask bitcast.
14192       if (Mask.getOpcode() == ISD::BITCAST)
14193         Mask = Mask.getOperand(0);
14194       if (X.getOpcode() == ISD::BITCAST)
14195         X = X.getOperand(0);
14196       if (Y.getOpcode() == ISD::BITCAST)
14197         Y = Y.getOperand(0);
14198
14199       EVT MaskVT = Mask.getValueType();
14200
14201       // Validate that the Mask operand is a vector sra node.
14202       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14203       // there is no psrai.b
14204       if (Mask.getOpcode() != X86ISD::VSRAI)
14205         return SDValue();
14206
14207       // Check that the SRA is all signbits.
14208       SDValue SraC = Mask.getOperand(1);
14209       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14210       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14211       if ((SraAmt + 1) != EltBits)
14212         return SDValue();
14213
14214       DebugLoc DL = N->getDebugLoc();
14215
14216       // Now we know we at least have a plendvb with the mask val.  See if
14217       // we can form a psignb/w/d.
14218       // psign = x.type == y.type == mask.type && y = sub(0, x);
14219       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14220           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14221           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14222         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14223                "Unsupported VT for PSIGN");
14224         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14225         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14226       }
14227       // PBLENDVB only available on SSE 4.1
14228       if (!Subtarget->hasSSE41())
14229         return SDValue();
14230
14231       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14232
14233       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14234       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14235       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14236       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14237       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14238     }
14239   }
14240
14241   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14242     return SDValue();
14243
14244   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14245   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14246     std::swap(N0, N1);
14247   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14248     return SDValue();
14249   if (!N0.hasOneUse() || !N1.hasOneUse())
14250     return SDValue();
14251
14252   SDValue ShAmt0 = N0.getOperand(1);
14253   if (ShAmt0.getValueType() != MVT::i8)
14254     return SDValue();
14255   SDValue ShAmt1 = N1.getOperand(1);
14256   if (ShAmt1.getValueType() != MVT::i8)
14257     return SDValue();
14258   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14259     ShAmt0 = ShAmt0.getOperand(0);
14260   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14261     ShAmt1 = ShAmt1.getOperand(0);
14262
14263   DebugLoc DL = N->getDebugLoc();
14264   unsigned Opc = X86ISD::SHLD;
14265   SDValue Op0 = N0.getOperand(0);
14266   SDValue Op1 = N1.getOperand(0);
14267   if (ShAmt0.getOpcode() == ISD::SUB) {
14268     Opc = X86ISD::SHRD;
14269     std::swap(Op0, Op1);
14270     std::swap(ShAmt0, ShAmt1);
14271   }
14272
14273   unsigned Bits = VT.getSizeInBits();
14274   if (ShAmt1.getOpcode() == ISD::SUB) {
14275     SDValue Sum = ShAmt1.getOperand(0);
14276     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14277       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14278       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14279         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14280       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14281         return DAG.getNode(Opc, DL, VT,
14282                            Op0, Op1,
14283                            DAG.getNode(ISD::TRUNCATE, DL,
14284                                        MVT::i8, ShAmt0));
14285     }
14286   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14287     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14288     if (ShAmt0C &&
14289         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14290       return DAG.getNode(Opc, DL, VT,
14291                          N0.getOperand(0), N1.getOperand(0),
14292                          DAG.getNode(ISD::TRUNCATE, DL,
14293                                        MVT::i8, ShAmt0));
14294   }
14295
14296   return SDValue();
14297 }
14298
14299 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14300 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14301                                  TargetLowering::DAGCombinerInfo &DCI,
14302                                  const X86Subtarget *Subtarget) {
14303   if (DCI.isBeforeLegalizeOps())
14304     return SDValue();
14305
14306   EVT VT = N->getValueType(0);
14307
14308   if (VT != MVT::i32 && VT != MVT::i64)
14309     return SDValue();
14310
14311   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14312
14313   // Create BLSMSK instructions by finding X ^ (X-1)
14314   SDValue N0 = N->getOperand(0);
14315   SDValue N1 = N->getOperand(1);
14316   DebugLoc DL = N->getDebugLoc();
14317
14318   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14319       isAllOnes(N0.getOperand(1)))
14320     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14321
14322   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14323       isAllOnes(N1.getOperand(1)))
14324     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14325
14326   return SDValue();
14327 }
14328
14329 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14330 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14331                                    const X86Subtarget *Subtarget) {
14332   LoadSDNode *Ld = cast<LoadSDNode>(N);
14333   EVT RegVT = Ld->getValueType(0);
14334   EVT MemVT = Ld->getMemoryVT();
14335   DebugLoc dl = Ld->getDebugLoc();
14336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14337
14338   ISD::LoadExtType Ext = Ld->getExtensionType();
14339
14340   // If this is a vector EXT Load then attempt to optimize it using a
14341   // shuffle. We need SSE4 for the shuffles.
14342   // TODO: It is possible to support ZExt by zeroing the undef values
14343   // during the shuffle phase or after the shuffle.
14344   if (RegVT.isVector() && RegVT.isInteger() &&
14345       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14346     assert(MemVT != RegVT && "Cannot extend to the same type");
14347     assert(MemVT.isVector() && "Must load a vector from memory");
14348
14349     unsigned NumElems = RegVT.getVectorNumElements();
14350     unsigned RegSz = RegVT.getSizeInBits();
14351     unsigned MemSz = MemVT.getSizeInBits();
14352     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14353     // All sizes must be a power of two
14354     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14355
14356     // Attempt to load the original value using a single load op.
14357     // Find a scalar type which is equal to the loaded word size.
14358     MVT SclrLoadTy = MVT::i8;
14359     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14360          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14361       MVT Tp = (MVT::SimpleValueType)tp;
14362       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14363         SclrLoadTy = Tp;
14364         break;
14365       }
14366     }
14367
14368     // Proceed if a load word is found.
14369     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14370
14371     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14372       RegSz/SclrLoadTy.getSizeInBits());
14373
14374     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14375                                   RegSz/MemVT.getScalarType().getSizeInBits());
14376     // Can't shuffle using an illegal type.
14377     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14378
14379     // Perform a single load.
14380     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14381                                   Ld->getBasePtr(),
14382                                   Ld->getPointerInfo(), Ld->isVolatile(),
14383                                   Ld->isNonTemporal(), Ld->isInvariant(),
14384                                   Ld->getAlignment());
14385
14386     // Insert the word loaded into a vector.
14387     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14388       LoadUnitVecVT, ScalarLoad);
14389
14390     // Bitcast the loaded value to a vector of the original element type, in
14391     // the size of the target vector type.
14392     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14393                                     ScalarInVector);
14394     unsigned SizeRatio = RegSz/MemSz;
14395
14396     // Redistribute the loaded elements into the different locations.
14397     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14398     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14399
14400     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14401                                          DAG.getUNDEF(WideVecVT),
14402                                          &ShuffleVec[0]);
14403
14404     // Bitcast to the requested type.
14405     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14406     // Replace the original load with the new sequence
14407     // and return the new chain.
14408     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14409     return SDValue(ScalarLoad.getNode(), 1);
14410   }
14411
14412   return SDValue();
14413 }
14414
14415 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14416 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14417                                    const X86Subtarget *Subtarget) {
14418   StoreSDNode *St = cast<StoreSDNode>(N);
14419   EVT VT = St->getValue().getValueType();
14420   EVT StVT = St->getMemoryVT();
14421   DebugLoc dl = St->getDebugLoc();
14422   SDValue StoredVal = St->getOperand(1);
14423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14424
14425   // If we are saving a concatenation of two XMM registers, perform two stores.
14426   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14427   // 128-bit ones. If in the future the cost becomes only one memory access the
14428   // first version would be better.
14429   if (VT.getSizeInBits() == 256 &&
14430     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14431     StoredVal.getNumOperands() == 2) {
14432
14433     SDValue Value0 = StoredVal.getOperand(0);
14434     SDValue Value1 = StoredVal.getOperand(1);
14435
14436     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14437     SDValue Ptr0 = St->getBasePtr();
14438     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14439
14440     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14441                                 St->getPointerInfo(), St->isVolatile(),
14442                                 St->isNonTemporal(), St->getAlignment());
14443     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14444                                 St->getPointerInfo(), St->isVolatile(),
14445                                 St->isNonTemporal(), St->getAlignment());
14446     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14447   }
14448
14449   // Optimize trunc store (of multiple scalars) to shuffle and store.
14450   // First, pack all of the elements in one place. Next, store to memory
14451   // in fewer chunks.
14452   if (St->isTruncatingStore() && VT.isVector()) {
14453     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14454     unsigned NumElems = VT.getVectorNumElements();
14455     assert(StVT != VT && "Cannot truncate to the same type");
14456     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14457     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14458
14459     // From, To sizes and ElemCount must be pow of two
14460     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14461     // We are going to use the original vector elt for storing.
14462     // Accumulated smaller vector elements must be a multiple of the store size.
14463     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14464
14465     unsigned SizeRatio  = FromSz / ToSz;
14466
14467     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14468
14469     // Create a type on which we perform the shuffle
14470     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14471             StVT.getScalarType(), NumElems*SizeRatio);
14472
14473     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14474
14475     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14476     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14477     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14478
14479     // Can't shuffle using an illegal type
14480     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14481
14482     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14483                                          DAG.getUNDEF(WideVecVT),
14484                                          &ShuffleVec[0]);
14485     // At this point all of the data is stored at the bottom of the
14486     // register. We now need to save it to mem.
14487
14488     // Find the largest store unit
14489     MVT StoreType = MVT::i8;
14490     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14491          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14492       MVT Tp = (MVT::SimpleValueType)tp;
14493       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14494         StoreType = Tp;
14495     }
14496
14497     // Bitcast the original vector into a vector of store-size units
14498     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14499             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14500     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14501     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14502     SmallVector<SDValue, 8> Chains;
14503     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14504                                         TLI.getPointerTy());
14505     SDValue Ptr = St->getBasePtr();
14506
14507     // Perform one or more big stores into memory.
14508     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14509       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14510                                    StoreType, ShuffWide,
14511                                    DAG.getIntPtrConstant(i));
14512       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14513                                 St->getPointerInfo(), St->isVolatile(),
14514                                 St->isNonTemporal(), St->getAlignment());
14515       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14516       Chains.push_back(Ch);
14517     }
14518
14519     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14520                                Chains.size());
14521   }
14522
14523
14524   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14525   // the FP state in cases where an emms may be missing.
14526   // A preferable solution to the general problem is to figure out the right
14527   // places to insert EMMS.  This qualifies as a quick hack.
14528
14529   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14530   if (VT.getSizeInBits() != 64)
14531     return SDValue();
14532
14533   const Function *F = DAG.getMachineFunction().getFunction();
14534   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14535   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14536                      && Subtarget->hasSSE2();
14537   if ((VT.isVector() ||
14538        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14539       isa<LoadSDNode>(St->getValue()) &&
14540       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14541       St->getChain().hasOneUse() && !St->isVolatile()) {
14542     SDNode* LdVal = St->getValue().getNode();
14543     LoadSDNode *Ld = 0;
14544     int TokenFactorIndex = -1;
14545     SmallVector<SDValue, 8> Ops;
14546     SDNode* ChainVal = St->getChain().getNode();
14547     // Must be a store of a load.  We currently handle two cases:  the load
14548     // is a direct child, and it's under an intervening TokenFactor.  It is
14549     // possible to dig deeper under nested TokenFactors.
14550     if (ChainVal == LdVal)
14551       Ld = cast<LoadSDNode>(St->getChain());
14552     else if (St->getValue().hasOneUse() &&
14553              ChainVal->getOpcode() == ISD::TokenFactor) {
14554       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14555         if (ChainVal->getOperand(i).getNode() == LdVal) {
14556           TokenFactorIndex = i;
14557           Ld = cast<LoadSDNode>(St->getValue());
14558         } else
14559           Ops.push_back(ChainVal->getOperand(i));
14560       }
14561     }
14562
14563     if (!Ld || !ISD::isNormalLoad(Ld))
14564       return SDValue();
14565
14566     // If this is not the MMX case, i.e. we are just turning i64 load/store
14567     // into f64 load/store, avoid the transformation if there are multiple
14568     // uses of the loaded value.
14569     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14570       return SDValue();
14571
14572     DebugLoc LdDL = Ld->getDebugLoc();
14573     DebugLoc StDL = N->getDebugLoc();
14574     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14575     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14576     // pair instead.
14577     if (Subtarget->is64Bit() || F64IsLegal) {
14578       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14579       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14580                                   Ld->getPointerInfo(), Ld->isVolatile(),
14581                                   Ld->isNonTemporal(), Ld->isInvariant(),
14582                                   Ld->getAlignment());
14583       SDValue NewChain = NewLd.getValue(1);
14584       if (TokenFactorIndex != -1) {
14585         Ops.push_back(NewChain);
14586         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14587                                Ops.size());
14588       }
14589       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14590                           St->getPointerInfo(),
14591                           St->isVolatile(), St->isNonTemporal(),
14592                           St->getAlignment());
14593     }
14594
14595     // Otherwise, lower to two pairs of 32-bit loads / stores.
14596     SDValue LoAddr = Ld->getBasePtr();
14597     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14598                                  DAG.getConstant(4, MVT::i32));
14599
14600     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14601                                Ld->getPointerInfo(),
14602                                Ld->isVolatile(), Ld->isNonTemporal(),
14603                                Ld->isInvariant(), Ld->getAlignment());
14604     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14605                                Ld->getPointerInfo().getWithOffset(4),
14606                                Ld->isVolatile(), Ld->isNonTemporal(),
14607                                Ld->isInvariant(),
14608                                MinAlign(Ld->getAlignment(), 4));
14609
14610     SDValue NewChain = LoLd.getValue(1);
14611     if (TokenFactorIndex != -1) {
14612       Ops.push_back(LoLd);
14613       Ops.push_back(HiLd);
14614       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14615                              Ops.size());
14616     }
14617
14618     LoAddr = St->getBasePtr();
14619     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14620                          DAG.getConstant(4, MVT::i32));
14621
14622     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14623                                 St->getPointerInfo(),
14624                                 St->isVolatile(), St->isNonTemporal(),
14625                                 St->getAlignment());
14626     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14627                                 St->getPointerInfo().getWithOffset(4),
14628                                 St->isVolatile(),
14629                                 St->isNonTemporal(),
14630                                 MinAlign(St->getAlignment(), 4));
14631     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14632   }
14633   return SDValue();
14634 }
14635
14636 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14637 /// and return the operands for the horizontal operation in LHS and RHS.  A
14638 /// horizontal operation performs the binary operation on successive elements
14639 /// of its first operand, then on successive elements of its second operand,
14640 /// returning the resulting values in a vector.  For example, if
14641 ///   A = < float a0, float a1, float a2, float a3 >
14642 /// and
14643 ///   B = < float b0, float b1, float b2, float b3 >
14644 /// then the result of doing a horizontal operation on A and B is
14645 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14646 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14647 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14648 /// set to A, RHS to B, and the routine returns 'true'.
14649 /// Note that the binary operation should have the property that if one of the
14650 /// operands is UNDEF then the result is UNDEF.
14651 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14652   // Look for the following pattern: if
14653   //   A = < float a0, float a1, float a2, float a3 >
14654   //   B = < float b0, float b1, float b2, float b3 >
14655   // and
14656   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14657   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14658   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14659   // which is A horizontal-op B.
14660
14661   // At least one of the operands should be a vector shuffle.
14662   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14663       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14664     return false;
14665
14666   EVT VT = LHS.getValueType();
14667
14668   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14669          "Unsupported vector type for horizontal add/sub");
14670
14671   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14672   // operate independently on 128-bit lanes.
14673   unsigned NumElts = VT.getVectorNumElements();
14674   unsigned NumLanes = VT.getSizeInBits()/128;
14675   unsigned NumLaneElts = NumElts / NumLanes;
14676   assert((NumLaneElts % 2 == 0) &&
14677          "Vector type should have an even number of elements in each lane");
14678   unsigned HalfLaneElts = NumLaneElts/2;
14679
14680   // View LHS in the form
14681   //   LHS = VECTOR_SHUFFLE A, B, LMask
14682   // If LHS is not a shuffle then pretend it is the shuffle
14683   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14684   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14685   // type VT.
14686   SDValue A, B;
14687   SmallVector<int, 16> LMask(NumElts);
14688   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14689     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14690       A = LHS.getOperand(0);
14691     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14692       B = LHS.getOperand(1);
14693     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14694     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14695   } else {
14696     if (LHS.getOpcode() != ISD::UNDEF)
14697       A = LHS;
14698     for (unsigned i = 0; i != NumElts; ++i)
14699       LMask[i] = i;
14700   }
14701
14702   // Likewise, view RHS in the form
14703   //   RHS = VECTOR_SHUFFLE C, D, RMask
14704   SDValue C, D;
14705   SmallVector<int, 16> RMask(NumElts);
14706   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14707     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14708       C = RHS.getOperand(0);
14709     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14710       D = RHS.getOperand(1);
14711     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14712     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14713   } else {
14714     if (RHS.getOpcode() != ISD::UNDEF)
14715       C = RHS;
14716     for (unsigned i = 0; i != NumElts; ++i)
14717       RMask[i] = i;
14718   }
14719
14720   // Check that the shuffles are both shuffling the same vectors.
14721   if (!(A == C && B == D) && !(A == D && B == C))
14722     return false;
14723
14724   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14725   if (!A.getNode() && !B.getNode())
14726     return false;
14727
14728   // If A and B occur in reverse order in RHS, then "swap" them (which means
14729   // rewriting the mask).
14730   if (A != C)
14731     CommuteVectorShuffleMask(RMask, NumElts);
14732
14733   // At this point LHS and RHS are equivalent to
14734   //   LHS = VECTOR_SHUFFLE A, B, LMask
14735   //   RHS = VECTOR_SHUFFLE A, B, RMask
14736   // Check that the masks correspond to performing a horizontal operation.
14737   for (unsigned i = 0; i != NumElts; ++i) {
14738     int LIdx = LMask[i], RIdx = RMask[i];
14739
14740     // Ignore any UNDEF components.
14741     if (LIdx < 0 || RIdx < 0 ||
14742         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14743         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14744       continue;
14745
14746     // Check that successive elements are being operated on.  If not, this is
14747     // not a horizontal operation.
14748     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14749     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14750     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14751     if (!(LIdx == Index && RIdx == Index + 1) &&
14752         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14753       return false;
14754   }
14755
14756   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14757   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14758   return true;
14759 }
14760
14761 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14762 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14763                                   const X86Subtarget *Subtarget) {
14764   EVT VT = N->getValueType(0);
14765   SDValue LHS = N->getOperand(0);
14766   SDValue RHS = N->getOperand(1);
14767
14768   // Try to synthesize horizontal adds from adds of shuffles.
14769   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14770        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14771       isHorizontalBinOp(LHS, RHS, true))
14772     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14773   return SDValue();
14774 }
14775
14776 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14777 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14778                                   const X86Subtarget *Subtarget) {
14779   EVT VT = N->getValueType(0);
14780   SDValue LHS = N->getOperand(0);
14781   SDValue RHS = N->getOperand(1);
14782
14783   // Try to synthesize horizontal subs from subs of shuffles.
14784   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14785        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14786       isHorizontalBinOp(LHS, RHS, false))
14787     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14788   return SDValue();
14789 }
14790
14791 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14792 /// X86ISD::FXOR nodes.
14793 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14794   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14795   // F[X]OR(0.0, x) -> x
14796   // F[X]OR(x, 0.0) -> x
14797   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14798     if (C->getValueAPF().isPosZero())
14799       return N->getOperand(1);
14800   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14801     if (C->getValueAPF().isPosZero())
14802       return N->getOperand(0);
14803   return SDValue();
14804 }
14805
14806 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14807 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14808   // FAND(0.0, x) -> 0.0
14809   // FAND(x, 0.0) -> 0.0
14810   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14811     if (C->getValueAPF().isPosZero())
14812       return N->getOperand(0);
14813   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14814     if (C->getValueAPF().isPosZero())
14815       return N->getOperand(1);
14816   return SDValue();
14817 }
14818
14819 static SDValue PerformBTCombine(SDNode *N,
14820                                 SelectionDAG &DAG,
14821                                 TargetLowering::DAGCombinerInfo &DCI) {
14822   // BT ignores high bits in the bit index operand.
14823   SDValue Op1 = N->getOperand(1);
14824   if (Op1.hasOneUse()) {
14825     unsigned BitWidth = Op1.getValueSizeInBits();
14826     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14827     APInt KnownZero, KnownOne;
14828     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14829                                           !DCI.isBeforeLegalizeOps());
14830     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14831     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14832         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14833       DCI.CommitTargetLoweringOpt(TLO);
14834   }
14835   return SDValue();
14836 }
14837
14838 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14839   SDValue Op = N->getOperand(0);
14840   if (Op.getOpcode() == ISD::BITCAST)
14841     Op = Op.getOperand(0);
14842   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14843   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14844       VT.getVectorElementType().getSizeInBits() ==
14845       OpVT.getVectorElementType().getSizeInBits()) {
14846     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14847   }
14848   return SDValue();
14849 }
14850
14851 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14852                                   TargetLowering::DAGCombinerInfo &DCI,
14853                                   const X86Subtarget *Subtarget) {
14854   if (!DCI.isBeforeLegalizeOps())
14855     return SDValue();
14856
14857   if (!Subtarget->hasAVX()) 
14858     return SDValue();
14859
14860   EVT VT = N->getValueType(0);
14861   SDValue Op = N->getOperand(0);
14862   EVT OpVT = Op.getValueType();
14863   DebugLoc dl = N->getDebugLoc();
14864
14865   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
14866       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
14867
14868     if (Subtarget->hasAVX2()) {
14869       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
14870     }
14871
14872     // Optimize vectors in AVX mode
14873     // Sign extend  v8i16 to v8i32 and
14874     //              v4i32 to v4i64
14875     //
14876     // Divide input vector into two parts
14877     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14878     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14879     // concat the vectors to original VT
14880
14881     unsigned NumElems = OpVT.getVectorNumElements();
14882     SmallVector<int,8> ShufMask1(NumElems, -1);
14883     for (unsigned i = 0; i < NumElems/2; i++) ShufMask1[i] = i;
14884
14885     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14886                                         &ShufMask1[0]);
14887
14888     SmallVector<int,8> ShufMask2(NumElems, -1);
14889     for (unsigned i = 0; i < NumElems/2; i++) ShufMask2[i] = i + NumElems/2;
14890
14891     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14892                                         &ShufMask2[0]);
14893
14894     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 
14895                                   VT.getVectorNumElements()/2);
14896
14897     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 
14898     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
14899
14900     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14901   }
14902   return SDValue();
14903 }
14904
14905 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
14906                                   const X86Subtarget *Subtarget) {
14907   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14908   //           (and (i32 x86isd::setcc_carry), 1)
14909   // This eliminates the zext. This transformation is necessary because
14910   // ISD::SETCC is always legalized to i8.
14911   DebugLoc dl = N->getDebugLoc();
14912   SDValue N0 = N->getOperand(0);
14913   EVT VT = N->getValueType(0);
14914   EVT OpVT = N0.getValueType();
14915
14916   if (N0.getOpcode() == ISD::AND &&
14917       N0.hasOneUse() &&
14918       N0.getOperand(0).hasOneUse()) {
14919     SDValue N00 = N0.getOperand(0);
14920     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14921       return SDValue();
14922     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14923     if (!C || C->getZExtValue() != 1)
14924       return SDValue();
14925     return DAG.getNode(ISD::AND, dl, VT,
14926                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14927                                    N00.getOperand(0), N00.getOperand(1)),
14928                        DAG.getConstant(1, VT));
14929   }
14930
14931   // Optimize vectors in AVX mode:
14932   //
14933   //   v8i16 -> v8i32
14934   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14935   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14936   //   Concat upper and lower parts.
14937   //
14938   //   v4i32 -> v4i64
14939   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14940   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14941   //   Concat upper and lower parts.
14942   //
14943   if (Subtarget->hasAVX()) {
14944
14945     if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
14946         ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
14947
14948       if (Subtarget->hasAVX2())
14949         return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
14950
14951       SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
14952       SDValue OpLo = getTargetShuffleNode(X86ISD::UNPCKL, dl, OpVT, N0, ZeroVec,
14953                                           DAG);
14954       SDValue OpHi = getTargetShuffleNode(X86ISD::UNPCKH, dl, OpVT, N0, ZeroVec,
14955                                           DAG);
14956
14957       EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
14958                                  VT.getVectorNumElements()/2);
14959
14960       OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14961       OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14962
14963       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14964     }
14965   }
14966
14967   return SDValue();
14968 }
14969
14970 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14971 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14972   unsigned X86CC = N->getConstantOperandVal(0);
14973   SDValue EFLAG = N->getOperand(1);
14974   DebugLoc DL = N->getDebugLoc();
14975
14976   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14977   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14978   // cases.
14979   if (X86CC == X86::COND_B)
14980     return DAG.getNode(ISD::AND, DL, MVT::i8,
14981                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14982                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14983                        DAG.getConstant(1, MVT::i8));
14984
14985   return SDValue();
14986 }
14987
14988 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14989                                         const X86TargetLowering *XTLI) {
14990   SDValue Op0 = N->getOperand(0);
14991   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14992   // a 32-bit target where SSE doesn't support i64->FP operations.
14993   if (Op0.getOpcode() == ISD::LOAD) {
14994     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14995     EVT VT = Ld->getValueType(0);
14996     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14997         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14998         !XTLI->getSubtarget()->is64Bit() &&
14999         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15000       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15001                                           Ld->getChain(), Op0, DAG);
15002       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15003       return FILDChain;
15004     }
15005   }
15006   return SDValue();
15007 }
15008
15009 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15010 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15011                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15012   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15013   // the result is either zero or one (depending on the input carry bit).
15014   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15015   if (X86::isZeroNode(N->getOperand(0)) &&
15016       X86::isZeroNode(N->getOperand(1)) &&
15017       // We don't have a good way to replace an EFLAGS use, so only do this when
15018       // dead right now.
15019       SDValue(N, 1).use_empty()) {
15020     DebugLoc DL = N->getDebugLoc();
15021     EVT VT = N->getValueType(0);
15022     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15023     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15024                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15025                                            DAG.getConstant(X86::COND_B,MVT::i8),
15026                                            N->getOperand(2)),
15027                                DAG.getConstant(1, VT));
15028     return DCI.CombineTo(N, Res1, CarryOut);
15029   }
15030
15031   return SDValue();
15032 }
15033
15034 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15035 //      (add Y, (setne X, 0)) -> sbb -1, Y
15036 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15037 //      (sub (setne X, 0), Y) -> adc -1, Y
15038 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15039   DebugLoc DL = N->getDebugLoc();
15040
15041   // Look through ZExts.
15042   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15043   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15044     return SDValue();
15045
15046   SDValue SetCC = Ext.getOperand(0);
15047   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15048     return SDValue();
15049
15050   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15051   if (CC != X86::COND_E && CC != X86::COND_NE)
15052     return SDValue();
15053
15054   SDValue Cmp = SetCC.getOperand(1);
15055   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15056       !X86::isZeroNode(Cmp.getOperand(1)) ||
15057       !Cmp.getOperand(0).getValueType().isInteger())
15058     return SDValue();
15059
15060   SDValue CmpOp0 = Cmp.getOperand(0);
15061   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15062                                DAG.getConstant(1, CmpOp0.getValueType()));
15063
15064   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15065   if (CC == X86::COND_NE)
15066     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15067                        DL, OtherVal.getValueType(), OtherVal,
15068                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15069   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15070                      DL, OtherVal.getValueType(), OtherVal,
15071                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15072 }
15073
15074 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15075 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15076                                  const X86Subtarget *Subtarget) {
15077   EVT VT = N->getValueType(0);
15078   SDValue Op0 = N->getOperand(0);
15079   SDValue Op1 = N->getOperand(1);
15080
15081   // Try to synthesize horizontal adds from adds of shuffles.
15082   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15083        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15084       isHorizontalBinOp(Op0, Op1, true))
15085     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15086
15087   return OptimizeConditionalInDecrement(N, DAG);
15088 }
15089
15090 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15091                                  const X86Subtarget *Subtarget) {
15092   SDValue Op0 = N->getOperand(0);
15093   SDValue Op1 = N->getOperand(1);
15094
15095   // X86 can't encode an immediate LHS of a sub. See if we can push the
15096   // negation into a preceding instruction.
15097   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15098     // If the RHS of the sub is a XOR with one use and a constant, invert the
15099     // immediate. Then add one to the LHS of the sub so we can turn
15100     // X-Y -> X+~Y+1, saving one register.
15101     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15102         isa<ConstantSDNode>(Op1.getOperand(1))) {
15103       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15104       EVT VT = Op0.getValueType();
15105       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15106                                    Op1.getOperand(0),
15107                                    DAG.getConstant(~XorC, VT));
15108       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15109                          DAG.getConstant(C->getAPIntValue()+1, VT));
15110     }
15111   }
15112
15113   // Try to synthesize horizontal adds from adds of shuffles.
15114   EVT VT = N->getValueType(0);
15115   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15116        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15117       isHorizontalBinOp(Op0, Op1, true))
15118     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15119
15120   return OptimizeConditionalInDecrement(N, DAG);
15121 }
15122
15123 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15124                                              DAGCombinerInfo &DCI) const {
15125   SelectionDAG &DAG = DCI.DAG;
15126   switch (N->getOpcode()) {
15127   default: break;
15128   case ISD::EXTRACT_VECTOR_ELT:
15129     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15130   case ISD::VSELECT:
15131   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15132   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15133   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15134   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15135   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15136   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15137   case ISD::SHL:
15138   case ISD::SRA:
15139   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15140   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15141   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15142   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15143   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
15144   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15145   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15146   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15147   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15148   case X86ISD::FXOR:
15149   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15150   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15151   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15152   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15153   case ISD::ANY_EXTEND:
15154   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, Subtarget);
15155   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15156   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15157   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15158   case X86ISD::SHUFP:       // Handle all target specific shuffles
15159   case X86ISD::PALIGN:
15160   case X86ISD::UNPCKH:
15161   case X86ISD::UNPCKL:
15162   case X86ISD::MOVHLPS:
15163   case X86ISD::MOVLHPS:
15164   case X86ISD::PSHUFD:
15165   case X86ISD::PSHUFHW:
15166   case X86ISD::PSHUFLW:
15167   case X86ISD::MOVSS:
15168   case X86ISD::MOVSD:
15169   case X86ISD::VPERMILP:
15170   case X86ISD::VPERM2X128:
15171   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15172   }
15173
15174   return SDValue();
15175 }
15176
15177 /// isTypeDesirableForOp - Return true if the target has native support for
15178 /// the specified value type and it is 'desirable' to use the type for the
15179 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15180 /// instruction encodings are longer and some i16 instructions are slow.
15181 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15182   if (!isTypeLegal(VT))
15183     return false;
15184   if (VT != MVT::i16)
15185     return true;
15186
15187   switch (Opc) {
15188   default:
15189     return true;
15190   case ISD::LOAD:
15191   case ISD::SIGN_EXTEND:
15192   case ISD::ZERO_EXTEND:
15193   case ISD::ANY_EXTEND:
15194   case ISD::SHL:
15195   case ISD::SRL:
15196   case ISD::SUB:
15197   case ISD::ADD:
15198   case ISD::MUL:
15199   case ISD::AND:
15200   case ISD::OR:
15201   case ISD::XOR:
15202     return false;
15203   }
15204 }
15205
15206 /// IsDesirableToPromoteOp - This method query the target whether it is
15207 /// beneficial for dag combiner to promote the specified node. If true, it
15208 /// should return the desired promotion type by reference.
15209 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15210   EVT VT = Op.getValueType();
15211   if (VT != MVT::i16)
15212     return false;
15213
15214   bool Promote = false;
15215   bool Commute = false;
15216   switch (Op.getOpcode()) {
15217   default: break;
15218   case ISD::LOAD: {
15219     LoadSDNode *LD = cast<LoadSDNode>(Op);
15220     // If the non-extending load has a single use and it's not live out, then it
15221     // might be folded.
15222     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15223                                                      Op.hasOneUse()*/) {
15224       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15225              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15226         // The only case where we'd want to promote LOAD (rather then it being
15227         // promoted as an operand is when it's only use is liveout.
15228         if (UI->getOpcode() != ISD::CopyToReg)
15229           return false;
15230       }
15231     }
15232     Promote = true;
15233     break;
15234   }
15235   case ISD::SIGN_EXTEND:
15236   case ISD::ZERO_EXTEND:
15237   case ISD::ANY_EXTEND:
15238     Promote = true;
15239     break;
15240   case ISD::SHL:
15241   case ISD::SRL: {
15242     SDValue N0 = Op.getOperand(0);
15243     // Look out for (store (shl (load), x)).
15244     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15245       return false;
15246     Promote = true;
15247     break;
15248   }
15249   case ISD::ADD:
15250   case ISD::MUL:
15251   case ISD::AND:
15252   case ISD::OR:
15253   case ISD::XOR:
15254     Commute = true;
15255     // fallthrough
15256   case ISD::SUB: {
15257     SDValue N0 = Op.getOperand(0);
15258     SDValue N1 = Op.getOperand(1);
15259     if (!Commute && MayFoldLoad(N1))
15260       return false;
15261     // Avoid disabling potential load folding opportunities.
15262     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15263       return false;
15264     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15265       return false;
15266     Promote = true;
15267   }
15268   }
15269
15270   PVT = MVT::i32;
15271   return Promote;
15272 }
15273
15274 //===----------------------------------------------------------------------===//
15275 //                           X86 Inline Assembly Support
15276 //===----------------------------------------------------------------------===//
15277
15278 namespace {
15279   // Helper to match a string separated by whitespace.
15280   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15281     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15282
15283     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15284       StringRef piece(*args[i]);
15285       if (!s.startswith(piece)) // Check if the piece matches.
15286         return false;
15287
15288       s = s.substr(piece.size());
15289       StringRef::size_type pos = s.find_first_not_of(" \t");
15290       if (pos == 0) // We matched a prefix.
15291         return false;
15292
15293       s = s.substr(pos);
15294     }
15295
15296     return s.empty();
15297   }
15298   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15299 }
15300
15301 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15302   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15303
15304   std::string AsmStr = IA->getAsmString();
15305
15306   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15307   if (!Ty || Ty->getBitWidth() % 16 != 0)
15308     return false;
15309
15310   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15311   SmallVector<StringRef, 4> AsmPieces;
15312   SplitString(AsmStr, AsmPieces, ";\n");
15313
15314   switch (AsmPieces.size()) {
15315   default: return false;
15316   case 1:
15317     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15318     // we will turn this bswap into something that will be lowered to logical
15319     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15320     // lower so don't worry about this.
15321     // bswap $0
15322     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15323         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15324         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15325         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15326         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15327         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15328       // No need to check constraints, nothing other than the equivalent of
15329       // "=r,0" would be valid here.
15330       return IntrinsicLowering::LowerToByteSwap(CI);
15331     }
15332
15333     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15334     if (CI->getType()->isIntegerTy(16) &&
15335         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15336         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15337          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15338       AsmPieces.clear();
15339       const std::string &ConstraintsStr = IA->getConstraintString();
15340       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15341       std::sort(AsmPieces.begin(), AsmPieces.end());
15342       if (AsmPieces.size() == 4 &&
15343           AsmPieces[0] == "~{cc}" &&
15344           AsmPieces[1] == "~{dirflag}" &&
15345           AsmPieces[2] == "~{flags}" &&
15346           AsmPieces[3] == "~{fpsr}")
15347       return IntrinsicLowering::LowerToByteSwap(CI);
15348     }
15349     break;
15350   case 3:
15351     if (CI->getType()->isIntegerTy(32) &&
15352         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15353         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15354         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15355         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15356       AsmPieces.clear();
15357       const std::string &ConstraintsStr = IA->getConstraintString();
15358       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15359       std::sort(AsmPieces.begin(), AsmPieces.end());
15360       if (AsmPieces.size() == 4 &&
15361           AsmPieces[0] == "~{cc}" &&
15362           AsmPieces[1] == "~{dirflag}" &&
15363           AsmPieces[2] == "~{flags}" &&
15364           AsmPieces[3] == "~{fpsr}")
15365         return IntrinsicLowering::LowerToByteSwap(CI);
15366     }
15367
15368     if (CI->getType()->isIntegerTy(64)) {
15369       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15370       if (Constraints.size() >= 2 &&
15371           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15372           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15373         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15374         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15375             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15376             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15377           return IntrinsicLowering::LowerToByteSwap(CI);
15378       }
15379     }
15380     break;
15381   }
15382   return false;
15383 }
15384
15385
15386
15387 /// getConstraintType - Given a constraint letter, return the type of
15388 /// constraint it is for this target.
15389 X86TargetLowering::ConstraintType
15390 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15391   if (Constraint.size() == 1) {
15392     switch (Constraint[0]) {
15393     case 'R':
15394     case 'q':
15395     case 'Q':
15396     case 'f':
15397     case 't':
15398     case 'u':
15399     case 'y':
15400     case 'x':
15401     case 'Y':
15402     case 'l':
15403       return C_RegisterClass;
15404     case 'a':
15405     case 'b':
15406     case 'c':
15407     case 'd':
15408     case 'S':
15409     case 'D':
15410     case 'A':
15411       return C_Register;
15412     case 'I':
15413     case 'J':
15414     case 'K':
15415     case 'L':
15416     case 'M':
15417     case 'N':
15418     case 'G':
15419     case 'C':
15420     case 'e':
15421     case 'Z':
15422       return C_Other;
15423     default:
15424       break;
15425     }
15426   }
15427   return TargetLowering::getConstraintType(Constraint);
15428 }
15429
15430 /// Examine constraint type and operand type and determine a weight value.
15431 /// This object must already have been set up with the operand type
15432 /// and the current alternative constraint selected.
15433 TargetLowering::ConstraintWeight
15434   X86TargetLowering::getSingleConstraintMatchWeight(
15435     AsmOperandInfo &info, const char *constraint) const {
15436   ConstraintWeight weight = CW_Invalid;
15437   Value *CallOperandVal = info.CallOperandVal;
15438     // If we don't have a value, we can't do a match,
15439     // but allow it at the lowest weight.
15440   if (CallOperandVal == NULL)
15441     return CW_Default;
15442   Type *type = CallOperandVal->getType();
15443   // Look at the constraint type.
15444   switch (*constraint) {
15445   default:
15446     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15447   case 'R':
15448   case 'q':
15449   case 'Q':
15450   case 'a':
15451   case 'b':
15452   case 'c':
15453   case 'd':
15454   case 'S':
15455   case 'D':
15456   case 'A':
15457     if (CallOperandVal->getType()->isIntegerTy())
15458       weight = CW_SpecificReg;
15459     break;
15460   case 'f':
15461   case 't':
15462   case 'u':
15463       if (type->isFloatingPointTy())
15464         weight = CW_SpecificReg;
15465       break;
15466   case 'y':
15467       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15468         weight = CW_SpecificReg;
15469       break;
15470   case 'x':
15471   case 'Y':
15472     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15473         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15474       weight = CW_Register;
15475     break;
15476   case 'I':
15477     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15478       if (C->getZExtValue() <= 31)
15479         weight = CW_Constant;
15480     }
15481     break;
15482   case 'J':
15483     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15484       if (C->getZExtValue() <= 63)
15485         weight = CW_Constant;
15486     }
15487     break;
15488   case 'K':
15489     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15490       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15491         weight = CW_Constant;
15492     }
15493     break;
15494   case 'L':
15495     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15496       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15497         weight = CW_Constant;
15498     }
15499     break;
15500   case 'M':
15501     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15502       if (C->getZExtValue() <= 3)
15503         weight = CW_Constant;
15504     }
15505     break;
15506   case 'N':
15507     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15508       if (C->getZExtValue() <= 0xff)
15509         weight = CW_Constant;
15510     }
15511     break;
15512   case 'G':
15513   case 'C':
15514     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15515       weight = CW_Constant;
15516     }
15517     break;
15518   case 'e':
15519     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15520       if ((C->getSExtValue() >= -0x80000000LL) &&
15521           (C->getSExtValue() <= 0x7fffffffLL))
15522         weight = CW_Constant;
15523     }
15524     break;
15525   case 'Z':
15526     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15527       if (C->getZExtValue() <= 0xffffffff)
15528         weight = CW_Constant;
15529     }
15530     break;
15531   }
15532   return weight;
15533 }
15534
15535 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15536 /// with another that has more specific requirements based on the type of the
15537 /// corresponding operand.
15538 const char *X86TargetLowering::
15539 LowerXConstraint(EVT ConstraintVT) const {
15540   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15541   // 'f' like normal targets.
15542   if (ConstraintVT.isFloatingPoint()) {
15543     if (Subtarget->hasSSE2())
15544       return "Y";
15545     if (Subtarget->hasSSE1())
15546       return "x";
15547   }
15548
15549   return TargetLowering::LowerXConstraint(ConstraintVT);
15550 }
15551
15552 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15553 /// vector.  If it is invalid, don't add anything to Ops.
15554 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15555                                                      std::string &Constraint,
15556                                                      std::vector<SDValue>&Ops,
15557                                                      SelectionDAG &DAG) const {
15558   SDValue Result(0, 0);
15559
15560   // Only support length 1 constraints for now.
15561   if (Constraint.length() > 1) return;
15562
15563   char ConstraintLetter = Constraint[0];
15564   switch (ConstraintLetter) {
15565   default: break;
15566   case 'I':
15567     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15568       if (C->getZExtValue() <= 31) {
15569         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15570         break;
15571       }
15572     }
15573     return;
15574   case 'J':
15575     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15576       if (C->getZExtValue() <= 63) {
15577         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15578         break;
15579       }
15580     }
15581     return;
15582   case 'K':
15583     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15584       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15585         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15586         break;
15587       }
15588     }
15589     return;
15590   case 'N':
15591     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15592       if (C->getZExtValue() <= 255) {
15593         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15594         break;
15595       }
15596     }
15597     return;
15598   case 'e': {
15599     // 32-bit signed value
15600     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15601       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15602                                            C->getSExtValue())) {
15603         // Widen to 64 bits here to get it sign extended.
15604         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15605         break;
15606       }
15607     // FIXME gcc accepts some relocatable values here too, but only in certain
15608     // memory models; it's complicated.
15609     }
15610     return;
15611   }
15612   case 'Z': {
15613     // 32-bit unsigned value
15614     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15615       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15616                                            C->getZExtValue())) {
15617         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15618         break;
15619       }
15620     }
15621     // FIXME gcc accepts some relocatable values here too, but only in certain
15622     // memory models; it's complicated.
15623     return;
15624   }
15625   case 'i': {
15626     // Literal immediates are always ok.
15627     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15628       // Widen to 64 bits here to get it sign extended.
15629       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15630       break;
15631     }
15632
15633     // In any sort of PIC mode addresses need to be computed at runtime by
15634     // adding in a register or some sort of table lookup.  These can't
15635     // be used as immediates.
15636     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15637       return;
15638
15639     // If we are in non-pic codegen mode, we allow the address of a global (with
15640     // an optional displacement) to be used with 'i'.
15641     GlobalAddressSDNode *GA = 0;
15642     int64_t Offset = 0;
15643
15644     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15645     while (1) {
15646       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15647         Offset += GA->getOffset();
15648         break;
15649       } else if (Op.getOpcode() == ISD::ADD) {
15650         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15651           Offset += C->getZExtValue();
15652           Op = Op.getOperand(0);
15653           continue;
15654         }
15655       } else if (Op.getOpcode() == ISD::SUB) {
15656         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15657           Offset += -C->getZExtValue();
15658           Op = Op.getOperand(0);
15659           continue;
15660         }
15661       }
15662
15663       // Otherwise, this isn't something we can handle, reject it.
15664       return;
15665     }
15666
15667     const GlobalValue *GV = GA->getGlobal();
15668     // If we require an extra load to get this address, as in PIC mode, we
15669     // can't accept it.
15670     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15671                                                         getTargetMachine())))
15672       return;
15673
15674     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15675                                         GA->getValueType(0), Offset);
15676     break;
15677   }
15678   }
15679
15680   if (Result.getNode()) {
15681     Ops.push_back(Result);
15682     return;
15683   }
15684   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15685 }
15686
15687 std::pair<unsigned, const TargetRegisterClass*>
15688 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15689                                                 EVT VT) const {
15690   // First, see if this is a constraint that directly corresponds to an LLVM
15691   // register class.
15692   if (Constraint.size() == 1) {
15693     // GCC Constraint Letters
15694     switch (Constraint[0]) {
15695     default: break;
15696       // TODO: Slight differences here in allocation order and leaving
15697       // RIP in the class. Do they matter any more here than they do
15698       // in the normal allocation?
15699     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15700       if (Subtarget->is64Bit()) {
15701         if (VT == MVT::i32 || VT == MVT::f32)
15702           return std::make_pair(0U, &X86::GR32RegClass);
15703         if (VT == MVT::i16)
15704           return std::make_pair(0U, &X86::GR16RegClass);
15705         if (VT == MVT::i8 || VT == MVT::i1)
15706           return std::make_pair(0U, &X86::GR8RegClass);
15707         if (VT == MVT::i64 || VT == MVT::f64)
15708           return std::make_pair(0U, &X86::GR64RegClass);
15709         break;
15710       }
15711       // 32-bit fallthrough
15712     case 'Q':   // Q_REGS
15713       if (VT == MVT::i32 || VT == MVT::f32)
15714         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15715       if (VT == MVT::i16)
15716         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15717       if (VT == MVT::i8 || VT == MVT::i1)
15718         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15719       if (VT == MVT::i64)
15720         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15721       break;
15722     case 'r':   // GENERAL_REGS
15723     case 'l':   // INDEX_REGS
15724       if (VT == MVT::i8 || VT == MVT::i1)
15725         return std::make_pair(0U, &X86::GR8RegClass);
15726       if (VT == MVT::i16)
15727         return std::make_pair(0U, &X86::GR16RegClass);
15728       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15729         return std::make_pair(0U, &X86::GR32RegClass);
15730       return std::make_pair(0U, &X86::GR64RegClass);
15731     case 'R':   // LEGACY_REGS
15732       if (VT == MVT::i8 || VT == MVT::i1)
15733         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15734       if (VT == MVT::i16)
15735         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15736       if (VT == MVT::i32 || !Subtarget->is64Bit())
15737         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15738       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15739     case 'f':  // FP Stack registers.
15740       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15741       // value to the correct fpstack register class.
15742       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15743         return std::make_pair(0U, &X86::RFP32RegClass);
15744       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15745         return std::make_pair(0U, &X86::RFP64RegClass);
15746       return std::make_pair(0U, &X86::RFP80RegClass);
15747     case 'y':   // MMX_REGS if MMX allowed.
15748       if (!Subtarget->hasMMX()) break;
15749       return std::make_pair(0U, &X86::VR64RegClass);
15750     case 'Y':   // SSE_REGS if SSE2 allowed
15751       if (!Subtarget->hasSSE2()) break;
15752       // FALL THROUGH.
15753     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15754       if (!Subtarget->hasSSE1()) break;
15755
15756       switch (VT.getSimpleVT().SimpleTy) {
15757       default: break;
15758       // Scalar SSE types.
15759       case MVT::f32:
15760       case MVT::i32:
15761         return std::make_pair(0U, &X86::FR32RegClass);
15762       case MVT::f64:
15763       case MVT::i64:
15764         return std::make_pair(0U, &X86::FR64RegClass);
15765       // Vector types.
15766       case MVT::v16i8:
15767       case MVT::v8i16:
15768       case MVT::v4i32:
15769       case MVT::v2i64:
15770       case MVT::v4f32:
15771       case MVT::v2f64:
15772         return std::make_pair(0U, &X86::VR128RegClass);
15773       // AVX types.
15774       case MVT::v32i8:
15775       case MVT::v16i16:
15776       case MVT::v8i32:
15777       case MVT::v4i64:
15778       case MVT::v8f32:
15779       case MVT::v4f64:
15780         return std::make_pair(0U, &X86::VR256RegClass);
15781       }
15782       break;
15783     }
15784   }
15785
15786   // Use the default implementation in TargetLowering to convert the register
15787   // constraint into a member of a register class.
15788   std::pair<unsigned, const TargetRegisterClass*> Res;
15789   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15790
15791   // Not found as a standard register?
15792   if (Res.second == 0) {
15793     // Map st(0) -> st(7) -> ST0
15794     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15795         tolower(Constraint[1]) == 's' &&
15796         tolower(Constraint[2]) == 't' &&
15797         Constraint[3] == '(' &&
15798         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15799         Constraint[5] == ')' &&
15800         Constraint[6] == '}') {
15801
15802       Res.first = X86::ST0+Constraint[4]-'0';
15803       Res.second = &X86::RFP80RegClass;
15804       return Res;
15805     }
15806
15807     // GCC allows "st(0)" to be called just plain "st".
15808     if (StringRef("{st}").equals_lower(Constraint)) {
15809       Res.first = X86::ST0;
15810       Res.second = &X86::RFP80RegClass;
15811       return Res;
15812     }
15813
15814     // flags -> EFLAGS
15815     if (StringRef("{flags}").equals_lower(Constraint)) {
15816       Res.first = X86::EFLAGS;
15817       Res.second = &X86::CCRRegClass;
15818       return Res;
15819     }
15820
15821     // 'A' means EAX + EDX.
15822     if (Constraint == "A") {
15823       Res.first = X86::EAX;
15824       Res.second = &X86::GR32_ADRegClass;
15825       return Res;
15826     }
15827     return Res;
15828   }
15829
15830   // Otherwise, check to see if this is a register class of the wrong value
15831   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15832   // turn into {ax},{dx}.
15833   if (Res.second->hasType(VT))
15834     return Res;   // Correct type already, nothing to do.
15835
15836   // All of the single-register GCC register classes map their values onto
15837   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15838   // really want an 8-bit or 32-bit register, map to the appropriate register
15839   // class and return the appropriate register.
15840   if (Res.second == &X86::GR16RegClass) {
15841     if (VT == MVT::i8) {
15842       unsigned DestReg = 0;
15843       switch (Res.first) {
15844       default: break;
15845       case X86::AX: DestReg = X86::AL; break;
15846       case X86::DX: DestReg = X86::DL; break;
15847       case X86::CX: DestReg = X86::CL; break;
15848       case X86::BX: DestReg = X86::BL; break;
15849       }
15850       if (DestReg) {
15851         Res.first = DestReg;
15852         Res.second = &X86::GR8RegClass;
15853       }
15854     } else if (VT == MVT::i32) {
15855       unsigned DestReg = 0;
15856       switch (Res.first) {
15857       default: break;
15858       case X86::AX: DestReg = X86::EAX; break;
15859       case X86::DX: DestReg = X86::EDX; break;
15860       case X86::CX: DestReg = X86::ECX; break;
15861       case X86::BX: DestReg = X86::EBX; break;
15862       case X86::SI: DestReg = X86::ESI; break;
15863       case X86::DI: DestReg = X86::EDI; break;
15864       case X86::BP: DestReg = X86::EBP; break;
15865       case X86::SP: DestReg = X86::ESP; break;
15866       }
15867       if (DestReg) {
15868         Res.first = DestReg;
15869         Res.second = &X86::GR32RegClass;
15870       }
15871     } else if (VT == MVT::i64) {
15872       unsigned DestReg = 0;
15873       switch (Res.first) {
15874       default: break;
15875       case X86::AX: DestReg = X86::RAX; break;
15876       case X86::DX: DestReg = X86::RDX; break;
15877       case X86::CX: DestReg = X86::RCX; break;
15878       case X86::BX: DestReg = X86::RBX; break;
15879       case X86::SI: DestReg = X86::RSI; break;
15880       case X86::DI: DestReg = X86::RDI; break;
15881       case X86::BP: DestReg = X86::RBP; break;
15882       case X86::SP: DestReg = X86::RSP; break;
15883       }
15884       if (DestReg) {
15885         Res.first = DestReg;
15886         Res.second = &X86::GR64RegClass;
15887       }
15888     }
15889   } else if (Res.second == &X86::FR32RegClass ||
15890              Res.second == &X86::FR64RegClass ||
15891              Res.second == &X86::VR128RegClass) {
15892     // Handle references to XMM physical registers that got mapped into the
15893     // wrong class.  This can happen with constraints like {xmm0} where the
15894     // target independent register mapper will just pick the first match it can
15895     // find, ignoring the required type.
15896     if (VT == MVT::f32)
15897       Res.second = &X86::FR32RegClass;
15898     else if (VT == MVT::f64)
15899       Res.second = &X86::FR64RegClass;
15900     else if (X86::VR128RegClass.hasType(VT))
15901       Res.second = &X86::VR128RegClass;
15902   }
15903
15904   return Res;
15905 }