Rename a function.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161
162   RegInfo = TM.getRegisterInfo();
163   TD = getDataLayout();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom())
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184   // Bypass i32 with i8 on Atom when compiling with O2
185   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186     addBypassSlowDiv(32, 8);
187
188   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189     // Setup Windows compiler runtime calls.
190     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192     setLibcallName(RTLIB::SREM_I64, "_allrem");
193     setLibcallName(RTLIB::UREM_I64, "_aullrem");
194     setLibcallName(RTLIB::MUL_I64, "_allmul");
195     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201     // The _ftol2 runtime function has an unusual calling conv, which
202     // is modeled by a special pseudo-instruction.
203     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207   }
208
209   if (Subtarget->isTargetDarwin()) {
210     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211     setUseUnderscoreSetJmp(false);
212     setUseUnderscoreLongJmp(false);
213   } else if (Subtarget->isTargetMingw()) {
214     // MS runtime is weird: it exports _setjmp, but longjmp!
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(false);
217   } else {
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(true);
220   }
221
222   // Set up the register classes.
223   addRegisterClass(MVT::i8, &X86::GR8RegClass);
224   addRegisterClass(MVT::i16, &X86::GR16RegClass);
225   addRegisterClass(MVT::i32, &X86::GR32RegClass);
226   if (Subtarget->is64Bit())
227     addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231   // We don't accept any truncstore of integer registers.
232   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239   // SETOEQ and SETUNE require checking two conditions.
240   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248   // operation.
249   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253   if (Subtarget->is64Bit()) {
254     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256   } else if (!TM.Options.UseSoftFloat) {
257     // We have an algorithm for SSE2->double, and we turn this into a
258     // 64-bit FILD followed by conditional FADD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260     // We have an algorithm for SSE2, and we turn this into a 64-bit
261     // FILD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263   }
264
265   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266   // this operation.
267   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270   if (!TM.Options.UseSoftFloat) {
271     // SSE has no i16 to fp conversion, only i32
272     if (X86ScalarSSEf32) {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274       // f32 and f64 cases are Legal, f80 case is not
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     } else {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     }
280   } else {
281     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283   }
284
285   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286   // are Legal, f80 is custom lowered.
287   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291   // this operation.
292   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295   if (X86ScalarSSEf32) {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297     // f32 and f64 cases are Legal, f80 case is not
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   } else {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   }
303
304   // Handle FP_TO_UINT by promoting the destination to a larger signed
305   // conversion.
306   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310   if (Subtarget->is64Bit()) {
311     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313   } else if (!TM.Options.UseSoftFloat) {
314     // Since AVX is a superset of SSE3, only check for SSE here.
315     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316       // Expand FP_TO_UINT into a select.
317       // FIXME: We would like to use a Custom expander here eventually to do
318       // the optimal thing for SSE vs. the default expansion in the legalizer.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320     else
321       // With SSE3 we can use fisttpll to convert to a signed i64; without
322       // SSE, we're stuck with a fistpll.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324   }
325
326   if (isTargetFTOL()) {
327     // Use the _ftol2 runtime function, which has a pseudo-instruction
328     // to handle its weird calling convention.
329     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330   }
331
332   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333   if (!X86ScalarSSEf64) {
334     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336     if (Subtarget->is64Bit()) {
337       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338       // Without SSE, i64->f64 goes through memory.
339       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340     }
341   }
342
343   // Scalar integer divide and remainder are lowered to use operations that
344   // produce two results, to match the available instructions. This exposes
345   // the two-result form to trivial CSE, which is able to combine x/y and x%y
346   // into a single instruction.
347   //
348   // Scalar integer multiply-high is also lowered to use two-result
349   // operations, to match the available instructions. However, plain multiply
350   // (low) operations are left as Legal, as there are single-result
351   // instructions for this in x86. Using the two-result multiply instructions
352   // when both high and low results are needed must be arranged by dagcombine.
353   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354     MVT VT = IntVTs[i];
355     setOperationAction(ISD::MULHS, VT, Expand);
356     setOperationAction(ISD::MULHU, VT, Expand);
357     setOperationAction(ISD::SDIV, VT, Expand);
358     setOperationAction(ISD::UDIV, VT, Expand);
359     setOperationAction(ISD::SREM, VT, Expand);
360     setOperationAction(ISD::UREM, VT, Expand);
361
362     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363     setOperationAction(ISD::ADDC, VT, Custom);
364     setOperationAction(ISD::ADDE, VT, Custom);
365     setOperationAction(ISD::SUBC, VT, Custom);
366     setOperationAction(ISD::SUBE, VT, Custom);
367   }
368
369   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373   if (Subtarget->is64Bit())
374     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384   // Promote the i8 variants and force them on up to i32 which has a shorter
385   // encoding.
386   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390   if (Subtarget->hasBMI()) {
391     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393     if (Subtarget->is64Bit())
394       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395   } else {
396     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasLZCNT()) {
403     // When promoting the i8 variants, force them to i32 for a shorter
404     // encoding.
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411     if (Subtarget->is64Bit())
412       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413   } else {
414     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420     if (Subtarget->is64Bit()) {
421       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423     }
424   }
425
426   if (Subtarget->hasPOPCNT()) {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428   } else {
429     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432     if (Subtarget->is64Bit())
433       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434   }
435
436   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439   // These should be promoted to a larger select which is supported.
440   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441   // X86 wants to expand cmov itself.
442   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454   if (Subtarget->is64Bit()) {
455     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457   }
458   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461   // support continuation, user-level threading, and etc.. As a result, no
462   // other SjLj exception interfaces are implemented and please don't build
463   // your own exception handling based on them.
464   // LLVM/Clang supports zero-cost DWARF exception handling.
465   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468   // Darwin ABI issue.
469   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473   if (Subtarget->is64Bit())
474     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483   }
484   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488   if (Subtarget->is64Bit()) {
489     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasSSE1())
495     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500   // On X86 and X86-64, atomic operations are lowered to locked instructions.
501   // Locked instructions, in turn, have implicit fence semantics (all memory
502   // operations are flushed before issuing the locked instruction, and they
503   // are not buffered), so we can fold away the common pattern of
504   // fence-atomic-fence.
505   setShouldFoldAtomicFences(true);
506
507   // Expand certain atomics
508   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509     MVT VT = IntVTs[i];
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513   }
514
515   if (!Subtarget->is64Bit()) {
516     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528   }
529
530   if (Subtarget->hasCmpxchg16b()) {
531     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532   }
533
534   // FIXME - use subtarget debug flags
535   if (!Subtarget->isTargetDarwin() &&
536       !Subtarget->isTargetELF() &&
537       !Subtarget->isTargetCygMing()) {
538     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539   }
540
541   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545   if (Subtarget->is64Bit()) {
546     setExceptionPointerRegister(X86::RAX);
547     setExceptionSelectorRegister(X86::RDX);
548   } else {
549     setExceptionPointerRegister(X86::EAX);
550     setExceptionSelectorRegister(X86::EDX);
551   }
552   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558   setOperationAction(ISD::TRAP, MVT::Other, Legal);
559   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730     MVT VT = (MVT::SimpleValueType)i;
731     setOperationAction(ISD::ADD , VT, Expand);
732     setOperationAction(ISD::SUB , VT, Expand);
733     setOperationAction(ISD::FADD, VT, Expand);
734     setOperationAction(ISD::FNEG, VT, Expand);
735     setOperationAction(ISD::FSUB, VT, Expand);
736     setOperationAction(ISD::MUL , VT, Expand);
737     setOperationAction(ISD::FMUL, VT, Expand);
738     setOperationAction(ISD::SDIV, VT, Expand);
739     setOperationAction(ISD::UDIV, VT, Expand);
740     setOperationAction(ISD::FDIV, VT, Expand);
741     setOperationAction(ISD::SREM, VT, Expand);
742     setOperationAction(ISD::UREM, VT, Expand);
743     setOperationAction(ISD::LOAD, VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749     setOperationAction(ISD::FABS, VT, Expand);
750     setOperationAction(ISD::FSIN, VT, Expand);
751     setOperationAction(ISD::FCOS, VT, Expand);
752     setOperationAction(ISD::FREM, VT, Expand);
753     setOperationAction(ISD::FMA,  VT, Expand);
754     setOperationAction(ISD::FPOWI, VT, Expand);
755     setOperationAction(ISD::FSQRT, VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757     setOperationAction(ISD::FFLOOR, VT, Expand);
758     setOperationAction(ISD::FCEIL, VT, Expand);
759     setOperationAction(ISD::FTRUNC, VT, Expand);
760     setOperationAction(ISD::FRINT, VT, Expand);
761     setOperationAction(ISD::FNEARBYINT, VT, Expand);
762     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764     setOperationAction(ISD::SDIVREM, VT, Expand);
765     setOperationAction(ISD::UDIVREM, VT, Expand);
766     setOperationAction(ISD::FPOW, VT, Expand);
767     setOperationAction(ISD::CTPOP, VT, Expand);
768     setOperationAction(ISD::CTTZ, VT, Expand);
769     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770     setOperationAction(ISD::CTLZ, VT, Expand);
771     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772     setOperationAction(ISD::SHL, VT, Expand);
773     setOperationAction(ISD::SRA, VT, Expand);
774     setOperationAction(ISD::SRL, VT, Expand);
775     setOperationAction(ISD::ROTL, VT, Expand);
776     setOperationAction(ISD::ROTR, VT, Expand);
777     setOperationAction(ISD::BSWAP, VT, Expand);
778     setOperationAction(ISD::SETCC, VT, Expand);
779     setOperationAction(ISD::FLOG, VT, Expand);
780     setOperationAction(ISD::FLOG2, VT, Expand);
781     setOperationAction(ISD::FLOG10, VT, Expand);
782     setOperationAction(ISD::FEXP, VT, Expand);
783     setOperationAction(ISD::FEXP2, VT, Expand);
784     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789     setOperationAction(ISD::TRUNCATE, VT, Expand);
790     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793     setOperationAction(ISD::VSELECT, VT, Expand);
794     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796       setTruncStoreAction(VT,
797                           (MVT::SimpleValueType)InnerVT, Expand);
798     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
801   }
802
803   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804   // with -msoft-float, disable use of MMX as well.
805   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807     // No operations on x86mmx supported, everything uses intrinsics.
808   }
809
810   // MMX-sized vectors (other than x86mmx) are expected to be expanded
811   // into smaller operations.
812   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
813   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
814   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
815   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
816   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
817   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
818   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
819   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
820   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
821   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
822   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
823   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
824   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
825   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
826   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
827   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
828   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
829   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
830   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
831   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
832   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
833   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
834   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
835   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
836   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
837   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
838   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
839   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
840   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
841
842   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
844
845     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
846     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
847     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
848     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
849     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
850     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
851     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
852     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
853     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
854     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
855     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
857   }
858
859   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
861
862     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863     // registers cannot be used even for integer operations.
864     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
868
869     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
870     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
871     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
872     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
874     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
875     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
876     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
877     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
878     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
879     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
880     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
881     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
882     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
883     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
884     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
885     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
886     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
887
888     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
889     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
890     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
891     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
892
893     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
894     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
895     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
898
899     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901       MVT VT = (MVT::SimpleValueType)i;
902       // Do not attempt to custom lower non-power-of-2 vectors
903       if (!isPowerOf2_32(VT.getVectorNumElements()))
904         continue;
905       // Do not attempt to custom lower non-128-bit vectors
906       if (!VT.is128BitVector())
907         continue;
908       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
909       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911     }
912
913     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
916     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
917     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
919
920     if (Subtarget->is64Bit()) {
921       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
922       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
923     }
924
925     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927       MVT VT = (MVT::SimpleValueType)i;
928
929       // Do not attempt to promote non-128-bit vectors
930       if (!VT.is128BitVector())
931         continue;
932
933       setOperationAction(ISD::AND,    VT, Promote);
934       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
935       setOperationAction(ISD::OR,     VT, Promote);
936       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
937       setOperationAction(ISD::XOR,    VT, Promote);
938       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
939       setOperationAction(ISD::LOAD,   VT, Promote);
940       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
941       setOperationAction(ISD::SELECT, VT, Promote);
942       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
943     }
944
945     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
946
947     // Custom lower v2i64 and v2f64 selects.
948     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
950     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
951     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
952
953     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
954     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
955
956     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
957     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
958     // As there is no 64-bit GPR available, we need build a special custom
959     // sequence to convert from v2i32 to v2f32.
960     if (!Subtarget->is64Bit())
961       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
962
963     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
964     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
965
966     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
967   }
968
969   if (Subtarget->hasSSE41()) {
970     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
971     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
972     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
973     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
974     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
975     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
976     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
977     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
978     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
979     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
980
981     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
982     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
983     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
984     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
985     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
986     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
987     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
988     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
989     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
990     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
991
992     // FIXME: Do we need to handle scalar-to-vector here?
993     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
994
995     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
996     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
997     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
998     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
999     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1000
1001     // i8 and i16 vectors are custom , because the source register and source
1002     // source memory operand types are not the same width.  f32 vectors are
1003     // custom since the immediate controlling the insert encodes additional
1004     // information.
1005     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1009
1010     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014
1015     // FIXME: these should be Legal but thats only for the case where
1016     // the index is constant.  For now custom expand to deal with that.
1017     if (Subtarget->is64Bit()) {
1018       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1019       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020     }
1021   }
1022
1023   if (Subtarget->hasSSE2()) {
1024     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1026
1027     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1028     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1029
1030     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1031     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1032
1033     if (Subtarget->hasInt256()) {
1034       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1035       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1036
1037       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1038       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1039
1040       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1041     } else {
1042       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1043       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1044
1045       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1046       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1047
1048       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1049     }
1050   }
1051
1052   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1053     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1059
1060     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1063
1064     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1076
1077     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1089
1090     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1091
1092     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1093
1094     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1095     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1096     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1097
1098     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1099     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1100     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1101
1102     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1103
1104     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1105     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1106
1107     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1114     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1115     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1116     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1117
1118     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1119     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1120     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1121
1122     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1123     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1124     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1125     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1126
1127     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1128       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1129       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1130       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1134     }
1135
1136     if (Subtarget->hasInt256()) {
1137       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1138       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1139       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1141
1142       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1143       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1144       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1146
1147       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1148       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1149       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1150       // Don't lower v32i8 because there is no 128-bit byte mul
1151
1152       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1153
1154       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1155       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1156
1157       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1158       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1159
1160       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1161     } else {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1175       // Don't lower v32i8 because there is no 128-bit byte mul
1176
1177       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1178       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1179
1180       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1182
1183       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1184     }
1185
1186     // Custom lower several nodes for 256-bit types.
1187     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1188              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1189       MVT VT = (MVT::SimpleValueType)i;
1190
1191       // Extract subvector is special because the value type
1192       // (result) is 128-bit but the source is 256-bit wide.
1193       if (VT.is128BitVector())
1194         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1195
1196       // Do not attempt to custom lower other non-256-bit vectors
1197       if (!VT.is256BitVector())
1198         continue;
1199
1200       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1201       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1202       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1203       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1204       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1205       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1206       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1207     }
1208
1209     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1210     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1211       MVT VT = (MVT::SimpleValueType)i;
1212
1213       // Do not attempt to promote non-256-bit vectors
1214       if (!VT.is256BitVector())
1215         continue;
1216
1217       setOperationAction(ISD::AND,    VT, Promote);
1218       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1219       setOperationAction(ISD::OR,     VT, Promote);
1220       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1221       setOperationAction(ISD::XOR,    VT, Promote);
1222       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1223       setOperationAction(ISD::LOAD,   VT, Promote);
1224       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1225       setOperationAction(ISD::SELECT, VT, Promote);
1226       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1227     }
1228   }
1229
1230   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1231   // of this type with custom code.
1232   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1233            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1234     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1235                        Custom);
1236   }
1237
1238   // We want to custom lower some of our intrinsics.
1239   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1240   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1241
1242
1243   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1244   // handle type legalization for these operations here.
1245   //
1246   // FIXME: We really should do custom legalization for addition and
1247   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1248   // than generic legalization for 64-bit multiplication-with-overflow, though.
1249   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1250     // Add/Sub/Mul with overflow operations are custom lowered.
1251     MVT VT = IntVTs[i];
1252     setOperationAction(ISD::SADDO, VT, Custom);
1253     setOperationAction(ISD::UADDO, VT, Custom);
1254     setOperationAction(ISD::SSUBO, VT, Custom);
1255     setOperationAction(ISD::USUBO, VT, Custom);
1256     setOperationAction(ISD::SMULO, VT, Custom);
1257     setOperationAction(ISD::UMULO, VT, Custom);
1258   }
1259
1260   // There are no 8-bit 3-address imul/mul instructions
1261   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1262   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1263
1264   if (!Subtarget->is64Bit()) {
1265     // These libcalls are not available in 32-bit.
1266     setLibcallName(RTLIB::SHL_I128, 0);
1267     setLibcallName(RTLIB::SRL_I128, 0);
1268     setLibcallName(RTLIB::SRA_I128, 0);
1269   }
1270
1271   // We have target-specific dag combine patterns for the following nodes:
1272   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1273   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1274   setTargetDAGCombine(ISD::VSELECT);
1275   setTargetDAGCombine(ISD::SELECT);
1276   setTargetDAGCombine(ISD::SHL);
1277   setTargetDAGCombine(ISD::SRA);
1278   setTargetDAGCombine(ISD::SRL);
1279   setTargetDAGCombine(ISD::OR);
1280   setTargetDAGCombine(ISD::AND);
1281   setTargetDAGCombine(ISD::ADD);
1282   setTargetDAGCombine(ISD::FADD);
1283   setTargetDAGCombine(ISD::FSUB);
1284   setTargetDAGCombine(ISD::FMA);
1285   setTargetDAGCombine(ISD::SUB);
1286   setTargetDAGCombine(ISD::LOAD);
1287   setTargetDAGCombine(ISD::STORE);
1288   setTargetDAGCombine(ISD::ZERO_EXTEND);
1289   setTargetDAGCombine(ISD::ANY_EXTEND);
1290   setTargetDAGCombine(ISD::SIGN_EXTEND);
1291   setTargetDAGCombine(ISD::TRUNCATE);
1292   setTargetDAGCombine(ISD::SINT_TO_FP);
1293   setTargetDAGCombine(ISD::SETCC);
1294   if (Subtarget->is64Bit())
1295     setTargetDAGCombine(ISD::MUL);
1296   setTargetDAGCombine(ISD::XOR);
1297
1298   computeRegisterProperties();
1299
1300   // On Darwin, -Os means optimize for size without hurting performance,
1301   // do not reduce the limit.
1302   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1303   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1304   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1305   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1306   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1307   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1308   setPrefLoopAlignment(4); // 2^4 bytes.
1309   benefitFromCodePlacementOpt = true;
1310
1311   // Predictable cmov don't hurt on atom because it's in-order.
1312   predictableSelectIsExpensive = !Subtarget->isAtom();
1313
1314   setPrefFunctionAlignment(4); // 2^4 bytes.
1315 }
1316
1317
1318 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1319   if (!VT.isVector()) return MVT::i8;
1320   return VT.changeVectorElementTypeToInteger();
1321 }
1322
1323
1324 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1325 /// the desired ByVal argument alignment.
1326 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1327   if (MaxAlign == 16)
1328     return;
1329   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1330     if (VTy->getBitWidth() == 128)
1331       MaxAlign = 16;
1332   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1333     unsigned EltAlign = 0;
1334     getMaxByValAlign(ATy->getElementType(), EltAlign);
1335     if (EltAlign > MaxAlign)
1336       MaxAlign = EltAlign;
1337   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1338     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1339       unsigned EltAlign = 0;
1340       getMaxByValAlign(STy->getElementType(i), EltAlign);
1341       if (EltAlign > MaxAlign)
1342         MaxAlign = EltAlign;
1343       if (MaxAlign == 16)
1344         break;
1345     }
1346   }
1347 }
1348
1349 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1350 /// function arguments in the caller parameter area. For X86, aggregates
1351 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1352 /// are at 4-byte boundaries.
1353 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1354   if (Subtarget->is64Bit()) {
1355     // Max of 8 and alignment of type.
1356     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1357     if (TyAlign > 8)
1358       return TyAlign;
1359     return 8;
1360   }
1361
1362   unsigned Align = 4;
1363   if (Subtarget->hasSSE1())
1364     getMaxByValAlign(Ty, Align);
1365   return Align;
1366 }
1367
1368 /// getOptimalMemOpType - Returns the target specific optimal type for load
1369 /// and store operations as a result of memset, memcpy, and memmove
1370 /// lowering. If DstAlign is zero that means it's safe to destination
1371 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1372 /// means there isn't a need to check it against alignment requirement,
1373 /// probably because the source does not need to be loaded. If 'IsMemset' is
1374 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1375 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1376 /// source is constant so it does not need to be loaded.
1377 /// It returns EVT::Other if the type should be determined using generic
1378 /// target-independent logic.
1379 EVT
1380 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1381                                        unsigned DstAlign, unsigned SrcAlign,
1382                                        bool IsMemset, bool ZeroMemset,
1383                                        bool MemcpyStrSrc,
1384                                        MachineFunction &MF) const {
1385   const Function *F = MF.getFunction();
1386   if ((!IsMemset || ZeroMemset) &&
1387       !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1388     if (Size >= 16 &&
1389         (Subtarget->isUnalignedMemAccessFast() ||
1390          ((DstAlign == 0 || DstAlign >= 16) &&
1391           (SrcAlign == 0 || SrcAlign >= 16)))) {
1392       if (Size >= 32) {
1393         if (Subtarget->hasInt256())
1394           return MVT::v8i32;
1395         if (Subtarget->hasFp256())
1396           return MVT::v8f32;
1397       }
1398       if (Subtarget->hasSSE2())
1399         return MVT::v4i32;
1400       if (Subtarget->hasSSE1())
1401         return MVT::v4f32;
1402     } else if (!MemcpyStrSrc && Size >= 8 &&
1403                !Subtarget->is64Bit() &&
1404                Subtarget->hasSSE2()) {
1405       // Do not use f64 to lower memcpy if source is string constant. It's
1406       // better to use i32 to avoid the loads.
1407       return MVT::f64;
1408     }
1409   }
1410   if (Subtarget->is64Bit() && Size >= 8)
1411     return MVT::i64;
1412   return MVT::i32;
1413 }
1414
1415 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1416   if (VT == MVT::f32)
1417     return X86ScalarSSEf32;
1418   else if (VT == MVT::f64)
1419     return X86ScalarSSEf64;
1420   return true;
1421 }
1422
1423 bool
1424 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1425   if (Fast)
1426     *Fast = Subtarget->isUnalignedMemAccessFast();
1427   return true;
1428 }
1429
1430 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1431 /// current function.  The returned value is a member of the
1432 /// MachineJumpTableInfo::JTEntryKind enum.
1433 unsigned X86TargetLowering::getJumpTableEncoding() const {
1434   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1435   // symbol.
1436   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1437       Subtarget->isPICStyleGOT())
1438     return MachineJumpTableInfo::EK_Custom32;
1439
1440   // Otherwise, use the normal jump table encoding heuristics.
1441   return TargetLowering::getJumpTableEncoding();
1442 }
1443
1444 const MCExpr *
1445 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1446                                              const MachineBasicBlock *MBB,
1447                                              unsigned uid,MCContext &Ctx) const{
1448   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1449          Subtarget->isPICStyleGOT());
1450   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1451   // entries.
1452   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1453                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1454 }
1455
1456 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1457 /// jumptable.
1458 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1459                                                     SelectionDAG &DAG) const {
1460   if (!Subtarget->is64Bit())
1461     // This doesn't have DebugLoc associated with it, but is not really the
1462     // same as a Register.
1463     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1464   return Table;
1465 }
1466
1467 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1468 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1469 /// MCExpr.
1470 const MCExpr *X86TargetLowering::
1471 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1472                              MCContext &Ctx) const {
1473   // X86-64 uses RIP relative addressing based on the jump table label.
1474   if (Subtarget->isPICStyleRIPRel())
1475     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1476
1477   // Otherwise, the reference is relative to the PIC base.
1478   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1479 }
1480
1481 // FIXME: Why this routine is here? Move to RegInfo!
1482 std::pair<const TargetRegisterClass*, uint8_t>
1483 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1484   const TargetRegisterClass *RRC = 0;
1485   uint8_t Cost = 1;
1486   switch (VT.SimpleTy) {
1487   default:
1488     return TargetLowering::findRepresentativeClass(VT);
1489   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1490     RRC = Subtarget->is64Bit() ?
1491       (const TargetRegisterClass*)&X86::GR64RegClass :
1492       (const TargetRegisterClass*)&X86::GR32RegClass;
1493     break;
1494   case MVT::x86mmx:
1495     RRC = &X86::VR64RegClass;
1496     break;
1497   case MVT::f32: case MVT::f64:
1498   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1499   case MVT::v4f32: case MVT::v2f64:
1500   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1501   case MVT::v4f64:
1502     RRC = &X86::VR128RegClass;
1503     break;
1504   }
1505   return std::make_pair(RRC, Cost);
1506 }
1507
1508 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1509                                                unsigned &Offset) const {
1510   if (!Subtarget->isTargetLinux())
1511     return false;
1512
1513   if (Subtarget->is64Bit()) {
1514     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1515     Offset = 0x28;
1516     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1517       AddressSpace = 256;
1518     else
1519       AddressSpace = 257;
1520   } else {
1521     // %gs:0x14 on i386
1522     Offset = 0x14;
1523     AddressSpace = 256;
1524   }
1525   return true;
1526 }
1527
1528
1529 //===----------------------------------------------------------------------===//
1530 //               Return Value Calling Convention Implementation
1531 //===----------------------------------------------------------------------===//
1532
1533 #include "X86GenCallingConv.inc"
1534
1535 bool
1536 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1537                                   MachineFunction &MF, bool isVarArg,
1538                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1539                         LLVMContext &Context) const {
1540   SmallVector<CCValAssign, 16> RVLocs;
1541   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1542                  RVLocs, Context);
1543   return CCInfo.CheckReturn(Outs, RetCC_X86);
1544 }
1545
1546 SDValue
1547 X86TargetLowering::LowerReturn(SDValue Chain,
1548                                CallingConv::ID CallConv, bool isVarArg,
1549                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1550                                const SmallVectorImpl<SDValue> &OutVals,
1551                                DebugLoc dl, SelectionDAG &DAG) const {
1552   MachineFunction &MF = DAG.getMachineFunction();
1553   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1554
1555   SmallVector<CCValAssign, 16> RVLocs;
1556   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1557                  RVLocs, *DAG.getContext());
1558   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1559
1560   // Add the regs to the liveout set for the function.
1561   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1562   for (unsigned i = 0; i != RVLocs.size(); ++i)
1563     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1564       MRI.addLiveOut(RVLocs[i].getLocReg());
1565
1566   SDValue Flag;
1567
1568   SmallVector<SDValue, 6> RetOps;
1569   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1570   // Operand #1 = Bytes To Pop
1571   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1572                    MVT::i16));
1573
1574   // Copy the result values into the output registers.
1575   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1576     CCValAssign &VA = RVLocs[i];
1577     assert(VA.isRegLoc() && "Can only return in registers!");
1578     SDValue ValToCopy = OutVals[i];
1579     EVT ValVT = ValToCopy.getValueType();
1580
1581     // Promote values to the appropriate types
1582     if (VA.getLocInfo() == CCValAssign::SExt)
1583       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1584     else if (VA.getLocInfo() == CCValAssign::ZExt)
1585       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1586     else if (VA.getLocInfo() == CCValAssign::AExt)
1587       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1588     else if (VA.getLocInfo() == CCValAssign::BCvt)
1589       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1590
1591     // If this is x86-64, and we disabled SSE, we can't return FP values,
1592     // or SSE or MMX vectors.
1593     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1594          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1595           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1596       report_fatal_error("SSE register return with SSE disabled");
1597     }
1598     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1599     // llvm-gcc has never done it right and no one has noticed, so this
1600     // should be OK for now.
1601     if (ValVT == MVT::f64 &&
1602         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1603       report_fatal_error("SSE2 register return with SSE2 disabled");
1604
1605     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1606     // the RET instruction and handled by the FP Stackifier.
1607     if (VA.getLocReg() == X86::ST0 ||
1608         VA.getLocReg() == X86::ST1) {
1609       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1610       // change the value to the FP stack register class.
1611       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1612         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1613       RetOps.push_back(ValToCopy);
1614       // Don't emit a copytoreg.
1615       continue;
1616     }
1617
1618     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1619     // which is returned in RAX / RDX.
1620     if (Subtarget->is64Bit()) {
1621       if (ValVT == MVT::x86mmx) {
1622         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1623           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1624           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1625                                   ValToCopy);
1626           // If we don't have SSE2 available, convert to v4f32 so the generated
1627           // register is legal.
1628           if (!Subtarget->hasSSE2())
1629             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1630         }
1631       }
1632     }
1633
1634     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1635     Flag = Chain.getValue(1);
1636   }
1637
1638   // The x86-64 ABI for returning structs by value requires that we copy
1639   // the sret argument into %rax for the return. We saved the argument into
1640   // a virtual register in the entry block, so now we copy the value out
1641   // and into %rax.
1642   if (Subtarget->is64Bit() &&
1643       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1644     MachineFunction &MF = DAG.getMachineFunction();
1645     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1646     unsigned Reg = FuncInfo->getSRetReturnReg();
1647     assert(Reg &&
1648            "SRetReturnReg should have been set in LowerFormalArguments().");
1649     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1650
1651     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1652     Flag = Chain.getValue(1);
1653
1654     // RAX now acts like a return value.
1655     MRI.addLiveOut(X86::RAX);
1656   }
1657
1658   RetOps[0] = Chain;  // Update chain.
1659
1660   // Add the flag if we have it.
1661   if (Flag.getNode())
1662     RetOps.push_back(Flag);
1663
1664   return DAG.getNode(X86ISD::RET_FLAG, dl,
1665                      MVT::Other, &RetOps[0], RetOps.size());
1666 }
1667
1668 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1669   if (N->getNumValues() != 1)
1670     return false;
1671   if (!N->hasNUsesOfValue(1, 0))
1672     return false;
1673
1674   SDValue TCChain = Chain;
1675   SDNode *Copy = *N->use_begin();
1676   if (Copy->getOpcode() == ISD::CopyToReg) {
1677     // If the copy has a glue operand, we conservatively assume it isn't safe to
1678     // perform a tail call.
1679     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1680       return false;
1681     TCChain = Copy->getOperand(0);
1682   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1683     return false;
1684
1685   bool HasRet = false;
1686   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1687        UI != UE; ++UI) {
1688     if (UI->getOpcode() != X86ISD::RET_FLAG)
1689       return false;
1690     HasRet = true;
1691   }
1692
1693   if (!HasRet)
1694     return false;
1695
1696   Chain = TCChain;
1697   return true;
1698 }
1699
1700 MVT
1701 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1702                                             ISD::NodeType ExtendKind) const {
1703   MVT ReturnMVT;
1704   // TODO: Is this also valid on 32-bit?
1705   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1706     ReturnMVT = MVT::i8;
1707   else
1708     ReturnMVT = MVT::i32;
1709
1710   MVT MinVT = getRegisterType(ReturnMVT);
1711   return VT.bitsLT(MinVT) ? MinVT : VT;
1712 }
1713
1714 /// LowerCallResult - Lower the result values of a call into the
1715 /// appropriate copies out of appropriate physical registers.
1716 ///
1717 SDValue
1718 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1719                                    CallingConv::ID CallConv, bool isVarArg,
1720                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1721                                    DebugLoc dl, SelectionDAG &DAG,
1722                                    SmallVectorImpl<SDValue> &InVals) const {
1723
1724   // Assign locations to each value returned by this call.
1725   SmallVector<CCValAssign, 16> RVLocs;
1726   bool Is64Bit = Subtarget->is64Bit();
1727   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1728                  getTargetMachine(), RVLocs, *DAG.getContext());
1729   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1730
1731   // Copy all of the result registers out of their specified physreg.
1732   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1733     CCValAssign &VA = RVLocs[i];
1734     EVT CopyVT = VA.getValVT();
1735
1736     // If this is x86-64, and we disabled SSE, we can't return FP values
1737     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1738         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1739       report_fatal_error("SSE register return with SSE disabled");
1740     }
1741
1742     SDValue Val;
1743
1744     // If this is a call to a function that returns an fp value on the floating
1745     // point stack, we must guarantee the value is popped from the stack, so
1746     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1747     // if the return value is not used. We use the FpPOP_RETVAL instruction
1748     // instead.
1749     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1750       // If we prefer to use the value in xmm registers, copy it out as f80 and
1751       // use a truncate to move it from fp stack reg to xmm reg.
1752       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1753       SDValue Ops[] = { Chain, InFlag };
1754       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1755                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1756       Val = Chain.getValue(0);
1757
1758       // Round the f80 to the right size, which also moves it to the appropriate
1759       // xmm register.
1760       if (CopyVT != VA.getValVT())
1761         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1762                           // This truncation won't change the value.
1763                           DAG.getIntPtrConstant(1));
1764     } else {
1765       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1766                                  CopyVT, InFlag).getValue(1);
1767       Val = Chain.getValue(0);
1768     }
1769     InFlag = Chain.getValue(2);
1770     InVals.push_back(Val);
1771   }
1772
1773   return Chain;
1774 }
1775
1776
1777 //===----------------------------------------------------------------------===//
1778 //                C & StdCall & Fast Calling Convention implementation
1779 //===----------------------------------------------------------------------===//
1780 //  StdCall calling convention seems to be standard for many Windows' API
1781 //  routines and around. It differs from C calling convention just a little:
1782 //  callee should clean up the stack, not caller. Symbols should be also
1783 //  decorated in some fancy way :) It doesn't support any vector arguments.
1784 //  For info on fast calling convention see Fast Calling Convention (tail call)
1785 //  implementation LowerX86_32FastCCCallTo.
1786
1787 /// CallIsStructReturn - Determines whether a call uses struct return
1788 /// semantics.
1789 enum StructReturnType {
1790   NotStructReturn,
1791   RegStructReturn,
1792   StackStructReturn
1793 };
1794 static StructReturnType
1795 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1796   if (Outs.empty())
1797     return NotStructReturn;
1798
1799   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1800   if (!Flags.isSRet())
1801     return NotStructReturn;
1802   if (Flags.isInReg())
1803     return RegStructReturn;
1804   return StackStructReturn;
1805 }
1806
1807 /// ArgsAreStructReturn - Determines whether a function uses struct
1808 /// return semantics.
1809 static StructReturnType
1810 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1811   if (Ins.empty())
1812     return NotStructReturn;
1813
1814   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1815   if (!Flags.isSRet())
1816     return NotStructReturn;
1817   if (Flags.isInReg())
1818     return RegStructReturn;
1819   return StackStructReturn;
1820 }
1821
1822 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1823 /// by "Src" to address "Dst" with size and alignment information specified by
1824 /// the specific parameter attribute. The copy will be passed as a byval
1825 /// function parameter.
1826 static SDValue
1827 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1828                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1829                           DebugLoc dl) {
1830   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1831
1832   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1833                        /*isVolatile*/false, /*AlwaysInline=*/true,
1834                        MachinePointerInfo(), MachinePointerInfo());
1835 }
1836
1837 /// IsTailCallConvention - Return true if the calling convention is one that
1838 /// supports tail call optimization.
1839 static bool IsTailCallConvention(CallingConv::ID CC) {
1840   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1841           CC == CallingConv::HiPE);
1842 }
1843
1844 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1845   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1846     return false;
1847
1848   CallSite CS(CI);
1849   CallingConv::ID CalleeCC = CS.getCallingConv();
1850   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1851     return false;
1852
1853   return true;
1854 }
1855
1856 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1857 /// a tailcall target by changing its ABI.
1858 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1859                                    bool GuaranteedTailCallOpt) {
1860   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1861 }
1862
1863 SDValue
1864 X86TargetLowering::LowerMemArgument(SDValue Chain,
1865                                     CallingConv::ID CallConv,
1866                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1867                                     DebugLoc dl, SelectionDAG &DAG,
1868                                     const CCValAssign &VA,
1869                                     MachineFrameInfo *MFI,
1870                                     unsigned i) const {
1871   // Create the nodes corresponding to a load from this parameter slot.
1872   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1873   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1874                               getTargetMachine().Options.GuaranteedTailCallOpt);
1875   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1876   EVT ValVT;
1877
1878   // If value is passed by pointer we have address passed instead of the value
1879   // itself.
1880   if (VA.getLocInfo() == CCValAssign::Indirect)
1881     ValVT = VA.getLocVT();
1882   else
1883     ValVT = VA.getValVT();
1884
1885   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1886   // changed with more analysis.
1887   // In case of tail call optimization mark all arguments mutable. Since they
1888   // could be overwritten by lowering of arguments in case of a tail call.
1889   if (Flags.isByVal()) {
1890     unsigned Bytes = Flags.getByValSize();
1891     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1892     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1893     return DAG.getFrameIndex(FI, getPointerTy());
1894   } else {
1895     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1896                                     VA.getLocMemOffset(), isImmutable);
1897     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1898     return DAG.getLoad(ValVT, dl, Chain, FIN,
1899                        MachinePointerInfo::getFixedStack(FI),
1900                        false, false, false, 0);
1901   }
1902 }
1903
1904 SDValue
1905 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1906                                         CallingConv::ID CallConv,
1907                                         bool isVarArg,
1908                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1909                                         DebugLoc dl,
1910                                         SelectionDAG &DAG,
1911                                         SmallVectorImpl<SDValue> &InVals)
1912                                           const {
1913   MachineFunction &MF = DAG.getMachineFunction();
1914   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1915
1916   const Function* Fn = MF.getFunction();
1917   if (Fn->hasExternalLinkage() &&
1918       Subtarget->isTargetCygMing() &&
1919       Fn->getName() == "main")
1920     FuncInfo->setForceFramePointer(true);
1921
1922   MachineFrameInfo *MFI = MF.getFrameInfo();
1923   bool Is64Bit = Subtarget->is64Bit();
1924   bool IsWindows = Subtarget->isTargetWindows();
1925   bool IsWin64 = Subtarget->isTargetWin64();
1926
1927   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1928          "Var args not supported with calling convention fastcc, ghc or hipe");
1929
1930   // Assign locations to all of the incoming arguments.
1931   SmallVector<CCValAssign, 16> ArgLocs;
1932   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1933                  ArgLocs, *DAG.getContext());
1934
1935   // Allocate shadow area for Win64
1936   if (IsWin64) {
1937     CCInfo.AllocateStack(32, 8);
1938   }
1939
1940   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1941
1942   unsigned LastVal = ~0U;
1943   SDValue ArgValue;
1944   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1945     CCValAssign &VA = ArgLocs[i];
1946     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1947     // places.
1948     assert(VA.getValNo() != LastVal &&
1949            "Don't support value assigned to multiple locs yet");
1950     (void)LastVal;
1951     LastVal = VA.getValNo();
1952
1953     if (VA.isRegLoc()) {
1954       EVT RegVT = VA.getLocVT();
1955       const TargetRegisterClass *RC;
1956       if (RegVT == MVT::i32)
1957         RC = &X86::GR32RegClass;
1958       else if (Is64Bit && RegVT == MVT::i64)
1959         RC = &X86::GR64RegClass;
1960       else if (RegVT == MVT::f32)
1961         RC = &X86::FR32RegClass;
1962       else if (RegVT == MVT::f64)
1963         RC = &X86::FR64RegClass;
1964       else if (RegVT.is256BitVector())
1965         RC = &X86::VR256RegClass;
1966       else if (RegVT.is128BitVector())
1967         RC = &X86::VR128RegClass;
1968       else if (RegVT == MVT::x86mmx)
1969         RC = &X86::VR64RegClass;
1970       else
1971         llvm_unreachable("Unknown argument type!");
1972
1973       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1974       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1975
1976       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1977       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1978       // right size.
1979       if (VA.getLocInfo() == CCValAssign::SExt)
1980         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1981                                DAG.getValueType(VA.getValVT()));
1982       else if (VA.getLocInfo() == CCValAssign::ZExt)
1983         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1984                                DAG.getValueType(VA.getValVT()));
1985       else if (VA.getLocInfo() == CCValAssign::BCvt)
1986         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1987
1988       if (VA.isExtInLoc()) {
1989         // Handle MMX values passed in XMM regs.
1990         if (RegVT.isVector()) {
1991           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1992                                  ArgValue);
1993         } else
1994           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1995       }
1996     } else {
1997       assert(VA.isMemLoc());
1998       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1999     }
2000
2001     // If value is passed via pointer - do a load.
2002     if (VA.getLocInfo() == CCValAssign::Indirect)
2003       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2004                              MachinePointerInfo(), false, false, false, 0);
2005
2006     InVals.push_back(ArgValue);
2007   }
2008
2009   // The x86-64 ABI for returning structs by value requires that we copy
2010   // the sret argument into %rax for the return. Save the argument into
2011   // a virtual register so that we can access it from the return points.
2012   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2013     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2014     unsigned Reg = FuncInfo->getSRetReturnReg();
2015     if (!Reg) {
2016       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2017       FuncInfo->setSRetReturnReg(Reg);
2018     }
2019     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2020     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2021   }
2022
2023   unsigned StackSize = CCInfo.getNextStackOffset();
2024   // Align stack specially for tail calls.
2025   if (FuncIsMadeTailCallSafe(CallConv,
2026                              MF.getTarget().Options.GuaranteedTailCallOpt))
2027     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2028
2029   // If the function takes variable number of arguments, make a frame index for
2030   // the start of the first vararg value... for expansion of llvm.va_start.
2031   if (isVarArg) {
2032     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2033                     CallConv != CallingConv::X86_ThisCall)) {
2034       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2035     }
2036     if (Is64Bit) {
2037       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2038
2039       // FIXME: We should really autogenerate these arrays
2040       static const uint16_t GPR64ArgRegsWin64[] = {
2041         X86::RCX, X86::RDX, X86::R8,  X86::R9
2042       };
2043       static const uint16_t GPR64ArgRegs64Bit[] = {
2044         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2045       };
2046       static const uint16_t XMMArgRegs64Bit[] = {
2047         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2048         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2049       };
2050       const uint16_t *GPR64ArgRegs;
2051       unsigned NumXMMRegs = 0;
2052
2053       if (IsWin64) {
2054         // The XMM registers which might contain var arg parameters are shadowed
2055         // in their paired GPR.  So we only need to save the GPR to their home
2056         // slots.
2057         TotalNumIntRegs = 4;
2058         GPR64ArgRegs = GPR64ArgRegsWin64;
2059       } else {
2060         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2061         GPR64ArgRegs = GPR64ArgRegs64Bit;
2062
2063         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2064                                                 TotalNumXMMRegs);
2065       }
2066       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2067                                                        TotalNumIntRegs);
2068
2069       bool NoImplicitFloatOps = Fn->getFnAttributes().
2070         hasAttribute(Attribute::NoImplicitFloat);
2071       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2072              "SSE register cannot be used when SSE is disabled!");
2073       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2074                NoImplicitFloatOps) &&
2075              "SSE register cannot be used when SSE is disabled!");
2076       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2077           !Subtarget->hasSSE1())
2078         // Kernel mode asks for SSE to be disabled, so don't push them
2079         // on the stack.
2080         TotalNumXMMRegs = 0;
2081
2082       if (IsWin64) {
2083         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2084         // Get to the caller-allocated home save location.  Add 8 to account
2085         // for the return address.
2086         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2087         FuncInfo->setRegSaveFrameIndex(
2088           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2089         // Fixup to set vararg frame on shadow area (4 x i64).
2090         if (NumIntRegs < 4)
2091           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2092       } else {
2093         // For X86-64, if there are vararg parameters that are passed via
2094         // registers, then we must store them to their spots on the stack so
2095         // they may be loaded by deferencing the result of va_next.
2096         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2097         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2098         FuncInfo->setRegSaveFrameIndex(
2099           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2100                                false));
2101       }
2102
2103       // Store the integer parameter registers.
2104       SmallVector<SDValue, 8> MemOps;
2105       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2106                                         getPointerTy());
2107       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2108       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2109         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2110                                   DAG.getIntPtrConstant(Offset));
2111         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2112                                      &X86::GR64RegClass);
2113         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2114         SDValue Store =
2115           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2116                        MachinePointerInfo::getFixedStack(
2117                          FuncInfo->getRegSaveFrameIndex(), Offset),
2118                        false, false, 0);
2119         MemOps.push_back(Store);
2120         Offset += 8;
2121       }
2122
2123       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2124         // Now store the XMM (fp + vector) parameter registers.
2125         SmallVector<SDValue, 11> SaveXMMOps;
2126         SaveXMMOps.push_back(Chain);
2127
2128         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2129         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2130         SaveXMMOps.push_back(ALVal);
2131
2132         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2133                                FuncInfo->getRegSaveFrameIndex()));
2134         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2135                                FuncInfo->getVarArgsFPOffset()));
2136
2137         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2138           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2139                                        &X86::VR128RegClass);
2140           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2141           SaveXMMOps.push_back(Val);
2142         }
2143         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2144                                      MVT::Other,
2145                                      &SaveXMMOps[0], SaveXMMOps.size()));
2146       }
2147
2148       if (!MemOps.empty())
2149         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2150                             &MemOps[0], MemOps.size());
2151     }
2152   }
2153
2154   // Some CCs need callee pop.
2155   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2156                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2157     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2158   } else {
2159     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2160     // If this is an sret function, the return should pop the hidden pointer.
2161     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2162         argsAreStructReturn(Ins) == StackStructReturn)
2163       FuncInfo->setBytesToPopOnReturn(4);
2164   }
2165
2166   if (!Is64Bit) {
2167     // RegSaveFrameIndex is X86-64 only.
2168     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2169     if (CallConv == CallingConv::X86_FastCall ||
2170         CallConv == CallingConv::X86_ThisCall)
2171       // fastcc functions can't have varargs.
2172       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2173   }
2174
2175   FuncInfo->setArgumentStackSize(StackSize);
2176
2177   return Chain;
2178 }
2179
2180 SDValue
2181 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2182                                     SDValue StackPtr, SDValue Arg,
2183                                     DebugLoc dl, SelectionDAG &DAG,
2184                                     const CCValAssign &VA,
2185                                     ISD::ArgFlagsTy Flags) const {
2186   unsigned LocMemOffset = VA.getLocMemOffset();
2187   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2188   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2189   if (Flags.isByVal())
2190     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2191
2192   return DAG.getStore(Chain, dl, Arg, PtrOff,
2193                       MachinePointerInfo::getStack(LocMemOffset),
2194                       false, false, 0);
2195 }
2196
2197 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2198 /// optimization is performed and it is required.
2199 SDValue
2200 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2201                                            SDValue &OutRetAddr, SDValue Chain,
2202                                            bool IsTailCall, bool Is64Bit,
2203                                            int FPDiff, DebugLoc dl) const {
2204   // Adjust the Return address stack slot.
2205   EVT VT = getPointerTy();
2206   OutRetAddr = getReturnAddressFrameIndex(DAG);
2207
2208   // Load the "old" Return address.
2209   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2210                            false, false, false, 0);
2211   return SDValue(OutRetAddr.getNode(), 1);
2212 }
2213
2214 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2215 /// optimization is performed and it is required (FPDiff!=0).
2216 static SDValue
2217 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2218                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2219                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2220   // Store the return address to the appropriate stack slot.
2221   if (!FPDiff) return Chain;
2222   // Calculate the new stack slot for the return address.
2223   int NewReturnAddrFI =
2224     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2225   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2226   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2227                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2228                        false, false, 0);
2229   return Chain;
2230 }
2231
2232 SDValue
2233 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2234                              SmallVectorImpl<SDValue> &InVals) const {
2235   SelectionDAG &DAG                     = CLI.DAG;
2236   DebugLoc &dl                          = CLI.DL;
2237   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2238   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2239   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2240   SDValue Chain                         = CLI.Chain;
2241   SDValue Callee                        = CLI.Callee;
2242   CallingConv::ID CallConv              = CLI.CallConv;
2243   bool &isTailCall                      = CLI.IsTailCall;
2244   bool isVarArg                         = CLI.IsVarArg;
2245
2246   MachineFunction &MF = DAG.getMachineFunction();
2247   bool Is64Bit        = Subtarget->is64Bit();
2248   bool IsWin64        = Subtarget->isTargetWin64();
2249   bool IsWindows      = Subtarget->isTargetWindows();
2250   StructReturnType SR = callIsStructReturn(Outs);
2251   bool IsSibcall      = false;
2252
2253   if (MF.getTarget().Options.DisableTailCalls)
2254     isTailCall = false;
2255
2256   if (isTailCall) {
2257     // Check if it's really possible to do a tail call.
2258     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2259                     isVarArg, SR != NotStructReturn,
2260                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2261                     Outs, OutVals, Ins, DAG);
2262
2263     // Sibcalls are automatically detected tailcalls which do not require
2264     // ABI changes.
2265     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2266       IsSibcall = true;
2267
2268     if (isTailCall)
2269       ++NumTailCalls;
2270   }
2271
2272   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2273          "Var args not supported with calling convention fastcc, ghc or hipe");
2274
2275   // Analyze operands of the call, assigning locations to each operand.
2276   SmallVector<CCValAssign, 16> ArgLocs;
2277   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2278                  ArgLocs, *DAG.getContext());
2279
2280   // Allocate shadow area for Win64
2281   if (IsWin64) {
2282     CCInfo.AllocateStack(32, 8);
2283   }
2284
2285   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2286
2287   // Get a count of how many bytes are to be pushed on the stack.
2288   unsigned NumBytes = CCInfo.getNextStackOffset();
2289   if (IsSibcall)
2290     // This is a sibcall. The memory operands are available in caller's
2291     // own caller's stack.
2292     NumBytes = 0;
2293   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2294            IsTailCallConvention(CallConv))
2295     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2296
2297   int FPDiff = 0;
2298   if (isTailCall && !IsSibcall) {
2299     // Lower arguments at fp - stackoffset + fpdiff.
2300     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2301     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2302
2303     FPDiff = NumBytesCallerPushed - NumBytes;
2304
2305     // Set the delta of movement of the returnaddr stackslot.
2306     // But only set if delta is greater than previous delta.
2307     if (FPDiff < X86Info->getTCReturnAddrDelta())
2308       X86Info->setTCReturnAddrDelta(FPDiff);
2309   }
2310
2311   if (!IsSibcall)
2312     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2313
2314   SDValue RetAddrFrIdx;
2315   // Load return address for tail calls.
2316   if (isTailCall && FPDiff)
2317     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2318                                     Is64Bit, FPDiff, dl);
2319
2320   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2321   SmallVector<SDValue, 8> MemOpChains;
2322   SDValue StackPtr;
2323
2324   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2325   // of tail call optimization arguments are handle later.
2326   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2327     CCValAssign &VA = ArgLocs[i];
2328     EVT RegVT = VA.getLocVT();
2329     SDValue Arg = OutVals[i];
2330     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2331     bool isByVal = Flags.isByVal();
2332
2333     // Promote the value if needed.
2334     switch (VA.getLocInfo()) {
2335     default: llvm_unreachable("Unknown loc info!");
2336     case CCValAssign::Full: break;
2337     case CCValAssign::SExt:
2338       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2339       break;
2340     case CCValAssign::ZExt:
2341       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2342       break;
2343     case CCValAssign::AExt:
2344       if (RegVT.is128BitVector()) {
2345         // Special case: passing MMX values in XMM registers.
2346         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2347         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2348         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2349       } else
2350         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2351       break;
2352     case CCValAssign::BCvt:
2353       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2354       break;
2355     case CCValAssign::Indirect: {
2356       // Store the argument.
2357       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2358       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2359       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2360                            MachinePointerInfo::getFixedStack(FI),
2361                            false, false, 0);
2362       Arg = SpillSlot;
2363       break;
2364     }
2365     }
2366
2367     if (VA.isRegLoc()) {
2368       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2369       if (isVarArg && IsWin64) {
2370         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2371         // shadow reg if callee is a varargs function.
2372         unsigned ShadowReg = 0;
2373         switch (VA.getLocReg()) {
2374         case X86::XMM0: ShadowReg = X86::RCX; break;
2375         case X86::XMM1: ShadowReg = X86::RDX; break;
2376         case X86::XMM2: ShadowReg = X86::R8; break;
2377         case X86::XMM3: ShadowReg = X86::R9; break;
2378         }
2379         if (ShadowReg)
2380           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2381       }
2382     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2383       assert(VA.isMemLoc());
2384       if (StackPtr.getNode() == 0)
2385         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2386                                       getPointerTy());
2387       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2388                                              dl, DAG, VA, Flags));
2389     }
2390   }
2391
2392   if (!MemOpChains.empty())
2393     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2394                         &MemOpChains[0], MemOpChains.size());
2395
2396   if (Subtarget->isPICStyleGOT()) {
2397     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2398     // GOT pointer.
2399     if (!isTailCall) {
2400       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2401                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2402     } else {
2403       // If we are tail calling and generating PIC/GOT style code load the
2404       // address of the callee into ECX. The value in ecx is used as target of
2405       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2406       // for tail calls on PIC/GOT architectures. Normally we would just put the
2407       // address of GOT into ebx and then call target@PLT. But for tail calls
2408       // ebx would be restored (since ebx is callee saved) before jumping to the
2409       // target@PLT.
2410
2411       // Note: The actual moving to ECX is done further down.
2412       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2413       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2414           !G->getGlobal()->hasProtectedVisibility())
2415         Callee = LowerGlobalAddress(Callee, DAG);
2416       else if (isa<ExternalSymbolSDNode>(Callee))
2417         Callee = LowerExternalSymbol(Callee, DAG);
2418     }
2419   }
2420
2421   if (Is64Bit && isVarArg && !IsWin64) {
2422     // From AMD64 ABI document:
2423     // For calls that may call functions that use varargs or stdargs
2424     // (prototype-less calls or calls to functions containing ellipsis (...) in
2425     // the declaration) %al is used as hidden argument to specify the number
2426     // of SSE registers used. The contents of %al do not need to match exactly
2427     // the number of registers, but must be an ubound on the number of SSE
2428     // registers used and is in the range 0 - 8 inclusive.
2429
2430     // Count the number of XMM registers allocated.
2431     static const uint16_t XMMArgRegs[] = {
2432       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2433       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2434     };
2435     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2436     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2437            && "SSE registers cannot be used when SSE is disabled");
2438
2439     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2440                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2441   }
2442
2443   // For tail calls lower the arguments to the 'real' stack slot.
2444   if (isTailCall) {
2445     // Force all the incoming stack arguments to be loaded from the stack
2446     // before any new outgoing arguments are stored to the stack, because the
2447     // outgoing stack slots may alias the incoming argument stack slots, and
2448     // the alias isn't otherwise explicit. This is slightly more conservative
2449     // than necessary, because it means that each store effectively depends
2450     // on every argument instead of just those arguments it would clobber.
2451     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2452
2453     SmallVector<SDValue, 8> MemOpChains2;
2454     SDValue FIN;
2455     int FI = 0;
2456     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2457       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2458         CCValAssign &VA = ArgLocs[i];
2459         if (VA.isRegLoc())
2460           continue;
2461         assert(VA.isMemLoc());
2462         SDValue Arg = OutVals[i];
2463         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2464         // Create frame index.
2465         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2466         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2467         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2468         FIN = DAG.getFrameIndex(FI, getPointerTy());
2469
2470         if (Flags.isByVal()) {
2471           // Copy relative to framepointer.
2472           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2473           if (StackPtr.getNode() == 0)
2474             StackPtr = DAG.getCopyFromReg(Chain, dl,
2475                                           RegInfo->getStackRegister(),
2476                                           getPointerTy());
2477           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2478
2479           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2480                                                            ArgChain,
2481                                                            Flags, DAG, dl));
2482         } else {
2483           // Store relative to framepointer.
2484           MemOpChains2.push_back(
2485             DAG.getStore(ArgChain, dl, Arg, FIN,
2486                          MachinePointerInfo::getFixedStack(FI),
2487                          false, false, 0));
2488         }
2489       }
2490     }
2491
2492     if (!MemOpChains2.empty())
2493       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2494                           &MemOpChains2[0], MemOpChains2.size());
2495
2496     // Store the return address to the appropriate stack slot.
2497     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2498                                      getPointerTy(), RegInfo->getSlotSize(),
2499                                      FPDiff, dl);
2500   }
2501
2502   // Build a sequence of copy-to-reg nodes chained together with token chain
2503   // and flag operands which copy the outgoing args into registers.
2504   SDValue InFlag;
2505   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2506     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2507                              RegsToPass[i].second, InFlag);
2508     InFlag = Chain.getValue(1);
2509   }
2510
2511   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2512     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2513     // In the 64-bit large code model, we have to make all calls
2514     // through a register, since the call instruction's 32-bit
2515     // pc-relative offset may not be large enough to hold the whole
2516     // address.
2517   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2518     // If the callee is a GlobalAddress node (quite common, every direct call
2519     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2520     // it.
2521
2522     // We should use extra load for direct calls to dllimported functions in
2523     // non-JIT mode.
2524     const GlobalValue *GV = G->getGlobal();
2525     if (!GV->hasDLLImportLinkage()) {
2526       unsigned char OpFlags = 0;
2527       bool ExtraLoad = false;
2528       unsigned WrapperKind = ISD::DELETED_NODE;
2529
2530       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2531       // external symbols most go through the PLT in PIC mode.  If the symbol
2532       // has hidden or protected visibility, or if it is static or local, then
2533       // we don't need to use the PLT - we can directly call it.
2534       if (Subtarget->isTargetELF() &&
2535           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2536           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2537         OpFlags = X86II::MO_PLT;
2538       } else if (Subtarget->isPICStyleStubAny() &&
2539                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2540                  (!Subtarget->getTargetTriple().isMacOSX() ||
2541                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2542         // PC-relative references to external symbols should go through $stub,
2543         // unless we're building with the leopard linker or later, which
2544         // automatically synthesizes these stubs.
2545         OpFlags = X86II::MO_DARWIN_STUB;
2546       } else if (Subtarget->isPICStyleRIPRel() &&
2547                  isa<Function>(GV) &&
2548                  cast<Function>(GV)->getFnAttributes().
2549                    hasAttribute(Attribute::NonLazyBind)) {
2550         // If the function is marked as non-lazy, generate an indirect call
2551         // which loads from the GOT directly. This avoids runtime overhead
2552         // at the cost of eager binding (and one extra byte of encoding).
2553         OpFlags = X86II::MO_GOTPCREL;
2554         WrapperKind = X86ISD::WrapperRIP;
2555         ExtraLoad = true;
2556       }
2557
2558       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2559                                           G->getOffset(), OpFlags);
2560
2561       // Add a wrapper if needed.
2562       if (WrapperKind != ISD::DELETED_NODE)
2563         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2564       // Add extra indirection if needed.
2565       if (ExtraLoad)
2566         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2567                              MachinePointerInfo::getGOT(),
2568                              false, false, false, 0);
2569     }
2570   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2571     unsigned char OpFlags = 0;
2572
2573     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2574     // external symbols should go through the PLT.
2575     if (Subtarget->isTargetELF() &&
2576         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2577       OpFlags = X86II::MO_PLT;
2578     } else if (Subtarget->isPICStyleStubAny() &&
2579                (!Subtarget->getTargetTriple().isMacOSX() ||
2580                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2581       // PC-relative references to external symbols should go through $stub,
2582       // unless we're building with the leopard linker or later, which
2583       // automatically synthesizes these stubs.
2584       OpFlags = X86II::MO_DARWIN_STUB;
2585     }
2586
2587     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2588                                          OpFlags);
2589   }
2590
2591   // Returns a chain & a flag for retval copy to use.
2592   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2593   SmallVector<SDValue, 8> Ops;
2594
2595   if (!IsSibcall && isTailCall) {
2596     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2597                            DAG.getIntPtrConstant(0, true), InFlag);
2598     InFlag = Chain.getValue(1);
2599   }
2600
2601   Ops.push_back(Chain);
2602   Ops.push_back(Callee);
2603
2604   if (isTailCall)
2605     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2606
2607   // Add argument registers to the end of the list so that they are known live
2608   // into the call.
2609   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2610     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2611                                   RegsToPass[i].second.getValueType()));
2612
2613   // Add a register mask operand representing the call-preserved registers.
2614   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2615   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2616   assert(Mask && "Missing call preserved mask for calling convention");
2617   Ops.push_back(DAG.getRegisterMask(Mask));
2618
2619   if (InFlag.getNode())
2620     Ops.push_back(InFlag);
2621
2622   if (isTailCall) {
2623     // We used to do:
2624     //// If this is the first return lowered for this function, add the regs
2625     //// to the liveout set for the function.
2626     // This isn't right, although it's probably harmless on x86; liveouts
2627     // should be computed from returns not tail calls.  Consider a void
2628     // function making a tail call to a function returning int.
2629     return DAG.getNode(X86ISD::TC_RETURN, dl,
2630                        NodeTys, &Ops[0], Ops.size());
2631   }
2632
2633   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2634   InFlag = Chain.getValue(1);
2635
2636   // Create the CALLSEQ_END node.
2637   unsigned NumBytesForCalleeToPush;
2638   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2639                        getTargetMachine().Options.GuaranteedTailCallOpt))
2640     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2641   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2642            SR == StackStructReturn)
2643     // If this is a call to a struct-return function, the callee
2644     // pops the hidden struct pointer, so we have to push it back.
2645     // This is common for Darwin/X86, Linux & Mingw32 targets.
2646     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2647     NumBytesForCalleeToPush = 4;
2648   else
2649     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2650
2651   // Returns a flag for retval copy to use.
2652   if (!IsSibcall) {
2653     Chain = DAG.getCALLSEQ_END(Chain,
2654                                DAG.getIntPtrConstant(NumBytes, true),
2655                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2656                                                      true),
2657                                InFlag);
2658     InFlag = Chain.getValue(1);
2659   }
2660
2661   // Handle result values, copying them out of physregs into vregs that we
2662   // return.
2663   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2664                          Ins, dl, DAG, InVals);
2665 }
2666
2667
2668 //===----------------------------------------------------------------------===//
2669 //                Fast Calling Convention (tail call) implementation
2670 //===----------------------------------------------------------------------===//
2671
2672 //  Like std call, callee cleans arguments, convention except that ECX is
2673 //  reserved for storing the tail called function address. Only 2 registers are
2674 //  free for argument passing (inreg). Tail call optimization is performed
2675 //  provided:
2676 //                * tailcallopt is enabled
2677 //                * caller/callee are fastcc
2678 //  On X86_64 architecture with GOT-style position independent code only local
2679 //  (within module) calls are supported at the moment.
2680 //  To keep the stack aligned according to platform abi the function
2681 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2682 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2683 //  If a tail called function callee has more arguments than the caller the
2684 //  caller needs to make sure that there is room to move the RETADDR to. This is
2685 //  achieved by reserving an area the size of the argument delta right after the
2686 //  original REtADDR, but before the saved framepointer or the spilled registers
2687 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2688 //  stack layout:
2689 //    arg1
2690 //    arg2
2691 //    RETADDR
2692 //    [ new RETADDR
2693 //      move area ]
2694 //    (possible EBP)
2695 //    ESI
2696 //    EDI
2697 //    local1 ..
2698
2699 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2700 /// for a 16 byte align requirement.
2701 unsigned
2702 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2703                                                SelectionDAG& DAG) const {
2704   MachineFunction &MF = DAG.getMachineFunction();
2705   const TargetMachine &TM = MF.getTarget();
2706   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2707   unsigned StackAlignment = TFI.getStackAlignment();
2708   uint64_t AlignMask = StackAlignment - 1;
2709   int64_t Offset = StackSize;
2710   unsigned SlotSize = RegInfo->getSlotSize();
2711   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2712     // Number smaller than 12 so just add the difference.
2713     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2714   } else {
2715     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2716     Offset = ((~AlignMask) & Offset) + StackAlignment +
2717       (StackAlignment-SlotSize);
2718   }
2719   return Offset;
2720 }
2721
2722 /// MatchingStackOffset - Return true if the given stack call argument is
2723 /// already available in the same position (relatively) of the caller's
2724 /// incoming argument stack.
2725 static
2726 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2727                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2728                          const X86InstrInfo *TII) {
2729   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2730   int FI = INT_MAX;
2731   if (Arg.getOpcode() == ISD::CopyFromReg) {
2732     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2733     if (!TargetRegisterInfo::isVirtualRegister(VR))
2734       return false;
2735     MachineInstr *Def = MRI->getVRegDef(VR);
2736     if (!Def)
2737       return false;
2738     if (!Flags.isByVal()) {
2739       if (!TII->isLoadFromStackSlot(Def, FI))
2740         return false;
2741     } else {
2742       unsigned Opcode = Def->getOpcode();
2743       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2744           Def->getOperand(1).isFI()) {
2745         FI = Def->getOperand(1).getIndex();
2746         Bytes = Flags.getByValSize();
2747       } else
2748         return false;
2749     }
2750   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2751     if (Flags.isByVal())
2752       // ByVal argument is passed in as a pointer but it's now being
2753       // dereferenced. e.g.
2754       // define @foo(%struct.X* %A) {
2755       //   tail call @bar(%struct.X* byval %A)
2756       // }
2757       return false;
2758     SDValue Ptr = Ld->getBasePtr();
2759     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2760     if (!FINode)
2761       return false;
2762     FI = FINode->getIndex();
2763   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2764     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2765     FI = FINode->getIndex();
2766     Bytes = Flags.getByValSize();
2767   } else
2768     return false;
2769
2770   assert(FI != INT_MAX);
2771   if (!MFI->isFixedObjectIndex(FI))
2772     return false;
2773   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2774 }
2775
2776 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2777 /// for tail call optimization. Targets which want to do tail call
2778 /// optimization should implement this function.
2779 bool
2780 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2781                                                      CallingConv::ID CalleeCC,
2782                                                      bool isVarArg,
2783                                                      bool isCalleeStructRet,
2784                                                      bool isCallerStructRet,
2785                                                      Type *RetTy,
2786                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2787                                     const SmallVectorImpl<SDValue> &OutVals,
2788                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2789                                                      SelectionDAG& DAG) const {
2790   if (!IsTailCallConvention(CalleeCC) &&
2791       CalleeCC != CallingConv::C)
2792     return false;
2793
2794   // If -tailcallopt is specified, make fastcc functions tail-callable.
2795   const MachineFunction &MF = DAG.getMachineFunction();
2796   const Function *CallerF = DAG.getMachineFunction().getFunction();
2797
2798   // If the function return type is x86_fp80 and the callee return type is not,
2799   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2800   // perform a tailcall optimization here.
2801   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2802     return false;
2803
2804   CallingConv::ID CallerCC = CallerF->getCallingConv();
2805   bool CCMatch = CallerCC == CalleeCC;
2806
2807   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2808     if (IsTailCallConvention(CalleeCC) && CCMatch)
2809       return true;
2810     return false;
2811   }
2812
2813   // Look for obvious safe cases to perform tail call optimization that do not
2814   // require ABI changes. This is what gcc calls sibcall.
2815
2816   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2817   // emit a special epilogue.
2818   if (RegInfo->needsStackRealignment(MF))
2819     return false;
2820
2821   // Also avoid sibcall optimization if either caller or callee uses struct
2822   // return semantics.
2823   if (isCalleeStructRet || isCallerStructRet)
2824     return false;
2825
2826   // An stdcall caller is expected to clean up its arguments; the callee
2827   // isn't going to do that.
2828   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2829     return false;
2830
2831   // Do not sibcall optimize vararg calls unless all arguments are passed via
2832   // registers.
2833   if (isVarArg && !Outs.empty()) {
2834
2835     // Optimizing for varargs on Win64 is unlikely to be safe without
2836     // additional testing.
2837     if (Subtarget->isTargetWin64())
2838       return false;
2839
2840     SmallVector<CCValAssign, 16> ArgLocs;
2841     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2842                    getTargetMachine(), ArgLocs, *DAG.getContext());
2843
2844     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2845     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2846       if (!ArgLocs[i].isRegLoc())
2847         return false;
2848   }
2849
2850   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2851   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2852   // this into a sibcall.
2853   bool Unused = false;
2854   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2855     if (!Ins[i].Used) {
2856       Unused = true;
2857       break;
2858     }
2859   }
2860   if (Unused) {
2861     SmallVector<CCValAssign, 16> RVLocs;
2862     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2863                    getTargetMachine(), RVLocs, *DAG.getContext());
2864     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2865     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2866       CCValAssign &VA = RVLocs[i];
2867       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2868         return false;
2869     }
2870   }
2871
2872   // If the calling conventions do not match, then we'd better make sure the
2873   // results are returned in the same way as what the caller expects.
2874   if (!CCMatch) {
2875     SmallVector<CCValAssign, 16> RVLocs1;
2876     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2877                     getTargetMachine(), RVLocs1, *DAG.getContext());
2878     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2879
2880     SmallVector<CCValAssign, 16> RVLocs2;
2881     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2882                     getTargetMachine(), RVLocs2, *DAG.getContext());
2883     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2884
2885     if (RVLocs1.size() != RVLocs2.size())
2886       return false;
2887     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2888       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2889         return false;
2890       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2891         return false;
2892       if (RVLocs1[i].isRegLoc()) {
2893         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2894           return false;
2895       } else {
2896         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2897           return false;
2898       }
2899     }
2900   }
2901
2902   // If the callee takes no arguments then go on to check the results of the
2903   // call.
2904   if (!Outs.empty()) {
2905     // Check if stack adjustment is needed. For now, do not do this if any
2906     // argument is passed on the stack.
2907     SmallVector<CCValAssign, 16> ArgLocs;
2908     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2909                    getTargetMachine(), ArgLocs, *DAG.getContext());
2910
2911     // Allocate shadow area for Win64
2912     if (Subtarget->isTargetWin64()) {
2913       CCInfo.AllocateStack(32, 8);
2914     }
2915
2916     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2917     if (CCInfo.getNextStackOffset()) {
2918       MachineFunction &MF = DAG.getMachineFunction();
2919       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2920         return false;
2921
2922       // Check if the arguments are already laid out in the right way as
2923       // the caller's fixed stack objects.
2924       MachineFrameInfo *MFI = MF.getFrameInfo();
2925       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2926       const X86InstrInfo *TII =
2927         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2928       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2929         CCValAssign &VA = ArgLocs[i];
2930         SDValue Arg = OutVals[i];
2931         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2932         if (VA.getLocInfo() == CCValAssign::Indirect)
2933           return false;
2934         if (!VA.isRegLoc()) {
2935           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2936                                    MFI, MRI, TII))
2937             return false;
2938         }
2939       }
2940     }
2941
2942     // If the tailcall address may be in a register, then make sure it's
2943     // possible to register allocate for it. In 32-bit, the call address can
2944     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2945     // callee-saved registers are restored. These happen to be the same
2946     // registers used to pass 'inreg' arguments so watch out for those.
2947     if (!Subtarget->is64Bit() &&
2948         !isa<GlobalAddressSDNode>(Callee) &&
2949         !isa<ExternalSymbolSDNode>(Callee)) {
2950       unsigned NumInRegs = 0;
2951       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2952         CCValAssign &VA = ArgLocs[i];
2953         if (!VA.isRegLoc())
2954           continue;
2955         unsigned Reg = VA.getLocReg();
2956         switch (Reg) {
2957         default: break;
2958         case X86::EAX: case X86::EDX: case X86::ECX:
2959           if (++NumInRegs == 3)
2960             return false;
2961           break;
2962         }
2963       }
2964     }
2965   }
2966
2967   return true;
2968 }
2969
2970 FastISel *
2971 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2972                                   const TargetLibraryInfo *libInfo) const {
2973   return X86::createFastISel(funcInfo, libInfo);
2974 }
2975
2976
2977 //===----------------------------------------------------------------------===//
2978 //                           Other Lowering Hooks
2979 //===----------------------------------------------------------------------===//
2980
2981 static bool MayFoldLoad(SDValue Op) {
2982   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2983 }
2984
2985 static bool MayFoldIntoStore(SDValue Op) {
2986   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2987 }
2988
2989 static bool isTargetShuffle(unsigned Opcode) {
2990   switch(Opcode) {
2991   default: return false;
2992   case X86ISD::PSHUFD:
2993   case X86ISD::PSHUFHW:
2994   case X86ISD::PSHUFLW:
2995   case X86ISD::SHUFP:
2996   case X86ISD::PALIGN:
2997   case X86ISD::MOVLHPS:
2998   case X86ISD::MOVLHPD:
2999   case X86ISD::MOVHLPS:
3000   case X86ISD::MOVLPS:
3001   case X86ISD::MOVLPD:
3002   case X86ISD::MOVSHDUP:
3003   case X86ISD::MOVSLDUP:
3004   case X86ISD::MOVDDUP:
3005   case X86ISD::MOVSS:
3006   case X86ISD::MOVSD:
3007   case X86ISD::UNPCKL:
3008   case X86ISD::UNPCKH:
3009   case X86ISD::VPERMILP:
3010   case X86ISD::VPERM2X128:
3011   case X86ISD::VPERMI:
3012     return true;
3013   }
3014 }
3015
3016 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3017                                     SDValue V1, SelectionDAG &DAG) {
3018   switch(Opc) {
3019   default: llvm_unreachable("Unknown x86 shuffle node");
3020   case X86ISD::MOVSHDUP:
3021   case X86ISD::MOVSLDUP:
3022   case X86ISD::MOVDDUP:
3023     return DAG.getNode(Opc, dl, VT, V1);
3024   }
3025 }
3026
3027 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3028                                     SDValue V1, unsigned TargetMask,
3029                                     SelectionDAG &DAG) {
3030   switch(Opc) {
3031   default: llvm_unreachable("Unknown x86 shuffle node");
3032   case X86ISD::PSHUFD:
3033   case X86ISD::PSHUFHW:
3034   case X86ISD::PSHUFLW:
3035   case X86ISD::VPERMILP:
3036   case X86ISD::VPERMI:
3037     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3038   }
3039 }
3040
3041 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3042                                     SDValue V1, SDValue V2, unsigned TargetMask,
3043                                     SelectionDAG &DAG) {
3044   switch(Opc) {
3045   default: llvm_unreachable("Unknown x86 shuffle node");
3046   case X86ISD::PALIGN:
3047   case X86ISD::SHUFP:
3048   case X86ISD::VPERM2X128:
3049     return DAG.getNode(Opc, dl, VT, V1, V2,
3050                        DAG.getConstant(TargetMask, MVT::i8));
3051   }
3052 }
3053
3054 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3055                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3056   switch(Opc) {
3057   default: llvm_unreachable("Unknown x86 shuffle node");
3058   case X86ISD::MOVLHPS:
3059   case X86ISD::MOVLHPD:
3060   case X86ISD::MOVHLPS:
3061   case X86ISD::MOVLPS:
3062   case X86ISD::MOVLPD:
3063   case X86ISD::MOVSS:
3064   case X86ISD::MOVSD:
3065   case X86ISD::UNPCKL:
3066   case X86ISD::UNPCKH:
3067     return DAG.getNode(Opc, dl, VT, V1, V2);
3068   }
3069 }
3070
3071 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3072   MachineFunction &MF = DAG.getMachineFunction();
3073   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3074   int ReturnAddrIndex = FuncInfo->getRAIndex();
3075
3076   if (ReturnAddrIndex == 0) {
3077     // Set up a frame object for the return address.
3078     unsigned SlotSize = RegInfo->getSlotSize();
3079     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3080                                                            false);
3081     FuncInfo->setRAIndex(ReturnAddrIndex);
3082   }
3083
3084   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3085 }
3086
3087
3088 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3089                                        bool hasSymbolicDisplacement) {
3090   // Offset should fit into 32 bit immediate field.
3091   if (!isInt<32>(Offset))
3092     return false;
3093
3094   // If we don't have a symbolic displacement - we don't have any extra
3095   // restrictions.
3096   if (!hasSymbolicDisplacement)
3097     return true;
3098
3099   // FIXME: Some tweaks might be needed for medium code model.
3100   if (M != CodeModel::Small && M != CodeModel::Kernel)
3101     return false;
3102
3103   // For small code model we assume that latest object is 16MB before end of 31
3104   // bits boundary. We may also accept pretty large negative constants knowing
3105   // that all objects are in the positive half of address space.
3106   if (M == CodeModel::Small && Offset < 16*1024*1024)
3107     return true;
3108
3109   // For kernel code model we know that all object resist in the negative half
3110   // of 32bits address space. We may not accept negative offsets, since they may
3111   // be just off and we may accept pretty large positive ones.
3112   if (M == CodeModel::Kernel && Offset > 0)
3113     return true;
3114
3115   return false;
3116 }
3117
3118 /// isCalleePop - Determines whether the callee is required to pop its
3119 /// own arguments. Callee pop is necessary to support tail calls.
3120 bool X86::isCalleePop(CallingConv::ID CallingConv,
3121                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3122   if (IsVarArg)
3123     return false;
3124
3125   switch (CallingConv) {
3126   default:
3127     return false;
3128   case CallingConv::X86_StdCall:
3129     return !is64Bit;
3130   case CallingConv::X86_FastCall:
3131     return !is64Bit;
3132   case CallingConv::X86_ThisCall:
3133     return !is64Bit;
3134   case CallingConv::Fast:
3135     return TailCallOpt;
3136   case CallingConv::GHC:
3137     return TailCallOpt;
3138   case CallingConv::HiPE:
3139     return TailCallOpt;
3140   }
3141 }
3142
3143 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3144 /// specific condition code, returning the condition code and the LHS/RHS of the
3145 /// comparison to make.
3146 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3147                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3148   if (!isFP) {
3149     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3150       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3151         // X > -1   -> X == 0, jump !sign.
3152         RHS = DAG.getConstant(0, RHS.getValueType());
3153         return X86::COND_NS;
3154       }
3155       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3156         // X < 0   -> X == 0, jump on sign.
3157         return X86::COND_S;
3158       }
3159       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3160         // X < 1   -> X <= 0
3161         RHS = DAG.getConstant(0, RHS.getValueType());
3162         return X86::COND_LE;
3163       }
3164     }
3165
3166     switch (SetCCOpcode) {
3167     default: llvm_unreachable("Invalid integer condition!");
3168     case ISD::SETEQ:  return X86::COND_E;
3169     case ISD::SETGT:  return X86::COND_G;
3170     case ISD::SETGE:  return X86::COND_GE;
3171     case ISD::SETLT:  return X86::COND_L;
3172     case ISD::SETLE:  return X86::COND_LE;
3173     case ISD::SETNE:  return X86::COND_NE;
3174     case ISD::SETULT: return X86::COND_B;
3175     case ISD::SETUGT: return X86::COND_A;
3176     case ISD::SETULE: return X86::COND_BE;
3177     case ISD::SETUGE: return X86::COND_AE;
3178     }
3179   }
3180
3181   // First determine if it is required or is profitable to flip the operands.
3182
3183   // If LHS is a foldable load, but RHS is not, flip the condition.
3184   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3185       !ISD::isNON_EXTLoad(RHS.getNode())) {
3186     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3187     std::swap(LHS, RHS);
3188   }
3189
3190   switch (SetCCOpcode) {
3191   default: break;
3192   case ISD::SETOLT:
3193   case ISD::SETOLE:
3194   case ISD::SETUGT:
3195   case ISD::SETUGE:
3196     std::swap(LHS, RHS);
3197     break;
3198   }
3199
3200   // On a floating point condition, the flags are set as follows:
3201   // ZF  PF  CF   op
3202   //  0 | 0 | 0 | X > Y
3203   //  0 | 0 | 1 | X < Y
3204   //  1 | 0 | 0 | X == Y
3205   //  1 | 1 | 1 | unordered
3206   switch (SetCCOpcode) {
3207   default: llvm_unreachable("Condcode should be pre-legalized away");
3208   case ISD::SETUEQ:
3209   case ISD::SETEQ:   return X86::COND_E;
3210   case ISD::SETOLT:              // flipped
3211   case ISD::SETOGT:
3212   case ISD::SETGT:   return X86::COND_A;
3213   case ISD::SETOLE:              // flipped
3214   case ISD::SETOGE:
3215   case ISD::SETGE:   return X86::COND_AE;
3216   case ISD::SETUGT:              // flipped
3217   case ISD::SETULT:
3218   case ISD::SETLT:   return X86::COND_B;
3219   case ISD::SETUGE:              // flipped
3220   case ISD::SETULE:
3221   case ISD::SETLE:   return X86::COND_BE;
3222   case ISD::SETONE:
3223   case ISD::SETNE:   return X86::COND_NE;
3224   case ISD::SETUO:   return X86::COND_P;
3225   case ISD::SETO:    return X86::COND_NP;
3226   case ISD::SETOEQ:
3227   case ISD::SETUNE:  return X86::COND_INVALID;
3228   }
3229 }
3230
3231 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3232 /// code. Current x86 isa includes the following FP cmov instructions:
3233 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3234 static bool hasFPCMov(unsigned X86CC) {
3235   switch (X86CC) {
3236   default:
3237     return false;
3238   case X86::COND_B:
3239   case X86::COND_BE:
3240   case X86::COND_E:
3241   case X86::COND_P:
3242   case X86::COND_A:
3243   case X86::COND_AE:
3244   case X86::COND_NE:
3245   case X86::COND_NP:
3246     return true;
3247   }
3248 }
3249
3250 /// isFPImmLegal - Returns true if the target can instruction select the
3251 /// specified FP immediate natively. If false, the legalizer will
3252 /// materialize the FP immediate as a load from a constant pool.
3253 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3254   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3255     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3256       return true;
3257   }
3258   return false;
3259 }
3260
3261 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3262 /// the specified range (L, H].
3263 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3264   return (Val < 0) || (Val >= Low && Val < Hi);
3265 }
3266
3267 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3268 /// specified value.
3269 static bool isUndefOrEqual(int Val, int CmpVal) {
3270   return (Val < 0 || Val == CmpVal);
3271 }
3272
3273 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3274 /// from position Pos and ending in Pos+Size, falls within the specified
3275 /// sequential range (L, L+Pos]. or is undef.
3276 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3277                                        unsigned Pos, unsigned Size, int Low) {
3278   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3279     if (!isUndefOrEqual(Mask[i], Low))
3280       return false;
3281   return true;
3282 }
3283
3284 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3285 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3286 /// the second operand.
3287 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3288   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3289     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3290   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3291     return (Mask[0] < 2 && Mask[1] < 2);
3292   return false;
3293 }
3294
3295 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3296 /// is suitable for input to PSHUFHW.
3297 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3298   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3299     return false;
3300
3301   // Lower quadword copied in order or undef.
3302   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3303     return false;
3304
3305   // Upper quadword shuffled.
3306   for (unsigned i = 4; i != 8; ++i)
3307     if (!isUndefOrInRange(Mask[i], 4, 8))
3308       return false;
3309
3310   if (VT == MVT::v16i16) {
3311     // Lower quadword copied in order or undef.
3312     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3313       return false;
3314
3315     // Upper quadword shuffled.
3316     for (unsigned i = 12; i != 16; ++i)
3317       if (!isUndefOrInRange(Mask[i], 12, 16))
3318         return false;
3319   }
3320
3321   return true;
3322 }
3323
3324 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3325 /// is suitable for input to PSHUFLW.
3326 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3327   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3328     return false;
3329
3330   // Upper quadword copied in order.
3331   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3332     return false;
3333
3334   // Lower quadword shuffled.
3335   for (unsigned i = 0; i != 4; ++i)
3336     if (!isUndefOrInRange(Mask[i], 0, 4))
3337       return false;
3338
3339   if (VT == MVT::v16i16) {
3340     // Upper quadword copied in order.
3341     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3342       return false;
3343
3344     // Lower quadword shuffled.
3345     for (unsigned i = 8; i != 12; ++i)
3346       if (!isUndefOrInRange(Mask[i], 8, 12))
3347         return false;
3348   }
3349
3350   return true;
3351 }
3352
3353 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3354 /// is suitable for input to PALIGNR.
3355 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3356                           const X86Subtarget *Subtarget) {
3357   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3358       (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3359     return false;
3360
3361   unsigned NumElts = VT.getVectorNumElements();
3362   unsigned NumLanes = VT.getSizeInBits()/128;
3363   unsigned NumLaneElts = NumElts/NumLanes;
3364
3365   // Do not handle 64-bit element shuffles with palignr.
3366   if (NumLaneElts == 2)
3367     return false;
3368
3369   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3370     unsigned i;
3371     for (i = 0; i != NumLaneElts; ++i) {
3372       if (Mask[i+l] >= 0)
3373         break;
3374     }
3375
3376     // Lane is all undef, go to next lane
3377     if (i == NumLaneElts)
3378       continue;
3379
3380     int Start = Mask[i+l];
3381
3382     // Make sure its in this lane in one of the sources
3383     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3384         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3385       return false;
3386
3387     // If not lane 0, then we must match lane 0
3388     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3389       return false;
3390
3391     // Correct second source to be contiguous with first source
3392     if (Start >= (int)NumElts)
3393       Start -= NumElts - NumLaneElts;
3394
3395     // Make sure we're shifting in the right direction.
3396     if (Start <= (int)(i+l))
3397       return false;
3398
3399     Start -= i;
3400
3401     // Check the rest of the elements to see if they are consecutive.
3402     for (++i; i != NumLaneElts; ++i) {
3403       int Idx = Mask[i+l];
3404
3405       // Make sure its in this lane
3406       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3407           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3408         return false;
3409
3410       // If not lane 0, then we must match lane 0
3411       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3412         return false;
3413
3414       if (Idx >= (int)NumElts)
3415         Idx -= NumElts - NumLaneElts;
3416
3417       if (!isUndefOrEqual(Idx, Start+i))
3418         return false;
3419
3420     }
3421   }
3422
3423   return true;
3424 }
3425
3426 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3427 /// the two vector operands have swapped position.
3428 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3429                                      unsigned NumElems) {
3430   for (unsigned i = 0; i != NumElems; ++i) {
3431     int idx = Mask[i];
3432     if (idx < 0)
3433       continue;
3434     else if (idx < (int)NumElems)
3435       Mask[i] = idx + NumElems;
3436     else
3437       Mask[i] = idx - NumElems;
3438   }
3439 }
3440
3441 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3442 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3443 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3444 /// reverse of what x86 shuffles want.
3445 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3446                         bool Commuted = false) {
3447   if (!HasFp256 && VT.getSizeInBits() == 256)
3448     return false;
3449
3450   unsigned NumElems = VT.getVectorNumElements();
3451   unsigned NumLanes = VT.getSizeInBits()/128;
3452   unsigned NumLaneElems = NumElems/NumLanes;
3453
3454   if (NumLaneElems != 2 && NumLaneElems != 4)
3455     return false;
3456
3457   // VSHUFPSY divides the resulting vector into 4 chunks.
3458   // The sources are also splitted into 4 chunks, and each destination
3459   // chunk must come from a different source chunk.
3460   //
3461   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3462   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3463   //
3464   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3465   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3466   //
3467   // VSHUFPDY divides the resulting vector into 4 chunks.
3468   // The sources are also splitted into 4 chunks, and each destination
3469   // chunk must come from a different source chunk.
3470   //
3471   //  SRC1 =>      X3       X2       X1       X0
3472   //  SRC2 =>      Y3       Y2       Y1       Y0
3473   //
3474   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3475   //
3476   unsigned HalfLaneElems = NumLaneElems/2;
3477   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3478     for (unsigned i = 0; i != NumLaneElems; ++i) {
3479       int Idx = Mask[i+l];
3480       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3481       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3482         return false;
3483       // For VSHUFPSY, the mask of the second half must be the same as the
3484       // first but with the appropriate offsets. This works in the same way as
3485       // VPERMILPS works with masks.
3486       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3487         continue;
3488       if (!isUndefOrEqual(Idx, Mask[i]+l))
3489         return false;
3490     }
3491   }
3492
3493   return true;
3494 }
3495
3496 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3498 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3499   if (!VT.is128BitVector())
3500     return false;
3501
3502   unsigned NumElems = VT.getVectorNumElements();
3503
3504   if (NumElems != 4)
3505     return false;
3506
3507   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3508   return isUndefOrEqual(Mask[0], 6) &&
3509          isUndefOrEqual(Mask[1], 7) &&
3510          isUndefOrEqual(Mask[2], 2) &&
3511          isUndefOrEqual(Mask[3], 3);
3512 }
3513
3514 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3515 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3516 /// <2, 3, 2, 3>
3517 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3518   if (!VT.is128BitVector())
3519     return false;
3520
3521   unsigned NumElems = VT.getVectorNumElements();
3522
3523   if (NumElems != 4)
3524     return false;
3525
3526   return isUndefOrEqual(Mask[0], 2) &&
3527          isUndefOrEqual(Mask[1], 3) &&
3528          isUndefOrEqual(Mask[2], 2) &&
3529          isUndefOrEqual(Mask[3], 3);
3530 }
3531
3532 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3533 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3534 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3535   if (!VT.is128BitVector())
3536     return false;
3537
3538   unsigned NumElems = VT.getVectorNumElements();
3539
3540   if (NumElems != 2 && NumElems != 4)
3541     return false;
3542
3543   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3544     if (!isUndefOrEqual(Mask[i], i + NumElems))
3545       return false;
3546
3547   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3548     if (!isUndefOrEqual(Mask[i], i))
3549       return false;
3550
3551   return true;
3552 }
3553
3554 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3555 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3556 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3557   if (!VT.is128BitVector())
3558     return false;
3559
3560   unsigned NumElems = VT.getVectorNumElements();
3561
3562   if (NumElems != 2 && NumElems != 4)
3563     return false;
3564
3565   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3566     if (!isUndefOrEqual(Mask[i], i))
3567       return false;
3568
3569   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3570     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3571       return false;
3572
3573   return true;
3574 }
3575
3576 //
3577 // Some special combinations that can be optimized.
3578 //
3579 static
3580 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3581                                SelectionDAG &DAG) {
3582   EVT VT = SVOp->getValueType(0);
3583   DebugLoc dl = SVOp->getDebugLoc();
3584
3585   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3586     return SDValue();
3587
3588   ArrayRef<int> Mask = SVOp->getMask();
3589
3590   // These are the special masks that may be optimized.
3591   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3592   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3593   bool MatchEvenMask = true;
3594   bool MatchOddMask  = true;
3595   for (int i=0; i<8; ++i) {
3596     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3597       MatchEvenMask = false;
3598     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3599       MatchOddMask = false;
3600   }
3601
3602   if (!MatchEvenMask && !MatchOddMask)
3603     return SDValue();
3604
3605   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3606
3607   SDValue Op0 = SVOp->getOperand(0);
3608   SDValue Op1 = SVOp->getOperand(1);
3609
3610   if (MatchEvenMask) {
3611     // Shift the second operand right to 32 bits.
3612     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3613     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3614   } else {
3615     // Shift the first operand left to 32 bits.
3616     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3617     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3618   }
3619   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3620   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3621 }
3622
3623 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3624 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3625 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3626                          bool HasInt256, bool V2IsSplat = false) {
3627   unsigned NumElts = VT.getVectorNumElements();
3628
3629   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3630          "Unsupported vector type for unpckh");
3631
3632   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3633       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3634     return false;
3635
3636   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3637   // independently on 128-bit lanes.
3638   unsigned NumLanes = VT.getSizeInBits()/128;
3639   unsigned NumLaneElts = NumElts/NumLanes;
3640
3641   for (unsigned l = 0; l != NumLanes; ++l) {
3642     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3643          i != (l+1)*NumLaneElts;
3644          i += 2, ++j) {
3645       int BitI  = Mask[i];
3646       int BitI1 = Mask[i+1];
3647       if (!isUndefOrEqual(BitI, j))
3648         return false;
3649       if (V2IsSplat) {
3650         if (!isUndefOrEqual(BitI1, NumElts))
3651           return false;
3652       } else {
3653         if (!isUndefOrEqual(BitI1, j + NumElts))
3654           return false;
3655       }
3656     }
3657   }
3658
3659   return true;
3660 }
3661
3662 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3663 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3664 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3665                          bool HasInt256, bool V2IsSplat = false) {
3666   unsigned NumElts = VT.getVectorNumElements();
3667
3668   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3669          "Unsupported vector type for unpckh");
3670
3671   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3672       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3673     return false;
3674
3675   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3676   // independently on 128-bit lanes.
3677   unsigned NumLanes = VT.getSizeInBits()/128;
3678   unsigned NumLaneElts = NumElts/NumLanes;
3679
3680   for (unsigned l = 0; l != NumLanes; ++l) {
3681     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3682          i != (l+1)*NumLaneElts; i += 2, ++j) {
3683       int BitI  = Mask[i];
3684       int BitI1 = Mask[i+1];
3685       if (!isUndefOrEqual(BitI, j))
3686         return false;
3687       if (V2IsSplat) {
3688         if (isUndefOrEqual(BitI1, NumElts))
3689           return false;
3690       } else {
3691         if (!isUndefOrEqual(BitI1, j+NumElts))
3692           return false;
3693       }
3694     }
3695   }
3696   return true;
3697 }
3698
3699 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3700 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3701 /// <0, 0, 1, 1>
3702 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3703                                   bool HasInt256) {
3704   unsigned NumElts = VT.getVectorNumElements();
3705
3706   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3707          "Unsupported vector type for unpckh");
3708
3709   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3710       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3711     return false;
3712
3713   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3714   // FIXME: Need a better way to get rid of this, there's no latency difference
3715   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3716   // the former later. We should also remove the "_undef" special mask.
3717   if (NumElts == 4 && VT.getSizeInBits() == 256)
3718     return false;
3719
3720   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3721   // independently on 128-bit lanes.
3722   unsigned NumLanes = VT.getSizeInBits()/128;
3723   unsigned NumLaneElts = NumElts/NumLanes;
3724
3725   for (unsigned l = 0; l != NumLanes; ++l) {
3726     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3727          i != (l+1)*NumLaneElts;
3728          i += 2, ++j) {
3729       int BitI  = Mask[i];
3730       int BitI1 = Mask[i+1];
3731
3732       if (!isUndefOrEqual(BitI, j))
3733         return false;
3734       if (!isUndefOrEqual(BitI1, j))
3735         return false;
3736     }
3737   }
3738
3739   return true;
3740 }
3741
3742 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3743 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3744 /// <2, 2, 3, 3>
3745 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3746   unsigned NumElts = VT.getVectorNumElements();
3747
3748   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3749          "Unsupported vector type for unpckh");
3750
3751   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3752       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3753     return false;
3754
3755   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3756   // independently on 128-bit lanes.
3757   unsigned NumLanes = VT.getSizeInBits()/128;
3758   unsigned NumLaneElts = NumElts/NumLanes;
3759
3760   for (unsigned l = 0; l != NumLanes; ++l) {
3761     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3762          i != (l+1)*NumLaneElts; i += 2, ++j) {
3763       int BitI  = Mask[i];
3764       int BitI1 = Mask[i+1];
3765       if (!isUndefOrEqual(BitI, j))
3766         return false;
3767       if (!isUndefOrEqual(BitI1, j))
3768         return false;
3769     }
3770   }
3771   return true;
3772 }
3773
3774 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3775 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3776 /// MOVSD, and MOVD, i.e. setting the lowest element.
3777 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3778   if (VT.getVectorElementType().getSizeInBits() < 32)
3779     return false;
3780   if (!VT.is128BitVector())
3781     return false;
3782
3783   unsigned NumElts = VT.getVectorNumElements();
3784
3785   if (!isUndefOrEqual(Mask[0], NumElts))
3786     return false;
3787
3788   for (unsigned i = 1; i != NumElts; ++i)
3789     if (!isUndefOrEqual(Mask[i], i))
3790       return false;
3791
3792   return true;
3793 }
3794
3795 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3796 /// as permutations between 128-bit chunks or halves. As an example: this
3797 /// shuffle bellow:
3798 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3799 /// The first half comes from the second half of V1 and the second half from the
3800 /// the second half of V2.
3801 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3802   if (!HasFp256 || !VT.is256BitVector())
3803     return false;
3804
3805   // The shuffle result is divided into half A and half B. In total the two
3806   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3807   // B must come from C, D, E or F.
3808   unsigned HalfSize = VT.getVectorNumElements()/2;
3809   bool MatchA = false, MatchB = false;
3810
3811   // Check if A comes from one of C, D, E, F.
3812   for (unsigned Half = 0; Half != 4; ++Half) {
3813     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3814       MatchA = true;
3815       break;
3816     }
3817   }
3818
3819   // Check if B comes from one of C, D, E, F.
3820   for (unsigned Half = 0; Half != 4; ++Half) {
3821     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3822       MatchB = true;
3823       break;
3824     }
3825   }
3826
3827   return MatchA && MatchB;
3828 }
3829
3830 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3831 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3832 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3833   EVT VT = SVOp->getValueType(0);
3834
3835   unsigned HalfSize = VT.getVectorNumElements()/2;
3836
3837   unsigned FstHalf = 0, SndHalf = 0;
3838   for (unsigned i = 0; i < HalfSize; ++i) {
3839     if (SVOp->getMaskElt(i) > 0) {
3840       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3841       break;
3842     }
3843   }
3844   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3845     if (SVOp->getMaskElt(i) > 0) {
3846       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3847       break;
3848     }
3849   }
3850
3851   return (FstHalf | (SndHalf << 4));
3852 }
3853
3854 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3856 /// Note that VPERMIL mask matching is different depending whether theunderlying
3857 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3858 /// to the same elements of the low, but to the higher half of the source.
3859 /// In VPERMILPD the two lanes could be shuffled independently of each other
3860 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3861 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3862   if (!HasFp256)
3863     return false;
3864
3865   unsigned NumElts = VT.getVectorNumElements();
3866   // Only match 256-bit with 32/64-bit types
3867   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3868     return false;
3869
3870   unsigned NumLanes = VT.getSizeInBits()/128;
3871   unsigned LaneSize = NumElts/NumLanes;
3872   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3873     for (unsigned i = 0; i != LaneSize; ++i) {
3874       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3875         return false;
3876       if (NumElts != 8 || l == 0)
3877         continue;
3878       // VPERMILPS handling
3879       if (Mask[i] < 0)
3880         continue;
3881       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3882         return false;
3883     }
3884   }
3885
3886   return true;
3887 }
3888
3889 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3890 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3891 /// element of vector 2 and the other elements to come from vector 1 in order.
3892 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3893                                bool V2IsSplat = false, bool V2IsUndef = false) {
3894   if (!VT.is128BitVector())
3895     return false;
3896
3897   unsigned NumOps = VT.getVectorNumElements();
3898   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3899     return false;
3900
3901   if (!isUndefOrEqual(Mask[0], 0))
3902     return false;
3903
3904   for (unsigned i = 1; i != NumOps; ++i)
3905     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3906           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3907           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3908       return false;
3909
3910   return true;
3911 }
3912
3913 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3915 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3916 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3917                            const X86Subtarget *Subtarget) {
3918   if (!Subtarget->hasSSE3())
3919     return false;
3920
3921   unsigned NumElems = VT.getVectorNumElements();
3922
3923   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3924       (VT.getSizeInBits() == 256 && NumElems != 8))
3925     return false;
3926
3927   // "i+1" is the value the indexed mask element must have
3928   for (unsigned i = 0; i != NumElems; i += 2)
3929     if (!isUndefOrEqual(Mask[i], i+1) ||
3930         !isUndefOrEqual(Mask[i+1], i+1))
3931       return false;
3932
3933   return true;
3934 }
3935
3936 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3938 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3939 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3940                            const X86Subtarget *Subtarget) {
3941   if (!Subtarget->hasSSE3())
3942     return false;
3943
3944   unsigned NumElems = VT.getVectorNumElements();
3945
3946   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3947       (VT.getSizeInBits() == 256 && NumElems != 8))
3948     return false;
3949
3950   // "i" is the value the indexed mask element must have
3951   for (unsigned i = 0; i != NumElems; i += 2)
3952     if (!isUndefOrEqual(Mask[i], i) ||
3953         !isUndefOrEqual(Mask[i+1], i))
3954       return false;
3955
3956   return true;
3957 }
3958
3959 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to 256-bit
3961 /// version of MOVDDUP.
3962 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3963   if (!HasFp256 || !VT.is256BitVector())
3964     return false;
3965
3966   unsigned NumElts = VT.getVectorNumElements();
3967   if (NumElts != 4)
3968     return false;
3969
3970   for (unsigned i = 0; i != NumElts/2; ++i)
3971     if (!isUndefOrEqual(Mask[i], 0))
3972       return false;
3973   for (unsigned i = NumElts/2; i != NumElts; ++i)
3974     if (!isUndefOrEqual(Mask[i], NumElts/2))
3975       return false;
3976   return true;
3977 }
3978
3979 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3980 /// specifies a shuffle of elements that is suitable for input to 128-bit
3981 /// version of MOVDDUP.
3982 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3983   if (!VT.is128BitVector())
3984     return false;
3985
3986   unsigned e = VT.getVectorNumElements() / 2;
3987   for (unsigned i = 0; i != e; ++i)
3988     if (!isUndefOrEqual(Mask[i], i))
3989       return false;
3990   for (unsigned i = 0; i != e; ++i)
3991     if (!isUndefOrEqual(Mask[e+i], i))
3992       return false;
3993   return true;
3994 }
3995
3996 /// isVEXTRACTF128Index - Return true if the specified
3997 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3998 /// suitable for input to VEXTRACTF128.
3999 bool X86::isVEXTRACTF128Index(SDNode *N) {
4000   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4001     return false;
4002
4003   // The index should be aligned on a 128-bit boundary.
4004   uint64_t Index =
4005     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4006
4007   unsigned VL = N->getValueType(0).getVectorNumElements();
4008   unsigned VBits = N->getValueType(0).getSizeInBits();
4009   unsigned ElSize = VBits / VL;
4010   bool Result = (Index * ElSize) % 128 == 0;
4011
4012   return Result;
4013 }
4014
4015 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4016 /// operand specifies a subvector insert that is suitable for input to
4017 /// VINSERTF128.
4018 bool X86::isVINSERTF128Index(SDNode *N) {
4019   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4020     return false;
4021
4022   // The index should be aligned on a 128-bit boundary.
4023   uint64_t Index =
4024     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4025
4026   unsigned VL = N->getValueType(0).getVectorNumElements();
4027   unsigned VBits = N->getValueType(0).getSizeInBits();
4028   unsigned ElSize = VBits / VL;
4029   bool Result = (Index * ElSize) % 128 == 0;
4030
4031   return Result;
4032 }
4033
4034 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4035 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4036 /// Handles 128-bit and 256-bit.
4037 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4038   EVT VT = N->getValueType(0);
4039
4040   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4041          "Unsupported vector type for PSHUF/SHUFP");
4042
4043   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4044   // independently on 128-bit lanes.
4045   unsigned NumElts = VT.getVectorNumElements();
4046   unsigned NumLanes = VT.getSizeInBits()/128;
4047   unsigned NumLaneElts = NumElts/NumLanes;
4048
4049   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4050          "Only supports 2 or 4 elements per lane");
4051
4052   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4053   unsigned Mask = 0;
4054   for (unsigned i = 0; i != NumElts; ++i) {
4055     int Elt = N->getMaskElt(i);
4056     if (Elt < 0) continue;
4057     Elt &= NumLaneElts - 1;
4058     unsigned ShAmt = (i << Shift) % 8;
4059     Mask |= Elt << ShAmt;
4060   }
4061
4062   return Mask;
4063 }
4064
4065 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4067 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4068   EVT VT = N->getValueType(0);
4069
4070   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4071          "Unsupported vector type for PSHUFHW");
4072
4073   unsigned NumElts = VT.getVectorNumElements();
4074
4075   unsigned Mask = 0;
4076   for (unsigned l = 0; l != NumElts; l += 8) {
4077     // 8 nodes per lane, but we only care about the last 4.
4078     for (unsigned i = 0; i < 4; ++i) {
4079       int Elt = N->getMaskElt(l+i+4);
4080       if (Elt < 0) continue;
4081       Elt &= 0x3; // only 2-bits.
4082       Mask |= Elt << (i * 2);
4083     }
4084   }
4085
4086   return Mask;
4087 }
4088
4089 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4090 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4091 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4092   EVT VT = N->getValueType(0);
4093
4094   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4095          "Unsupported vector type for PSHUFHW");
4096
4097   unsigned NumElts = VT.getVectorNumElements();
4098
4099   unsigned Mask = 0;
4100   for (unsigned l = 0; l != NumElts; l += 8) {
4101     // 8 nodes per lane, but we only care about the first 4.
4102     for (unsigned i = 0; i < 4; ++i) {
4103       int Elt = N->getMaskElt(l+i);
4104       if (Elt < 0) continue;
4105       Elt &= 0x3; // only 2-bits
4106       Mask |= Elt << (i * 2);
4107     }
4108   }
4109
4110   return Mask;
4111 }
4112
4113 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4115 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4116   EVT VT = SVOp->getValueType(0);
4117   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4118
4119   unsigned NumElts = VT.getVectorNumElements();
4120   unsigned NumLanes = VT.getSizeInBits()/128;
4121   unsigned NumLaneElts = NumElts/NumLanes;
4122
4123   int Val = 0;
4124   unsigned i;
4125   for (i = 0; i != NumElts; ++i) {
4126     Val = SVOp->getMaskElt(i);
4127     if (Val >= 0)
4128       break;
4129   }
4130   if (Val >= (int)NumElts)
4131     Val -= NumElts - NumLaneElts;
4132
4133   assert(Val - i > 0 && "PALIGNR imm should be positive");
4134   return (Val - i) * EltSize;
4135 }
4136
4137 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4138 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4139 /// instructions.
4140 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4141   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4142     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4143
4144   uint64_t Index =
4145     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4146
4147   EVT VecVT = N->getOperand(0).getValueType();
4148   EVT ElVT = VecVT.getVectorElementType();
4149
4150   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4151   return Index / NumElemsPerChunk;
4152 }
4153
4154 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4155 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4156 /// instructions.
4157 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4158   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4159     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4160
4161   uint64_t Index =
4162     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4163
4164   EVT VecVT = N->getValueType(0);
4165   EVT ElVT = VecVT.getVectorElementType();
4166
4167   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4168   return Index / NumElemsPerChunk;
4169 }
4170
4171 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4172 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4173 /// Handles 256-bit.
4174 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4175   EVT VT = N->getValueType(0);
4176
4177   unsigned NumElts = VT.getVectorNumElements();
4178
4179   assert((VT.is256BitVector() && NumElts == 4) &&
4180          "Unsupported vector type for VPERMQ/VPERMPD");
4181
4182   unsigned Mask = 0;
4183   for (unsigned i = 0; i != NumElts; ++i) {
4184     int Elt = N->getMaskElt(i);
4185     if (Elt < 0)
4186       continue;
4187     Mask |= Elt << (i*2);
4188   }
4189
4190   return Mask;
4191 }
4192 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4193 /// constant +0.0.
4194 bool X86::isZeroNode(SDValue Elt) {
4195   return ((isa<ConstantSDNode>(Elt) &&
4196            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4197           (isa<ConstantFPSDNode>(Elt) &&
4198            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4199 }
4200
4201 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4202 /// their permute mask.
4203 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4204                                     SelectionDAG &DAG) {
4205   EVT VT = SVOp->getValueType(0);
4206   unsigned NumElems = VT.getVectorNumElements();
4207   SmallVector<int, 8> MaskVec;
4208
4209   for (unsigned i = 0; i != NumElems; ++i) {
4210     int Idx = SVOp->getMaskElt(i);
4211     if (Idx >= 0) {
4212       if (Idx < (int)NumElems)
4213         Idx += NumElems;
4214       else
4215         Idx -= NumElems;
4216     }
4217     MaskVec.push_back(Idx);
4218   }
4219   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4220                               SVOp->getOperand(0), &MaskVec[0]);
4221 }
4222
4223 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4224 /// match movhlps. The lower half elements should come from upper half of
4225 /// V1 (and in order), and the upper half elements should come from the upper
4226 /// half of V2 (and in order).
4227 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4228   if (!VT.is128BitVector())
4229     return false;
4230   if (VT.getVectorNumElements() != 4)
4231     return false;
4232   for (unsigned i = 0, e = 2; i != e; ++i)
4233     if (!isUndefOrEqual(Mask[i], i+2))
4234       return false;
4235   for (unsigned i = 2; i != 4; ++i)
4236     if (!isUndefOrEqual(Mask[i], i+4))
4237       return false;
4238   return true;
4239 }
4240
4241 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4242 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4243 /// required.
4244 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4245   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4246     return false;
4247   N = N->getOperand(0).getNode();
4248   if (!ISD::isNON_EXTLoad(N))
4249     return false;
4250   if (LD)
4251     *LD = cast<LoadSDNode>(N);
4252   return true;
4253 }
4254
4255 // Test whether the given value is a vector value which will be legalized
4256 // into a load.
4257 static bool WillBeConstantPoolLoad(SDNode *N) {
4258   if (N->getOpcode() != ISD::BUILD_VECTOR)
4259     return false;
4260
4261   // Check for any non-constant elements.
4262   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4263     switch (N->getOperand(i).getNode()->getOpcode()) {
4264     case ISD::UNDEF:
4265     case ISD::ConstantFP:
4266     case ISD::Constant:
4267       break;
4268     default:
4269       return false;
4270     }
4271
4272   // Vectors of all-zeros and all-ones are materialized with special
4273   // instructions rather than being loaded.
4274   return !ISD::isBuildVectorAllZeros(N) &&
4275          !ISD::isBuildVectorAllOnes(N);
4276 }
4277
4278 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4279 /// match movlp{s|d}. The lower half elements should come from lower half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order). And since V1 will become the source of the
4282 /// MOVLP, it must be either a vector load or a scalar load to vector.
4283 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4284                                ArrayRef<int> Mask, EVT VT) {
4285   if (!VT.is128BitVector())
4286     return false;
4287
4288   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4289     return false;
4290   // Is V2 is a vector load, don't do this transformation. We will try to use
4291   // load folding shufps op.
4292   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4293     return false;
4294
4295   unsigned NumElems = VT.getVectorNumElements();
4296
4297   if (NumElems != 2 && NumElems != 4)
4298     return false;
4299   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4300     if (!isUndefOrEqual(Mask[i], i))
4301       return false;
4302   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4303     if (!isUndefOrEqual(Mask[i], i+NumElems))
4304       return false;
4305   return true;
4306 }
4307
4308 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4309 /// all the same.
4310 static bool isSplatVector(SDNode *N) {
4311   if (N->getOpcode() != ISD::BUILD_VECTOR)
4312     return false;
4313
4314   SDValue SplatValue = N->getOperand(0);
4315   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4316     if (N->getOperand(i) != SplatValue)
4317       return false;
4318   return true;
4319 }
4320
4321 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4322 /// to an zero vector.
4323 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4324 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4325   SDValue V1 = N->getOperand(0);
4326   SDValue V2 = N->getOperand(1);
4327   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4328   for (unsigned i = 0; i != NumElems; ++i) {
4329     int Idx = N->getMaskElt(i);
4330     if (Idx >= (int)NumElems) {
4331       unsigned Opc = V2.getOpcode();
4332       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4333         continue;
4334       if (Opc != ISD::BUILD_VECTOR ||
4335           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4336         return false;
4337     } else if (Idx >= 0) {
4338       unsigned Opc = V1.getOpcode();
4339       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4340         continue;
4341       if (Opc != ISD::BUILD_VECTOR ||
4342           !X86::isZeroNode(V1.getOperand(Idx)))
4343         return false;
4344     }
4345   }
4346   return true;
4347 }
4348
4349 /// getZeroVector - Returns a vector of specified type with all zero elements.
4350 ///
4351 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4352                              SelectionDAG &DAG, DebugLoc dl) {
4353   assert(VT.isVector() && "Expected a vector type");
4354   unsigned Size = VT.getSizeInBits();
4355
4356   // Always build SSE zero vectors as <4 x i32> bitcasted
4357   // to their dest type. This ensures they get CSE'd.
4358   SDValue Vec;
4359   if (Size == 128) {  // SSE
4360     if (Subtarget->hasSSE2()) {  // SSE2
4361       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4363     } else { // SSE1
4364       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4365       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4366     }
4367   } else if (Size == 256) { // AVX
4368     if (Subtarget->hasInt256()) { // AVX2
4369       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4370       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4371       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4372     } else {
4373       // 256-bit logic and arithmetic instructions in AVX are all
4374       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4375       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4376       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4377       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4378     }
4379   } else
4380     llvm_unreachable("Unexpected vector type");
4381
4382   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4383 }
4384
4385 /// getOnesVector - Returns a vector of specified type with all bits set.
4386 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4387 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4388 /// Then bitcast to their original type, ensuring they get CSE'd.
4389 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4390                              DebugLoc dl) {
4391   assert(VT.isVector() && "Expected a vector type");
4392   unsigned Size = VT.getSizeInBits();
4393
4394   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4395   SDValue Vec;
4396   if (Size == 256) {
4397     if (HasInt256) { // AVX2
4398       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4399       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4400     } else { // AVX
4401       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4403     }
4404   } else if (Size == 128) {
4405     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4406   } else
4407     llvm_unreachable("Unexpected vector type");
4408
4409   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4410 }
4411
4412 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4413 /// that point to V2 points to its first element.
4414 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4415   for (unsigned i = 0; i != NumElems; ++i) {
4416     if (Mask[i] > (int)NumElems) {
4417       Mask[i] = NumElems;
4418     }
4419   }
4420 }
4421
4422 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4423 /// operation of specified width.
4424 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4425                        SDValue V2) {
4426   unsigned NumElems = VT.getVectorNumElements();
4427   SmallVector<int, 8> Mask;
4428   Mask.push_back(NumElems);
4429   for (unsigned i = 1; i != NumElems; ++i)
4430     Mask.push_back(i);
4431   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4432 }
4433
4434 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4435 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4436                           SDValue V2) {
4437   unsigned NumElems = VT.getVectorNumElements();
4438   SmallVector<int, 8> Mask;
4439   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4440     Mask.push_back(i);
4441     Mask.push_back(i + NumElems);
4442   }
4443   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4444 }
4445
4446 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4447 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4448                           SDValue V2) {
4449   unsigned NumElems = VT.getVectorNumElements();
4450   SmallVector<int, 8> Mask;
4451   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4452     Mask.push_back(i + Half);
4453     Mask.push_back(i + NumElems + Half);
4454   }
4455   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4456 }
4457
4458 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4459 // a generic shuffle instruction because the target has no such instructions.
4460 // Generate shuffles which repeat i16 and i8 several times until they can be
4461 // represented by v4f32 and then be manipulated by target suported shuffles.
4462 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4463   EVT VT = V.getValueType();
4464   int NumElems = VT.getVectorNumElements();
4465   DebugLoc dl = V.getDebugLoc();
4466
4467   while (NumElems > 4) {
4468     if (EltNo < NumElems/2) {
4469       V = getUnpackl(DAG, dl, VT, V, V);
4470     } else {
4471       V = getUnpackh(DAG, dl, VT, V, V);
4472       EltNo -= NumElems/2;
4473     }
4474     NumElems >>= 1;
4475   }
4476   return V;
4477 }
4478
4479 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4480 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4481   EVT VT = V.getValueType();
4482   DebugLoc dl = V.getDebugLoc();
4483   unsigned Size = VT.getSizeInBits();
4484
4485   if (Size == 128) {
4486     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4487     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4488     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4489                              &SplatMask[0]);
4490   } else if (Size == 256) {
4491     // To use VPERMILPS to splat scalars, the second half of indicies must
4492     // refer to the higher part, which is a duplication of the lower one,
4493     // because VPERMILPS can only handle in-lane permutations.
4494     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4495                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4496
4497     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4498     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4499                              &SplatMask[0]);
4500   } else
4501     llvm_unreachable("Vector size not supported");
4502
4503   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4504 }
4505
4506 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4507 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4508   EVT SrcVT = SV->getValueType(0);
4509   SDValue V1 = SV->getOperand(0);
4510   DebugLoc dl = SV->getDebugLoc();
4511
4512   int EltNo = SV->getSplatIndex();
4513   int NumElems = SrcVT.getVectorNumElements();
4514   unsigned Size = SrcVT.getSizeInBits();
4515
4516   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4517           "Unknown how to promote splat for type");
4518
4519   // Extract the 128-bit part containing the splat element and update
4520   // the splat element index when it refers to the higher register.
4521   if (Size == 256) {
4522     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4523     if (EltNo >= NumElems/2)
4524       EltNo -= NumElems/2;
4525   }
4526
4527   // All i16 and i8 vector types can't be used directly by a generic shuffle
4528   // instruction because the target has no such instruction. Generate shuffles
4529   // which repeat i16 and i8 several times until they fit in i32, and then can
4530   // be manipulated by target suported shuffles.
4531   EVT EltVT = SrcVT.getVectorElementType();
4532   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4533     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4534
4535   // Recreate the 256-bit vector and place the same 128-bit vector
4536   // into the low and high part. This is necessary because we want
4537   // to use VPERM* to shuffle the vectors
4538   if (Size == 256) {
4539     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4540   }
4541
4542   return getLegalSplat(DAG, V1, EltNo);
4543 }
4544
4545 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4546 /// vector of zero or undef vector.  This produces a shuffle where the low
4547 /// element of V2 is swizzled into the zero/undef vector, landing at element
4548 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4549 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4550                                            bool IsZero,
4551                                            const X86Subtarget *Subtarget,
4552                                            SelectionDAG &DAG) {
4553   EVT VT = V2.getValueType();
4554   SDValue V1 = IsZero
4555     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4556   unsigned NumElems = VT.getVectorNumElements();
4557   SmallVector<int, 16> MaskVec;
4558   for (unsigned i = 0; i != NumElems; ++i)
4559     // If this is the insertion idx, put the low elt of V2 here.
4560     MaskVec.push_back(i == Idx ? NumElems : i);
4561   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4562 }
4563
4564 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4565 /// target specific opcode. Returns true if the Mask could be calculated.
4566 /// Sets IsUnary to true if only uses one source.
4567 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4568                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4569   unsigned NumElems = VT.getVectorNumElements();
4570   SDValue ImmN;
4571
4572   IsUnary = false;
4573   switch(N->getOpcode()) {
4574   case X86ISD::SHUFP:
4575     ImmN = N->getOperand(N->getNumOperands()-1);
4576     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577     break;
4578   case X86ISD::UNPCKH:
4579     DecodeUNPCKHMask(VT, Mask);
4580     break;
4581   case X86ISD::UNPCKL:
4582     DecodeUNPCKLMask(VT, Mask);
4583     break;
4584   case X86ISD::MOVHLPS:
4585     DecodeMOVHLPSMask(NumElems, Mask);
4586     break;
4587   case X86ISD::MOVLHPS:
4588     DecodeMOVLHPSMask(NumElems, Mask);
4589     break;
4590   case X86ISD::PSHUFD:
4591   case X86ISD::VPERMILP:
4592     ImmN = N->getOperand(N->getNumOperands()-1);
4593     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4594     IsUnary = true;
4595     break;
4596   case X86ISD::PSHUFHW:
4597     ImmN = N->getOperand(N->getNumOperands()-1);
4598     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4599     IsUnary = true;
4600     break;
4601   case X86ISD::PSHUFLW:
4602     ImmN = N->getOperand(N->getNumOperands()-1);
4603     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4604     IsUnary = true;
4605     break;
4606   case X86ISD::VPERMI:
4607     ImmN = N->getOperand(N->getNumOperands()-1);
4608     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4609     IsUnary = true;
4610     break;
4611   case X86ISD::MOVSS:
4612   case X86ISD::MOVSD: {
4613     // The index 0 always comes from the first element of the second source,
4614     // this is why MOVSS and MOVSD are used in the first place. The other
4615     // elements come from the other positions of the first source vector
4616     Mask.push_back(NumElems);
4617     for (unsigned i = 1; i != NumElems; ++i) {
4618       Mask.push_back(i);
4619     }
4620     break;
4621   }
4622   case X86ISD::VPERM2X128:
4623     ImmN = N->getOperand(N->getNumOperands()-1);
4624     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4625     if (Mask.empty()) return false;
4626     break;
4627   case X86ISD::MOVDDUP:
4628   case X86ISD::MOVLHPD:
4629   case X86ISD::MOVLPD:
4630   case X86ISD::MOVLPS:
4631   case X86ISD::MOVSHDUP:
4632   case X86ISD::MOVSLDUP:
4633   case X86ISD::PALIGN:
4634     // Not yet implemented
4635     return false;
4636   default: llvm_unreachable("unknown target shuffle node");
4637   }
4638
4639   return true;
4640 }
4641
4642 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4643 /// element of the result of the vector shuffle.
4644 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4645                                    unsigned Depth) {
4646   if (Depth == 6)
4647     return SDValue();  // Limit search depth.
4648
4649   SDValue V = SDValue(N, 0);
4650   EVT VT = V.getValueType();
4651   unsigned Opcode = V.getOpcode();
4652
4653   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4654   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4655     int Elt = SV->getMaskElt(Index);
4656
4657     if (Elt < 0)
4658       return DAG.getUNDEF(VT.getVectorElementType());
4659
4660     unsigned NumElems = VT.getVectorNumElements();
4661     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4662                                          : SV->getOperand(1);
4663     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4664   }
4665
4666   // Recurse into target specific vector shuffles to find scalars.
4667   if (isTargetShuffle(Opcode)) {
4668     MVT ShufVT = V.getValueType().getSimpleVT();
4669     unsigned NumElems = ShufVT.getVectorNumElements();
4670     SmallVector<int, 16> ShuffleMask;
4671     bool IsUnary;
4672
4673     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4674       return SDValue();
4675
4676     int Elt = ShuffleMask[Index];
4677     if (Elt < 0)
4678       return DAG.getUNDEF(ShufVT.getVectorElementType());
4679
4680     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4681                                          : N->getOperand(1);
4682     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4683                                Depth+1);
4684   }
4685
4686   // Actual nodes that may contain scalar elements
4687   if (Opcode == ISD::BITCAST) {
4688     V = V.getOperand(0);
4689     EVT SrcVT = V.getValueType();
4690     unsigned NumElems = VT.getVectorNumElements();
4691
4692     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4693       return SDValue();
4694   }
4695
4696   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4697     return (Index == 0) ? V.getOperand(0)
4698                         : DAG.getUNDEF(VT.getVectorElementType());
4699
4700   if (V.getOpcode() == ISD::BUILD_VECTOR)
4701     return V.getOperand(Index);
4702
4703   return SDValue();
4704 }
4705
4706 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4707 /// shuffle operation which come from a consecutively from a zero. The
4708 /// search can start in two different directions, from left or right.
4709 static
4710 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4711                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4712   unsigned i;
4713   for (i = 0; i != NumElems; ++i) {
4714     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4715     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4716     if (!(Elt.getNode() &&
4717          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4718       break;
4719   }
4720
4721   return i;
4722 }
4723
4724 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4725 /// correspond consecutively to elements from one of the vector operands,
4726 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4727 static
4728 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4729                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4730                               unsigned NumElems, unsigned &OpNum) {
4731   bool SeenV1 = false;
4732   bool SeenV2 = false;
4733
4734   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4735     int Idx = SVOp->getMaskElt(i);
4736     // Ignore undef indicies
4737     if (Idx < 0)
4738       continue;
4739
4740     if (Idx < (int)NumElems)
4741       SeenV1 = true;
4742     else
4743       SeenV2 = true;
4744
4745     // Only accept consecutive elements from the same vector
4746     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4747       return false;
4748   }
4749
4750   OpNum = SeenV1 ? 0 : 1;
4751   return true;
4752 }
4753
4754 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4755 /// logical left shift of a vector.
4756 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4757                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4758   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4759   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4760               false /* check zeros from right */, DAG);
4761   unsigned OpSrc;
4762
4763   if (!NumZeros)
4764     return false;
4765
4766   // Considering the elements in the mask that are not consecutive zeros,
4767   // check if they consecutively come from only one of the source vectors.
4768   //
4769   //               V1 = {X, A, B, C}     0
4770   //                         \  \  \    /
4771   //   vector_shuffle V1, V2 <1, 2, 3, X>
4772   //
4773   if (!isShuffleMaskConsecutive(SVOp,
4774             0,                   // Mask Start Index
4775             NumElems-NumZeros,   // Mask End Index(exclusive)
4776             NumZeros,            // Where to start looking in the src vector
4777             NumElems,            // Number of elements in vector
4778             OpSrc))              // Which source operand ?
4779     return false;
4780
4781   isLeft = false;
4782   ShAmt = NumZeros;
4783   ShVal = SVOp->getOperand(OpSrc);
4784   return true;
4785 }
4786
4787 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4788 /// logical left shift of a vector.
4789 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4790                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4791   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4792   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4793               true /* check zeros from left */, DAG);
4794   unsigned OpSrc;
4795
4796   if (!NumZeros)
4797     return false;
4798
4799   // Considering the elements in the mask that are not consecutive zeros,
4800   // check if they consecutively come from only one of the source vectors.
4801   //
4802   //                           0    { A, B, X, X } = V2
4803   //                          / \    /  /
4804   //   vector_shuffle V1, V2 <X, X, 4, 5>
4805   //
4806   if (!isShuffleMaskConsecutive(SVOp,
4807             NumZeros,     // Mask Start Index
4808             NumElems,     // Mask End Index(exclusive)
4809             0,            // Where to start looking in the src vector
4810             NumElems,     // Number of elements in vector
4811             OpSrc))       // Which source operand ?
4812     return false;
4813
4814   isLeft = true;
4815   ShAmt = NumZeros;
4816   ShVal = SVOp->getOperand(OpSrc);
4817   return true;
4818 }
4819
4820 /// isVectorShift - Returns true if the shuffle can be implemented as a
4821 /// logical left or right shift of a vector.
4822 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4823                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4824   // Although the logic below support any bitwidth size, there are no
4825   // shift instructions which handle more than 128-bit vectors.
4826   if (!SVOp->getValueType(0).is128BitVector())
4827     return false;
4828
4829   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4830       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4831     return true;
4832
4833   return false;
4834 }
4835
4836 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4837 ///
4838 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4839                                        unsigned NumNonZero, unsigned NumZero,
4840                                        SelectionDAG &DAG,
4841                                        const X86Subtarget* Subtarget,
4842                                        const TargetLowering &TLI) {
4843   if (NumNonZero > 8)
4844     return SDValue();
4845
4846   DebugLoc dl = Op.getDebugLoc();
4847   SDValue V(0, 0);
4848   bool First = true;
4849   for (unsigned i = 0; i < 16; ++i) {
4850     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4851     if (ThisIsNonZero && First) {
4852       if (NumZero)
4853         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4854       else
4855         V = DAG.getUNDEF(MVT::v8i16);
4856       First = false;
4857     }
4858
4859     if ((i & 1) != 0) {
4860       SDValue ThisElt(0, 0), LastElt(0, 0);
4861       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4862       if (LastIsNonZero) {
4863         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4864                               MVT::i16, Op.getOperand(i-1));
4865       }
4866       if (ThisIsNonZero) {
4867         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4868         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4869                               ThisElt, DAG.getConstant(8, MVT::i8));
4870         if (LastIsNonZero)
4871           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4872       } else
4873         ThisElt = LastElt;
4874
4875       if (ThisElt.getNode())
4876         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4877                         DAG.getIntPtrConstant(i/2));
4878     }
4879   }
4880
4881   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4882 }
4883
4884 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4885 ///
4886 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4887                                      unsigned NumNonZero, unsigned NumZero,
4888                                      SelectionDAG &DAG,
4889                                      const X86Subtarget* Subtarget,
4890                                      const TargetLowering &TLI) {
4891   if (NumNonZero > 4)
4892     return SDValue();
4893
4894   DebugLoc dl = Op.getDebugLoc();
4895   SDValue V(0, 0);
4896   bool First = true;
4897   for (unsigned i = 0; i < 8; ++i) {
4898     bool isNonZero = (NonZeros & (1 << i)) != 0;
4899     if (isNonZero) {
4900       if (First) {
4901         if (NumZero)
4902           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4903         else
4904           V = DAG.getUNDEF(MVT::v8i16);
4905         First = false;
4906       }
4907       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4908                       MVT::v8i16, V, Op.getOperand(i),
4909                       DAG.getIntPtrConstant(i));
4910     }
4911   }
4912
4913   return V;
4914 }
4915
4916 /// getVShift - Return a vector logical shift node.
4917 ///
4918 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4919                          unsigned NumBits, SelectionDAG &DAG,
4920                          const TargetLowering &TLI, DebugLoc dl) {
4921   assert(VT.is128BitVector() && "Unknown type for VShift");
4922   EVT ShVT = MVT::v2i64;
4923   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4924   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4925   return DAG.getNode(ISD::BITCAST, dl, VT,
4926                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4927                              DAG.getConstant(NumBits,
4928                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4929 }
4930
4931 SDValue
4932 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4933                                           SelectionDAG &DAG) const {
4934
4935   // Check if the scalar load can be widened into a vector load. And if
4936   // the address is "base + cst" see if the cst can be "absorbed" into
4937   // the shuffle mask.
4938   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4939     SDValue Ptr = LD->getBasePtr();
4940     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4941       return SDValue();
4942     EVT PVT = LD->getValueType(0);
4943     if (PVT != MVT::i32 && PVT != MVT::f32)
4944       return SDValue();
4945
4946     int FI = -1;
4947     int64_t Offset = 0;
4948     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4949       FI = FINode->getIndex();
4950       Offset = 0;
4951     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4952                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4953       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4954       Offset = Ptr.getConstantOperandVal(1);
4955       Ptr = Ptr.getOperand(0);
4956     } else {
4957       return SDValue();
4958     }
4959
4960     // FIXME: 256-bit vector instructions don't require a strict alignment,
4961     // improve this code to support it better.
4962     unsigned RequiredAlign = VT.getSizeInBits()/8;
4963     SDValue Chain = LD->getChain();
4964     // Make sure the stack object alignment is at least 16 or 32.
4965     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4966     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4967       if (MFI->isFixedObjectIndex(FI)) {
4968         // Can't change the alignment. FIXME: It's possible to compute
4969         // the exact stack offset and reference FI + adjust offset instead.
4970         // If someone *really* cares about this. That's the way to implement it.
4971         return SDValue();
4972       } else {
4973         MFI->setObjectAlignment(FI, RequiredAlign);
4974       }
4975     }
4976
4977     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4978     // Ptr + (Offset & ~15).
4979     if (Offset < 0)
4980       return SDValue();
4981     if ((Offset % RequiredAlign) & 3)
4982       return SDValue();
4983     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4984     if (StartOffset)
4985       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4986                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4987
4988     int EltNo = (Offset - StartOffset) >> 2;
4989     unsigned NumElems = VT.getVectorNumElements();
4990
4991     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4992     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4993                              LD->getPointerInfo().getWithOffset(StartOffset),
4994                              false, false, false, 0);
4995
4996     SmallVector<int, 8> Mask;
4997     for (unsigned i = 0; i != NumElems; ++i)
4998       Mask.push_back(EltNo);
4999
5000     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5001   }
5002
5003   return SDValue();
5004 }
5005
5006 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5007 /// vector of type 'VT', see if the elements can be replaced by a single large
5008 /// load which has the same value as a build_vector whose operands are 'elts'.
5009 ///
5010 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5011 ///
5012 /// FIXME: we'd also like to handle the case where the last elements are zero
5013 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5014 /// There's even a handy isZeroNode for that purpose.
5015 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5016                                         DebugLoc &DL, SelectionDAG &DAG) {
5017   EVT EltVT = VT.getVectorElementType();
5018   unsigned NumElems = Elts.size();
5019
5020   LoadSDNode *LDBase = NULL;
5021   unsigned LastLoadedElt = -1U;
5022
5023   // For each element in the initializer, see if we've found a load or an undef.
5024   // If we don't find an initial load element, or later load elements are
5025   // non-consecutive, bail out.
5026   for (unsigned i = 0; i < NumElems; ++i) {
5027     SDValue Elt = Elts[i];
5028
5029     if (!Elt.getNode() ||
5030         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5031       return SDValue();
5032     if (!LDBase) {
5033       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5034         return SDValue();
5035       LDBase = cast<LoadSDNode>(Elt.getNode());
5036       LastLoadedElt = i;
5037       continue;
5038     }
5039     if (Elt.getOpcode() == ISD::UNDEF)
5040       continue;
5041
5042     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5043     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5044       return SDValue();
5045     LastLoadedElt = i;
5046   }
5047
5048   // If we have found an entire vector of loads and undefs, then return a large
5049   // load of the entire vector width starting at the base pointer.  If we found
5050   // consecutive loads for the low half, generate a vzext_load node.
5051   if (LastLoadedElt == NumElems - 1) {
5052     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5053       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5054                          LDBase->getPointerInfo(),
5055                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5056                          LDBase->isInvariant(), 0);
5057     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5058                        LDBase->getPointerInfo(),
5059                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5060                        LDBase->isInvariant(), LDBase->getAlignment());
5061   }
5062   if (NumElems == 4 && LastLoadedElt == 1 &&
5063       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5064     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5065     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5066     SDValue ResNode =
5067         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5068                                 LDBase->getPointerInfo(),
5069                                 LDBase->getAlignment(),
5070                                 false/*isVolatile*/, true/*ReadMem*/,
5071                                 false/*WriteMem*/);
5072
5073     // Make sure the newly-created LOAD is in the same position as LDBase in
5074     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5075     // update uses of LDBase's output chain to use the TokenFactor.
5076     if (LDBase->hasAnyUseOfValue(1)) {
5077       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5078                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5079       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5080       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5081                              SDValue(ResNode.getNode(), 1));
5082     }
5083
5084     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5085   }
5086   return SDValue();
5087 }
5088
5089 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5090 /// to generate a splat value for the following cases:
5091 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5092 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5093 /// a scalar load, or a constant.
5094 /// The VBROADCAST node is returned when a pattern is found,
5095 /// or SDValue() otherwise.
5096 SDValue
5097 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5098   if (!Subtarget->hasFp256())
5099     return SDValue();
5100
5101   EVT VT = Op.getValueType();
5102   DebugLoc dl = Op.getDebugLoc();
5103
5104   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5105          "Unsupported vector type for broadcast.");
5106
5107   SDValue Ld;
5108   bool ConstSplatVal;
5109
5110   switch (Op.getOpcode()) {
5111     default:
5112       // Unknown pattern found.
5113       return SDValue();
5114
5115     case ISD::BUILD_VECTOR: {
5116       // The BUILD_VECTOR node must be a splat.
5117       if (!isSplatVector(Op.getNode()))
5118         return SDValue();
5119
5120       Ld = Op.getOperand(0);
5121       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5122                      Ld.getOpcode() == ISD::ConstantFP);
5123
5124       // The suspected load node has several users. Make sure that all
5125       // of its users are from the BUILD_VECTOR node.
5126       // Constants may have multiple users.
5127       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5128         return SDValue();
5129       break;
5130     }
5131
5132     case ISD::VECTOR_SHUFFLE: {
5133       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5134
5135       // Shuffles must have a splat mask where the first element is
5136       // broadcasted.
5137       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5138         return SDValue();
5139
5140       SDValue Sc = Op.getOperand(0);
5141       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5142           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5143
5144         if (!Subtarget->hasInt256())
5145           return SDValue();
5146
5147         // Use the register form of the broadcast instruction available on AVX2.
5148         if (VT.is256BitVector())
5149           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5150         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5151       }
5152
5153       Ld = Sc.getOperand(0);
5154       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5155                        Ld.getOpcode() == ISD::ConstantFP);
5156
5157       // The scalar_to_vector node and the suspected
5158       // load node must have exactly one user.
5159       // Constants may have multiple users.
5160       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5161         return SDValue();
5162       break;
5163     }
5164   }
5165
5166   bool Is256 = VT.is256BitVector();
5167
5168   // Handle the broadcasting a single constant scalar from the constant pool
5169   // into a vector. On Sandybridge it is still better to load a constant vector
5170   // from the constant pool and not to broadcast it from a scalar.
5171   if (ConstSplatVal && Subtarget->hasInt256()) {
5172     EVT CVT = Ld.getValueType();
5173     assert(!CVT.isVector() && "Must not broadcast a vector type");
5174     unsigned ScalarSize = CVT.getSizeInBits();
5175
5176     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5177       const Constant *C = 0;
5178       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5179         C = CI->getConstantIntValue();
5180       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5181         C = CF->getConstantFPValue();
5182
5183       assert(C && "Invalid constant type");
5184
5185       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5186       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5187       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5188                        MachinePointerInfo::getConstantPool(),
5189                        false, false, false, Alignment);
5190
5191       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5192     }
5193   }
5194
5195   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5196   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5197
5198   // Handle AVX2 in-register broadcasts.
5199   if (!IsLoad && Subtarget->hasInt256() &&
5200       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5201     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5202
5203   // The scalar source must be a normal load.
5204   if (!IsLoad)
5205     return SDValue();
5206
5207   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5208     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5209
5210   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5211   // double since there is no vbroadcastsd xmm
5212   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5213     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5214       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5215   }
5216
5217   // Unsupported broadcast.
5218   return SDValue();
5219 }
5220
5221 SDValue
5222 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5223   EVT VT = Op.getValueType();
5224
5225   // Skip if insert_vec_elt is not supported.
5226   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5227     return SDValue();
5228
5229   DebugLoc DL = Op.getDebugLoc();
5230   unsigned NumElems = Op.getNumOperands();
5231
5232   SDValue VecIn1;
5233   SDValue VecIn2;
5234   SmallVector<unsigned, 4> InsertIndices;
5235   SmallVector<int, 8> Mask(NumElems, -1);
5236
5237   for (unsigned i = 0; i != NumElems; ++i) {
5238     unsigned Opc = Op.getOperand(i).getOpcode();
5239
5240     if (Opc == ISD::UNDEF)
5241       continue;
5242
5243     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5244       // Quit if more than 1 elements need inserting.
5245       if (InsertIndices.size() > 1)
5246         return SDValue();
5247
5248       InsertIndices.push_back(i);
5249       continue;
5250     }
5251
5252     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5253     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5254
5255     // Quit if extracted from vector of different type.
5256     if (ExtractedFromVec.getValueType() != VT)
5257       return SDValue();
5258
5259     // Quit if non-constant index.
5260     if (!isa<ConstantSDNode>(ExtIdx))
5261       return SDValue();
5262
5263     if (VecIn1.getNode() == 0)
5264       VecIn1 = ExtractedFromVec;
5265     else if (VecIn1 != ExtractedFromVec) {
5266       if (VecIn2.getNode() == 0)
5267         VecIn2 = ExtractedFromVec;
5268       else if (VecIn2 != ExtractedFromVec)
5269         // Quit if more than 2 vectors to shuffle
5270         return SDValue();
5271     }
5272
5273     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5274
5275     if (ExtractedFromVec == VecIn1)
5276       Mask[i] = Idx;
5277     else if (ExtractedFromVec == VecIn2)
5278       Mask[i] = Idx + NumElems;
5279   }
5280
5281   if (VecIn1.getNode() == 0)
5282     return SDValue();
5283
5284   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5285   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5286   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5287     unsigned Idx = InsertIndices[i];
5288     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5289                      DAG.getIntPtrConstant(Idx));
5290   }
5291
5292   return NV;
5293 }
5294
5295 SDValue
5296 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5297   DebugLoc dl = Op.getDebugLoc();
5298
5299   EVT VT = Op.getValueType();
5300   EVT ExtVT = VT.getVectorElementType();
5301   unsigned NumElems = Op.getNumOperands();
5302
5303   // Vectors containing all zeros can be matched by pxor and xorps later
5304   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5305     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5306     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5307     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5308       return Op;
5309
5310     return getZeroVector(VT, Subtarget, DAG, dl);
5311   }
5312
5313   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5314   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5315   // vpcmpeqd on 256-bit vectors.
5316   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5317     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5318       return Op;
5319
5320     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5321   }
5322
5323   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5324   if (Broadcast.getNode())
5325     return Broadcast;
5326
5327   unsigned EVTBits = ExtVT.getSizeInBits();
5328
5329   unsigned NumZero  = 0;
5330   unsigned NumNonZero = 0;
5331   unsigned NonZeros = 0;
5332   bool IsAllConstants = true;
5333   SmallSet<SDValue, 8> Values;
5334   for (unsigned i = 0; i < NumElems; ++i) {
5335     SDValue Elt = Op.getOperand(i);
5336     if (Elt.getOpcode() == ISD::UNDEF)
5337       continue;
5338     Values.insert(Elt);
5339     if (Elt.getOpcode() != ISD::Constant &&
5340         Elt.getOpcode() != ISD::ConstantFP)
5341       IsAllConstants = false;
5342     if (X86::isZeroNode(Elt))
5343       NumZero++;
5344     else {
5345       NonZeros |= (1 << i);
5346       NumNonZero++;
5347     }
5348   }
5349
5350   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5351   if (NumNonZero == 0)
5352     return DAG.getUNDEF(VT);
5353
5354   // Special case for single non-zero, non-undef, element.
5355   if (NumNonZero == 1) {
5356     unsigned Idx = CountTrailingZeros_32(NonZeros);
5357     SDValue Item = Op.getOperand(Idx);
5358
5359     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5360     // the value are obviously zero, truncate the value to i32 and do the
5361     // insertion that way.  Only do this if the value is non-constant or if the
5362     // value is a constant being inserted into element 0.  It is cheaper to do
5363     // a constant pool load than it is to do a movd + shuffle.
5364     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5365         (!IsAllConstants || Idx == 0)) {
5366       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5367         // Handle SSE only.
5368         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5369         EVT VecVT = MVT::v4i32;
5370         unsigned VecElts = 4;
5371
5372         // Truncate the value (which may itself be a constant) to i32, and
5373         // convert it to a vector with movd (S2V+shuffle to zero extend).
5374         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5375         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5376         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5377
5378         // Now we have our 32-bit value zero extended in the low element of
5379         // a vector.  If Idx != 0, swizzle it into place.
5380         if (Idx != 0) {
5381           SmallVector<int, 4> Mask;
5382           Mask.push_back(Idx);
5383           for (unsigned i = 1; i != VecElts; ++i)
5384             Mask.push_back(i);
5385           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5386                                       &Mask[0]);
5387         }
5388         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5389       }
5390     }
5391
5392     // If we have a constant or non-constant insertion into the low element of
5393     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5394     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5395     // depending on what the source datatype is.
5396     if (Idx == 0) {
5397       if (NumZero == 0)
5398         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5399
5400       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5401           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5402         if (VT.is256BitVector()) {
5403           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5404           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5405                              Item, DAG.getIntPtrConstant(0));
5406         }
5407         assert(VT.is128BitVector() && "Expected an SSE value type!");
5408         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5409         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5410         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5411       }
5412
5413       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5414         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5415         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5416         if (VT.is256BitVector()) {
5417           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5418           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5419         } else {
5420           assert(VT.is128BitVector() && "Expected an SSE value type!");
5421           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5422         }
5423         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5424       }
5425     }
5426
5427     // Is it a vector logical left shift?
5428     if (NumElems == 2 && Idx == 1 &&
5429         X86::isZeroNode(Op.getOperand(0)) &&
5430         !X86::isZeroNode(Op.getOperand(1))) {
5431       unsigned NumBits = VT.getSizeInBits();
5432       return getVShift(true, VT,
5433                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5434                                    VT, Op.getOperand(1)),
5435                        NumBits/2, DAG, *this, dl);
5436     }
5437
5438     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5439       return SDValue();
5440
5441     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5442     // is a non-constant being inserted into an element other than the low one,
5443     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5444     // movd/movss) to move this into the low element, then shuffle it into
5445     // place.
5446     if (EVTBits == 32) {
5447       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5448
5449       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5450       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5451       SmallVector<int, 8> MaskVec;
5452       for (unsigned i = 0; i != NumElems; ++i)
5453         MaskVec.push_back(i == Idx ? 0 : 1);
5454       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5455     }
5456   }
5457
5458   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5459   if (Values.size() == 1) {
5460     if (EVTBits == 32) {
5461       // Instead of a shuffle like this:
5462       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5463       // Check if it's possible to issue this instead.
5464       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5465       unsigned Idx = CountTrailingZeros_32(NonZeros);
5466       SDValue Item = Op.getOperand(Idx);
5467       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5468         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5469     }
5470     return SDValue();
5471   }
5472
5473   // A vector full of immediates; various special cases are already
5474   // handled, so this is best done with a single constant-pool load.
5475   if (IsAllConstants)
5476     return SDValue();
5477
5478   // For AVX-length vectors, build the individual 128-bit pieces and use
5479   // shuffles to put them in place.
5480   if (VT.is256BitVector()) {
5481     SmallVector<SDValue, 32> V;
5482     for (unsigned i = 0; i != NumElems; ++i)
5483       V.push_back(Op.getOperand(i));
5484
5485     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5486
5487     // Build both the lower and upper subvector.
5488     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5489     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5490                                 NumElems/2);
5491
5492     // Recreate the wider vector with the lower and upper part.
5493     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5494   }
5495
5496   // Let legalizer expand 2-wide build_vectors.
5497   if (EVTBits == 64) {
5498     if (NumNonZero == 1) {
5499       // One half is zero or undef.
5500       unsigned Idx = CountTrailingZeros_32(NonZeros);
5501       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5502                                  Op.getOperand(Idx));
5503       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5504     }
5505     return SDValue();
5506   }
5507
5508   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5509   if (EVTBits == 8 && NumElems == 16) {
5510     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5511                                         Subtarget, *this);
5512     if (V.getNode()) return V;
5513   }
5514
5515   if (EVTBits == 16 && NumElems == 8) {
5516     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5517                                       Subtarget, *this);
5518     if (V.getNode()) return V;
5519   }
5520
5521   // If element VT is == 32 bits, turn it into a number of shuffles.
5522   SmallVector<SDValue, 8> V(NumElems);
5523   if (NumElems == 4 && NumZero > 0) {
5524     for (unsigned i = 0; i < 4; ++i) {
5525       bool isZero = !(NonZeros & (1 << i));
5526       if (isZero)
5527         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5528       else
5529         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5530     }
5531
5532     for (unsigned i = 0; i < 2; ++i) {
5533       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5534         default: break;
5535         case 0:
5536           V[i] = V[i*2];  // Must be a zero vector.
5537           break;
5538         case 1:
5539           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5540           break;
5541         case 2:
5542           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5543           break;
5544         case 3:
5545           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5546           break;
5547       }
5548     }
5549
5550     bool Reverse1 = (NonZeros & 0x3) == 2;
5551     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5552     int MaskVec[] = {
5553       Reverse1 ? 1 : 0,
5554       Reverse1 ? 0 : 1,
5555       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5556       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5557     };
5558     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5559   }
5560
5561   if (Values.size() > 1 && VT.is128BitVector()) {
5562     // Check for a build vector of consecutive loads.
5563     for (unsigned i = 0; i < NumElems; ++i)
5564       V[i] = Op.getOperand(i);
5565
5566     // Check for elements which are consecutive loads.
5567     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5568     if (LD.getNode())
5569       return LD;
5570
5571     // Check for a build vector from mostly shuffle plus few inserting.
5572     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5573     if (Sh.getNode())
5574       return Sh;
5575
5576     // For SSE 4.1, use insertps to put the high elements into the low element.
5577     if (getSubtarget()->hasSSE41()) {
5578       SDValue Result;
5579       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5580         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5581       else
5582         Result = DAG.getUNDEF(VT);
5583
5584       for (unsigned i = 1; i < NumElems; ++i) {
5585         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5586         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5587                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5588       }
5589       return Result;
5590     }
5591
5592     // Otherwise, expand into a number of unpckl*, start by extending each of
5593     // our (non-undef) elements to the full vector width with the element in the
5594     // bottom slot of the vector (which generates no code for SSE).
5595     for (unsigned i = 0; i < NumElems; ++i) {
5596       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5597         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5598       else
5599         V[i] = DAG.getUNDEF(VT);
5600     }
5601
5602     // Next, we iteratively mix elements, e.g. for v4f32:
5603     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5604     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5605     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5606     unsigned EltStride = NumElems >> 1;
5607     while (EltStride != 0) {
5608       for (unsigned i = 0; i < EltStride; ++i) {
5609         // If V[i+EltStride] is undef and this is the first round of mixing,
5610         // then it is safe to just drop this shuffle: V[i] is already in the
5611         // right place, the one element (since it's the first round) being
5612         // inserted as undef can be dropped.  This isn't safe for successive
5613         // rounds because they will permute elements within both vectors.
5614         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5615             EltStride == NumElems/2)
5616           continue;
5617
5618         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5619       }
5620       EltStride >>= 1;
5621     }
5622     return V[0];
5623   }
5624   return SDValue();
5625 }
5626
5627 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5628 // to create 256-bit vectors from two other 128-bit ones.
5629 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5630   DebugLoc dl = Op.getDebugLoc();
5631   EVT ResVT = Op.getValueType();
5632
5633   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5634
5635   SDValue V1 = Op.getOperand(0);
5636   SDValue V2 = Op.getOperand(1);
5637   unsigned NumElems = ResVT.getVectorNumElements();
5638
5639   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5640 }
5641
5642 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5643   assert(Op.getNumOperands() == 2);
5644
5645   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5646   // from two other 128-bit ones.
5647   return LowerAVXCONCAT_VECTORS(Op, DAG);
5648 }
5649
5650 // Try to lower a shuffle node into a simple blend instruction.
5651 static SDValue
5652 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5653                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5654   SDValue V1 = SVOp->getOperand(0);
5655   SDValue V2 = SVOp->getOperand(1);
5656   DebugLoc dl = SVOp->getDebugLoc();
5657   EVT VT = SVOp->getValueType(0);
5658   EVT EltVT = VT.getVectorElementType();
5659   unsigned NumElems = VT.getVectorNumElements();
5660
5661   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5662     return SDValue();
5663   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5664     return SDValue();
5665
5666   // Check the mask for BLEND and build the value.
5667   unsigned MaskValue = 0;
5668   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5669   unsigned NumLanes = (NumElems-1)/8 + 1; 
5670   unsigned NumElemsInLane = NumElems / NumLanes;
5671
5672   // Blend for v16i16 should be symetric for the both lanes.
5673   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5674
5675     int SndLaneEltIdx = (NumLanes == 2) ? 
5676       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5677     int EltIdx = SVOp->getMaskElt(i);
5678
5679     if ((EltIdx == -1 || EltIdx == (int)i) && 
5680         (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5681       continue;
5682
5683     if (((unsigned)EltIdx == (i + NumElems)) && 
5684         (SndLaneEltIdx == -1 || 
5685          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5686       MaskValue |= (1<<i);
5687     else 
5688       return SDValue();
5689   }
5690
5691   // Convert i32 vectors to floating point if it is not AVX2.
5692   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5693   EVT BlendVT = VT;
5694   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5695     BlendVT = EVT::getVectorVT(*DAG.getContext(), 
5696                               EVT::getFloatingPointVT(EltVT.getSizeInBits()), 
5697                               NumElems);
5698     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5699     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5700   }
5701   
5702   SDValue Ret =  DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5703                              DAG.getConstant(MaskValue, MVT::i32));
5704   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5705 }
5706
5707 // v8i16 shuffles - Prefer shuffles in the following order:
5708 // 1. [all]   pshuflw, pshufhw, optional move
5709 // 2. [ssse3] 1 x pshufb
5710 // 3. [ssse3] 2 x pshufb + 1 x por
5711 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5712 static SDValue
5713 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5714                          SelectionDAG &DAG) {
5715   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5716   SDValue V1 = SVOp->getOperand(0);
5717   SDValue V2 = SVOp->getOperand(1);
5718   DebugLoc dl = SVOp->getDebugLoc();
5719   SmallVector<int, 8> MaskVals;
5720
5721   // Determine if more than 1 of the words in each of the low and high quadwords
5722   // of the result come from the same quadword of one of the two inputs.  Undef
5723   // mask values count as coming from any quadword, for better codegen.
5724   unsigned LoQuad[] = { 0, 0, 0, 0 };
5725   unsigned HiQuad[] = { 0, 0, 0, 0 };
5726   std::bitset<4> InputQuads;
5727   for (unsigned i = 0; i < 8; ++i) {
5728     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5729     int EltIdx = SVOp->getMaskElt(i);
5730     MaskVals.push_back(EltIdx);
5731     if (EltIdx < 0) {
5732       ++Quad[0];
5733       ++Quad[1];
5734       ++Quad[2];
5735       ++Quad[3];
5736       continue;
5737     }
5738     ++Quad[EltIdx / 4];
5739     InputQuads.set(EltIdx / 4);
5740   }
5741
5742   int BestLoQuad = -1;
5743   unsigned MaxQuad = 1;
5744   for (unsigned i = 0; i < 4; ++i) {
5745     if (LoQuad[i] > MaxQuad) {
5746       BestLoQuad = i;
5747       MaxQuad = LoQuad[i];
5748     }
5749   }
5750
5751   int BestHiQuad = -1;
5752   MaxQuad = 1;
5753   for (unsigned i = 0; i < 4; ++i) {
5754     if (HiQuad[i] > MaxQuad) {
5755       BestHiQuad = i;
5756       MaxQuad = HiQuad[i];
5757     }
5758   }
5759
5760   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5761   // of the two input vectors, shuffle them into one input vector so only a
5762   // single pshufb instruction is necessary. If There are more than 2 input
5763   // quads, disable the next transformation since it does not help SSSE3.
5764   bool V1Used = InputQuads[0] || InputQuads[1];
5765   bool V2Used = InputQuads[2] || InputQuads[3];
5766   if (Subtarget->hasSSSE3()) {
5767     if (InputQuads.count() == 2 && V1Used && V2Used) {
5768       BestLoQuad = InputQuads[0] ? 0 : 1;
5769       BestHiQuad = InputQuads[2] ? 2 : 3;
5770     }
5771     if (InputQuads.count() > 2) {
5772       BestLoQuad = -1;
5773       BestHiQuad = -1;
5774     }
5775   }
5776
5777   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5778   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5779   // words from all 4 input quadwords.
5780   SDValue NewV;
5781   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5782     int MaskV[] = {
5783       BestLoQuad < 0 ? 0 : BestLoQuad,
5784       BestHiQuad < 0 ? 1 : BestHiQuad
5785     };
5786     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5787                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5788                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5789     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5790
5791     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5792     // source words for the shuffle, to aid later transformations.
5793     bool AllWordsInNewV = true;
5794     bool InOrder[2] = { true, true };
5795     for (unsigned i = 0; i != 8; ++i) {
5796       int idx = MaskVals[i];
5797       if (idx != (int)i)
5798         InOrder[i/4] = false;
5799       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5800         continue;
5801       AllWordsInNewV = false;
5802       break;
5803     }
5804
5805     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5806     if (AllWordsInNewV) {
5807       for (int i = 0; i != 8; ++i) {
5808         int idx = MaskVals[i];
5809         if (idx < 0)
5810           continue;
5811         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5812         if ((idx != i) && idx < 4)
5813           pshufhw = false;
5814         if ((idx != i) && idx > 3)
5815           pshuflw = false;
5816       }
5817       V1 = NewV;
5818       V2Used = false;
5819       BestLoQuad = 0;
5820       BestHiQuad = 1;
5821     }
5822
5823     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5824     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5825     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5826       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5827       unsigned TargetMask = 0;
5828       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5829                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5830       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5831       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5832                              getShufflePSHUFLWImmediate(SVOp);
5833       V1 = NewV.getOperand(0);
5834       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5835     }
5836   }
5837
5838   // If we have SSSE3, and all words of the result are from 1 input vector,
5839   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5840   // is present, fall back to case 4.
5841   if (Subtarget->hasSSSE3()) {
5842     SmallVector<SDValue,16> pshufbMask;
5843
5844     // If we have elements from both input vectors, set the high bit of the
5845     // shuffle mask element to zero out elements that come from V2 in the V1
5846     // mask, and elements that come from V1 in the V2 mask, so that the two
5847     // results can be OR'd together.
5848     bool TwoInputs = V1Used && V2Used;
5849     for (unsigned i = 0; i != 8; ++i) {
5850       int EltIdx = MaskVals[i] * 2;
5851       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5852       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5853       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5854       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5855     }
5856     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5857     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5858                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5859                                  MVT::v16i8, &pshufbMask[0], 16));
5860     if (!TwoInputs)
5861       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5862
5863     // Calculate the shuffle mask for the second input, shuffle it, and
5864     // OR it with the first shuffled input.
5865     pshufbMask.clear();
5866     for (unsigned i = 0; i != 8; ++i) {
5867       int EltIdx = MaskVals[i] * 2;
5868       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5869       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5870       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5871       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5872     }
5873     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5874     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5875                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5876                                  MVT::v16i8, &pshufbMask[0], 16));
5877     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5878     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5879   }
5880
5881   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5882   // and update MaskVals with new element order.
5883   std::bitset<8> InOrder;
5884   if (BestLoQuad >= 0) {
5885     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5886     for (int i = 0; i != 4; ++i) {
5887       int idx = MaskVals[i];
5888       if (idx < 0) {
5889         InOrder.set(i);
5890       } else if ((idx / 4) == BestLoQuad) {
5891         MaskV[i] = idx & 3;
5892         InOrder.set(i);
5893       }
5894     }
5895     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5896                                 &MaskV[0]);
5897
5898     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5899       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5900       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5901                                   NewV.getOperand(0),
5902                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5903     }
5904   }
5905
5906   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5907   // and update MaskVals with the new element order.
5908   if (BestHiQuad >= 0) {
5909     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5910     for (unsigned i = 4; i != 8; ++i) {
5911       int idx = MaskVals[i];
5912       if (idx < 0) {
5913         InOrder.set(i);
5914       } else if ((idx / 4) == BestHiQuad) {
5915         MaskV[i] = (idx & 3) + 4;
5916         InOrder.set(i);
5917       }
5918     }
5919     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5920                                 &MaskV[0]);
5921
5922     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5923       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5924       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5925                                   NewV.getOperand(0),
5926                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5927     }
5928   }
5929
5930   // In case BestHi & BestLo were both -1, which means each quadword has a word
5931   // from each of the four input quadwords, calculate the InOrder bitvector now
5932   // before falling through to the insert/extract cleanup.
5933   if (BestLoQuad == -1 && BestHiQuad == -1) {
5934     NewV = V1;
5935     for (int i = 0; i != 8; ++i)
5936       if (MaskVals[i] < 0 || MaskVals[i] == i)
5937         InOrder.set(i);
5938   }
5939
5940   // The other elements are put in the right place using pextrw and pinsrw.
5941   for (unsigned i = 0; i != 8; ++i) {
5942     if (InOrder[i])
5943       continue;
5944     int EltIdx = MaskVals[i];
5945     if (EltIdx < 0)
5946       continue;
5947     SDValue ExtOp = (EltIdx < 8) ?
5948       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5949                   DAG.getIntPtrConstant(EltIdx)) :
5950       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5951                   DAG.getIntPtrConstant(EltIdx - 8));
5952     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5953                        DAG.getIntPtrConstant(i));
5954   }
5955   return NewV;
5956 }
5957
5958 // v16i8 shuffles - Prefer shuffles in the following order:
5959 // 1. [ssse3] 1 x pshufb
5960 // 2. [ssse3] 2 x pshufb + 1 x por
5961 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5962 static
5963 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5964                                  SelectionDAG &DAG,
5965                                  const X86TargetLowering &TLI) {
5966   SDValue V1 = SVOp->getOperand(0);
5967   SDValue V2 = SVOp->getOperand(1);
5968   DebugLoc dl = SVOp->getDebugLoc();
5969   ArrayRef<int> MaskVals = SVOp->getMask();
5970
5971   // If we have SSSE3, case 1 is generated when all result bytes come from
5972   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5973   // present, fall back to case 3.
5974
5975   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5976   if (TLI.getSubtarget()->hasSSSE3()) {
5977     SmallVector<SDValue,16> pshufbMask;
5978
5979     // If all result elements are from one input vector, then only translate
5980     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5981     //
5982     // Otherwise, we have elements from both input vectors, and must zero out
5983     // elements that come from V2 in the first mask, and V1 in the second mask
5984     // so that we can OR them together.
5985     for (unsigned i = 0; i != 16; ++i) {
5986       int EltIdx = MaskVals[i];
5987       if (EltIdx < 0 || EltIdx >= 16)
5988         EltIdx = 0x80;
5989       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5990     }
5991     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5992                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5993                                  MVT::v16i8, &pshufbMask[0], 16));
5994
5995     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5996     // the 2nd operand if it's undefined or zero.
5997     if (V2.getOpcode() == ISD::UNDEF ||
5998         ISD::isBuildVectorAllZeros(V2.getNode()))
5999       return V1;
6000
6001     // Calculate the shuffle mask for the second input, shuffle it, and
6002     // OR it with the first shuffled input.
6003     pshufbMask.clear();
6004     for (unsigned i = 0; i != 16; ++i) {
6005       int EltIdx = MaskVals[i];
6006       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6007       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6008     }
6009     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6010                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6011                                  MVT::v16i8, &pshufbMask[0], 16));
6012     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6013   }
6014
6015   // No SSSE3 - Calculate in place words and then fix all out of place words
6016   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6017   // the 16 different words that comprise the two doublequadword input vectors.
6018   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6019   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6020   SDValue NewV = V1;
6021   for (int i = 0; i != 8; ++i) {
6022     int Elt0 = MaskVals[i*2];
6023     int Elt1 = MaskVals[i*2+1];
6024
6025     // This word of the result is all undef, skip it.
6026     if (Elt0 < 0 && Elt1 < 0)
6027       continue;
6028
6029     // This word of the result is already in the correct place, skip it.
6030     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6031       continue;
6032
6033     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6034     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6035     SDValue InsElt;
6036
6037     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6038     // using a single extract together, load it and store it.
6039     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6040       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6041                            DAG.getIntPtrConstant(Elt1 / 2));
6042       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6043                         DAG.getIntPtrConstant(i));
6044       continue;
6045     }
6046
6047     // If Elt1 is defined, extract it from the appropriate source.  If the
6048     // source byte is not also odd, shift the extracted word left 8 bits
6049     // otherwise clear the bottom 8 bits if we need to do an or.
6050     if (Elt1 >= 0) {
6051       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6052                            DAG.getIntPtrConstant(Elt1 / 2));
6053       if ((Elt1 & 1) == 0)
6054         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6055                              DAG.getConstant(8,
6056                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6057       else if (Elt0 >= 0)
6058         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6059                              DAG.getConstant(0xFF00, MVT::i16));
6060     }
6061     // If Elt0 is defined, extract it from the appropriate source.  If the
6062     // source byte is not also even, shift the extracted word right 8 bits. If
6063     // Elt1 was also defined, OR the extracted values together before
6064     // inserting them in the result.
6065     if (Elt0 >= 0) {
6066       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6067                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6068       if ((Elt0 & 1) != 0)
6069         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6070                               DAG.getConstant(8,
6071                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6072       else if (Elt1 >= 0)
6073         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6074                              DAG.getConstant(0x00FF, MVT::i16));
6075       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6076                          : InsElt0;
6077     }
6078     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6079                        DAG.getIntPtrConstant(i));
6080   }
6081   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6082 }
6083
6084 // v32i8 shuffles - Translate to VPSHUFB if possible.
6085 static
6086 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6087                                  const X86Subtarget *Subtarget,
6088                                  SelectionDAG &DAG) {
6089   EVT VT = SVOp->getValueType(0);
6090   SDValue V1 = SVOp->getOperand(0);
6091   SDValue V2 = SVOp->getOperand(1);
6092   DebugLoc dl = SVOp->getDebugLoc();
6093   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6094
6095   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6096   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6097   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6098
6099   // VPSHUFB may be generated if
6100   // (1) one of input vector is undefined or zeroinitializer.
6101   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6102   // And (2) the mask indexes don't cross the 128-bit lane.
6103   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6104       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6105     return SDValue();
6106
6107   if (V1IsAllZero && !V2IsAllZero) {
6108     CommuteVectorShuffleMask(MaskVals, 32);
6109     V1 = V2;
6110   }
6111   SmallVector<SDValue, 32> pshufbMask;
6112   for (unsigned i = 0; i != 32; i++) {
6113     int EltIdx = MaskVals[i];
6114     if (EltIdx < 0 || EltIdx >= 32)
6115       EltIdx = 0x80;
6116     else {
6117       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6118         // Cross lane is not allowed.
6119         return SDValue();
6120       EltIdx &= 0xf;
6121     }
6122     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6123   }
6124   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6125                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6126                                   MVT::v32i8, &pshufbMask[0], 32));
6127 }
6128
6129 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6130 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6131 /// done when every pair / quad of shuffle mask elements point to elements in
6132 /// the right sequence. e.g.
6133 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6134 static
6135 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6136                                  SelectionDAG &DAG, DebugLoc dl) {
6137   MVT VT = SVOp->getValueType(0).getSimpleVT();
6138   unsigned NumElems = VT.getVectorNumElements();
6139   MVT NewVT;
6140   unsigned Scale;
6141   switch (VT.SimpleTy) {
6142   default: llvm_unreachable("Unexpected!");
6143   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6144   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6145   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6146   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6147   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6148   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6149   }
6150
6151   SmallVector<int, 8> MaskVec;
6152   for (unsigned i = 0; i != NumElems; i += Scale) {
6153     int StartIdx = -1;
6154     for (unsigned j = 0; j != Scale; ++j) {
6155       int EltIdx = SVOp->getMaskElt(i+j);
6156       if (EltIdx < 0)
6157         continue;
6158       if (StartIdx < 0)
6159         StartIdx = (EltIdx / Scale);
6160       if (EltIdx != (int)(StartIdx*Scale + j))
6161         return SDValue();
6162     }
6163     MaskVec.push_back(StartIdx);
6164   }
6165
6166   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6167   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6168   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6169 }
6170
6171 /// getVZextMovL - Return a zero-extending vector move low node.
6172 ///
6173 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6174                             SDValue SrcOp, SelectionDAG &DAG,
6175                             const X86Subtarget *Subtarget, DebugLoc dl) {
6176   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6177     LoadSDNode *LD = NULL;
6178     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6179       LD = dyn_cast<LoadSDNode>(SrcOp);
6180     if (!LD) {
6181       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6182       // instead.
6183       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6184       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6185           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6186           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6187           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6188         // PR2108
6189         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6190         return DAG.getNode(ISD::BITCAST, dl, VT,
6191                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6192                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6193                                                    OpVT,
6194                                                    SrcOp.getOperand(0)
6195                                                           .getOperand(0))));
6196       }
6197     }
6198   }
6199
6200   return DAG.getNode(ISD::BITCAST, dl, VT,
6201                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6202                                  DAG.getNode(ISD::BITCAST, dl,
6203                                              OpVT, SrcOp)));
6204 }
6205
6206 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6207 /// which could not be matched by any known target speficic shuffle
6208 static SDValue
6209 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6210
6211   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6212   if (NewOp.getNode())
6213     return NewOp;
6214
6215   EVT VT = SVOp->getValueType(0);
6216
6217   unsigned NumElems = VT.getVectorNumElements();
6218   unsigned NumLaneElems = NumElems / 2;
6219
6220   DebugLoc dl = SVOp->getDebugLoc();
6221   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6222   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6223   SDValue Output[2];
6224
6225   SmallVector<int, 16> Mask;
6226   for (unsigned l = 0; l < 2; ++l) {
6227     // Build a shuffle mask for the output, discovering on the fly which
6228     // input vectors to use as shuffle operands (recorded in InputUsed).
6229     // If building a suitable shuffle vector proves too hard, then bail
6230     // out with UseBuildVector set.
6231     bool UseBuildVector = false;
6232     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6233     unsigned LaneStart = l * NumLaneElems;
6234     for (unsigned i = 0; i != NumLaneElems; ++i) {
6235       // The mask element.  This indexes into the input.
6236       int Idx = SVOp->getMaskElt(i+LaneStart);
6237       if (Idx < 0) {
6238         // the mask element does not index into any input vector.
6239         Mask.push_back(-1);
6240         continue;
6241       }
6242
6243       // The input vector this mask element indexes into.
6244       int Input = Idx / NumLaneElems;
6245
6246       // Turn the index into an offset from the start of the input vector.
6247       Idx -= Input * NumLaneElems;
6248
6249       // Find or create a shuffle vector operand to hold this input.
6250       unsigned OpNo;
6251       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6252         if (InputUsed[OpNo] == Input)
6253           // This input vector is already an operand.
6254           break;
6255         if (InputUsed[OpNo] < 0) {
6256           // Create a new operand for this input vector.
6257           InputUsed[OpNo] = Input;
6258           break;
6259         }
6260       }
6261
6262       if (OpNo >= array_lengthof(InputUsed)) {
6263         // More than two input vectors used!  Give up on trying to create a
6264         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6265         UseBuildVector = true;
6266         break;
6267       }
6268
6269       // Add the mask index for the new shuffle vector.
6270       Mask.push_back(Idx + OpNo * NumLaneElems);
6271     }
6272
6273     if (UseBuildVector) {
6274       SmallVector<SDValue, 16> SVOps;
6275       for (unsigned i = 0; i != NumLaneElems; ++i) {
6276         // The mask element.  This indexes into the input.
6277         int Idx = SVOp->getMaskElt(i+LaneStart);
6278         if (Idx < 0) {
6279           SVOps.push_back(DAG.getUNDEF(EltVT));
6280           continue;
6281         }
6282
6283         // The input vector this mask element indexes into.
6284         int Input = Idx / NumElems;
6285
6286         // Turn the index into an offset from the start of the input vector.
6287         Idx -= Input * NumElems;
6288
6289         // Extract the vector element by hand.
6290         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6291                                     SVOp->getOperand(Input),
6292                                     DAG.getIntPtrConstant(Idx)));
6293       }
6294
6295       // Construct the output using a BUILD_VECTOR.
6296       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6297                               SVOps.size());
6298     } else if (InputUsed[0] < 0) {
6299       // No input vectors were used! The result is undefined.
6300       Output[l] = DAG.getUNDEF(NVT);
6301     } else {
6302       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6303                                         (InputUsed[0] % 2) * NumLaneElems,
6304                                         DAG, dl);
6305       // If only one input was used, use an undefined vector for the other.
6306       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6307         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6308                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6309       // At least one input vector was used. Create a new shuffle vector.
6310       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6311     }
6312
6313     Mask.clear();
6314   }
6315
6316   // Concatenate the result back
6317   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6318 }
6319
6320 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6321 /// 4 elements, and match them with several different shuffle types.
6322 static SDValue
6323 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6324   SDValue V1 = SVOp->getOperand(0);
6325   SDValue V2 = SVOp->getOperand(1);
6326   DebugLoc dl = SVOp->getDebugLoc();
6327   EVT VT = SVOp->getValueType(0);
6328
6329   assert(VT.is128BitVector() && "Unsupported vector size");
6330
6331   std::pair<int, int> Locs[4];
6332   int Mask1[] = { -1, -1, -1, -1 };
6333   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6334
6335   unsigned NumHi = 0;
6336   unsigned NumLo = 0;
6337   for (unsigned i = 0; i != 4; ++i) {
6338     int Idx = PermMask[i];
6339     if (Idx < 0) {
6340       Locs[i] = std::make_pair(-1, -1);
6341     } else {
6342       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6343       if (Idx < 4) {
6344         Locs[i] = std::make_pair(0, NumLo);
6345         Mask1[NumLo] = Idx;
6346         NumLo++;
6347       } else {
6348         Locs[i] = std::make_pair(1, NumHi);
6349         if (2+NumHi < 4)
6350           Mask1[2+NumHi] = Idx;
6351         NumHi++;
6352       }
6353     }
6354   }
6355
6356   if (NumLo <= 2 && NumHi <= 2) {
6357     // If no more than two elements come from either vector. This can be
6358     // implemented with two shuffles. First shuffle gather the elements.
6359     // The second shuffle, which takes the first shuffle as both of its
6360     // vector operands, put the elements into the right order.
6361     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6362
6363     int Mask2[] = { -1, -1, -1, -1 };
6364
6365     for (unsigned i = 0; i != 4; ++i)
6366       if (Locs[i].first != -1) {
6367         unsigned Idx = (i < 2) ? 0 : 4;
6368         Idx += Locs[i].first * 2 + Locs[i].second;
6369         Mask2[i] = Idx;
6370       }
6371
6372     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6373   }
6374
6375   if (NumLo == 3 || NumHi == 3) {
6376     // Otherwise, we must have three elements from one vector, call it X, and
6377     // one element from the other, call it Y.  First, use a shufps to build an
6378     // intermediate vector with the one element from Y and the element from X
6379     // that will be in the same half in the final destination (the indexes don't
6380     // matter). Then, use a shufps to build the final vector, taking the half
6381     // containing the element from Y from the intermediate, and the other half
6382     // from X.
6383     if (NumHi == 3) {
6384       // Normalize it so the 3 elements come from V1.
6385       CommuteVectorShuffleMask(PermMask, 4);
6386       std::swap(V1, V2);
6387     }
6388
6389     // Find the element from V2.
6390     unsigned HiIndex;
6391     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6392       int Val = PermMask[HiIndex];
6393       if (Val < 0)
6394         continue;
6395       if (Val >= 4)
6396         break;
6397     }
6398
6399     Mask1[0] = PermMask[HiIndex];
6400     Mask1[1] = -1;
6401     Mask1[2] = PermMask[HiIndex^1];
6402     Mask1[3] = -1;
6403     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6404
6405     if (HiIndex >= 2) {
6406       Mask1[0] = PermMask[0];
6407       Mask1[1] = PermMask[1];
6408       Mask1[2] = HiIndex & 1 ? 6 : 4;
6409       Mask1[3] = HiIndex & 1 ? 4 : 6;
6410       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6411     }
6412
6413     Mask1[0] = HiIndex & 1 ? 2 : 0;
6414     Mask1[1] = HiIndex & 1 ? 0 : 2;
6415     Mask1[2] = PermMask[2];
6416     Mask1[3] = PermMask[3];
6417     if (Mask1[2] >= 0)
6418       Mask1[2] += 4;
6419     if (Mask1[3] >= 0)
6420       Mask1[3] += 4;
6421     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6422   }
6423
6424   // Break it into (shuffle shuffle_hi, shuffle_lo).
6425   int LoMask[] = { -1, -1, -1, -1 };
6426   int HiMask[] = { -1, -1, -1, -1 };
6427
6428   int *MaskPtr = LoMask;
6429   unsigned MaskIdx = 0;
6430   unsigned LoIdx = 0;
6431   unsigned HiIdx = 2;
6432   for (unsigned i = 0; i != 4; ++i) {
6433     if (i == 2) {
6434       MaskPtr = HiMask;
6435       MaskIdx = 1;
6436       LoIdx = 0;
6437       HiIdx = 2;
6438     }
6439     int Idx = PermMask[i];
6440     if (Idx < 0) {
6441       Locs[i] = std::make_pair(-1, -1);
6442     } else if (Idx < 4) {
6443       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6444       MaskPtr[LoIdx] = Idx;
6445       LoIdx++;
6446     } else {
6447       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6448       MaskPtr[HiIdx] = Idx;
6449       HiIdx++;
6450     }
6451   }
6452
6453   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6454   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6455   int MaskOps[] = { -1, -1, -1, -1 };
6456   for (unsigned i = 0; i != 4; ++i)
6457     if (Locs[i].first != -1)
6458       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6459   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6460 }
6461
6462 static bool MayFoldVectorLoad(SDValue V) {
6463   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6464     V = V.getOperand(0);
6465
6466   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6467     V = V.getOperand(0);
6468   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6469       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6470     // BUILD_VECTOR (load), undef
6471     V = V.getOperand(0);
6472
6473   return MayFoldLoad(V);
6474 }
6475
6476 static
6477 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6478   EVT VT = Op.getValueType();
6479
6480   // Canonizalize to v2f64.
6481   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6482   return DAG.getNode(ISD::BITCAST, dl, VT,
6483                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6484                                           V1, DAG));
6485 }
6486
6487 static
6488 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6489                         bool HasSSE2) {
6490   SDValue V1 = Op.getOperand(0);
6491   SDValue V2 = Op.getOperand(1);
6492   EVT VT = Op.getValueType();
6493
6494   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6495
6496   if (HasSSE2 && VT == MVT::v2f64)
6497     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6498
6499   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6500   return DAG.getNode(ISD::BITCAST, dl, VT,
6501                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6502                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6503                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6504 }
6505
6506 static
6507 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6508   SDValue V1 = Op.getOperand(0);
6509   SDValue V2 = Op.getOperand(1);
6510   EVT VT = Op.getValueType();
6511
6512   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6513          "unsupported shuffle type");
6514
6515   if (V2.getOpcode() == ISD::UNDEF)
6516     V2 = V1;
6517
6518   // v4i32 or v4f32
6519   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6520 }
6521
6522 static
6523 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6524   SDValue V1 = Op.getOperand(0);
6525   SDValue V2 = Op.getOperand(1);
6526   EVT VT = Op.getValueType();
6527   unsigned NumElems = VT.getVectorNumElements();
6528
6529   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6530   // operand of these instructions is only memory, so check if there's a
6531   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6532   // same masks.
6533   bool CanFoldLoad = false;
6534
6535   // Trivial case, when V2 comes from a load.
6536   if (MayFoldVectorLoad(V2))
6537     CanFoldLoad = true;
6538
6539   // When V1 is a load, it can be folded later into a store in isel, example:
6540   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6541   //    turns into:
6542   //  (MOVLPSmr addr:$src1, VR128:$src2)
6543   // So, recognize this potential and also use MOVLPS or MOVLPD
6544   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6545     CanFoldLoad = true;
6546
6547   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6548   if (CanFoldLoad) {
6549     if (HasSSE2 && NumElems == 2)
6550       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6551
6552     if (NumElems == 4)
6553       // If we don't care about the second element, proceed to use movss.
6554       if (SVOp->getMaskElt(1) != -1)
6555         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6556   }
6557
6558   // movl and movlp will both match v2i64, but v2i64 is never matched by
6559   // movl earlier because we make it strict to avoid messing with the movlp load
6560   // folding logic (see the code above getMOVLP call). Match it here then,
6561   // this is horrible, but will stay like this until we move all shuffle
6562   // matching to x86 specific nodes. Note that for the 1st condition all
6563   // types are matched with movsd.
6564   if (HasSSE2) {
6565     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6566     // as to remove this logic from here, as much as possible
6567     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6568       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6569     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6570   }
6571
6572   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6573
6574   // Invert the operand order and use SHUFPS to match it.
6575   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6576                               getShuffleSHUFImmediate(SVOp), DAG);
6577 }
6578
6579 // Reduce a vector shuffle to zext.
6580 SDValue
6581 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6582   // PMOVZX is only available from SSE41.
6583   if (!Subtarget->hasSSE41())
6584     return SDValue();
6585
6586   EVT VT = Op.getValueType();
6587
6588   // Only AVX2 support 256-bit vector integer extending.
6589   if (!Subtarget->hasInt256() && VT.is256BitVector())
6590     return SDValue();
6591
6592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6593   DebugLoc DL = Op.getDebugLoc();
6594   SDValue V1 = Op.getOperand(0);
6595   SDValue V2 = Op.getOperand(1);
6596   unsigned NumElems = VT.getVectorNumElements();
6597
6598   // Extending is an unary operation and the element type of the source vector
6599   // won't be equal to or larger than i64.
6600   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6601       VT.getVectorElementType() == MVT::i64)
6602     return SDValue();
6603
6604   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6605   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6606   while ((1U << Shift) < NumElems) {
6607     if (SVOp->getMaskElt(1U << Shift) == 1)
6608       break;
6609     Shift += 1;
6610     // The maximal ratio is 8, i.e. from i8 to i64.
6611     if (Shift > 3)
6612       return SDValue();
6613   }
6614
6615   // Check the shuffle mask.
6616   unsigned Mask = (1U << Shift) - 1;
6617   for (unsigned i = 0; i != NumElems; ++i) {
6618     int EltIdx = SVOp->getMaskElt(i);
6619     if ((i & Mask) != 0 && EltIdx != -1)
6620       return SDValue();
6621     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6622       return SDValue();
6623   }
6624
6625   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6626   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6627   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6628
6629   if (!isTypeLegal(NVT))
6630     return SDValue();
6631
6632   // Simplify the operand as it's prepared to be fed into shuffle.
6633   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6634   if (V1.getOpcode() == ISD::BITCAST &&
6635       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6636       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6637       V1.getOperand(0)
6638         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6639     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6640     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6641     ConstantSDNode *CIdx =
6642       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6643     // If it's foldable, i.e. normal load with single use, we will let code
6644     // selection to fold it. Otherwise, we will short the conversion sequence.
6645     if (CIdx && CIdx->getZExtValue() == 0 &&
6646         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6647       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6648   }
6649
6650   return DAG.getNode(ISD::BITCAST, DL, VT,
6651                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6652 }
6653
6654 SDValue
6655 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6656   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6657   EVT VT = Op.getValueType();
6658   DebugLoc dl = Op.getDebugLoc();
6659   SDValue V1 = Op.getOperand(0);
6660   SDValue V2 = Op.getOperand(1);
6661
6662   if (isZeroShuffle(SVOp))
6663     return getZeroVector(VT, Subtarget, DAG, dl);
6664
6665   // Handle splat operations
6666   if (SVOp->isSplat()) {
6667     unsigned NumElem = VT.getVectorNumElements();
6668     int Size = VT.getSizeInBits();
6669
6670     // Use vbroadcast whenever the splat comes from a foldable load
6671     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6672     if (Broadcast.getNode())
6673       return Broadcast;
6674
6675     // Handle splats by matching through known shuffle masks
6676     if ((Size == 128 && NumElem <= 4) ||
6677         (Size == 256 && NumElem <= 8))
6678       return SDValue();
6679
6680     // All remaning splats are promoted to target supported vector shuffles.
6681     return PromoteSplat(SVOp, DAG);
6682   }
6683
6684   // Check integer expanding shuffles.
6685   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6686   if (NewOp.getNode())
6687     return NewOp;
6688
6689   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6690   // do it!
6691   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6692       VT == MVT::v16i16 || VT == MVT::v32i8) {
6693     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694     if (NewOp.getNode())
6695       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6696   } else if ((VT == MVT::v4i32 ||
6697              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6698     // FIXME: Figure out a cleaner way to do this.
6699     // Try to make use of movq to zero out the top part.
6700     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6701       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6702       if (NewOp.getNode()) {
6703         EVT NewVT = NewOp.getValueType();
6704         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6705                                NewVT, true, false))
6706           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6707                               DAG, Subtarget, dl);
6708       }
6709     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6710       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6711       if (NewOp.getNode()) {
6712         EVT NewVT = NewOp.getValueType();
6713         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6714           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6715                               DAG, Subtarget, dl);
6716       }
6717     }
6718   }
6719   return SDValue();
6720 }
6721
6722 SDValue
6723 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6724   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6725   SDValue V1 = Op.getOperand(0);
6726   SDValue V2 = Op.getOperand(1);
6727   EVT VT = Op.getValueType();
6728   DebugLoc dl = Op.getDebugLoc();
6729   unsigned NumElems = VT.getVectorNumElements();
6730   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6731   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6732   bool V1IsSplat = false;
6733   bool V2IsSplat = false;
6734   bool HasSSE2 = Subtarget->hasSSE2();
6735   bool HasFp256    = Subtarget->hasFp256();
6736   bool HasInt256   = Subtarget->hasInt256();
6737   MachineFunction &MF = DAG.getMachineFunction();
6738   bool OptForSize = MF.getFunction()->getFnAttributes().
6739     hasAttribute(Attribute::OptimizeForSize);
6740
6741   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6742
6743   if (V1IsUndef && V2IsUndef)
6744     return DAG.getUNDEF(VT);
6745
6746   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6747
6748   // Vector shuffle lowering takes 3 steps:
6749   //
6750   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6751   //    narrowing and commutation of operands should be handled.
6752   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6753   //    shuffle nodes.
6754   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6755   //    so the shuffle can be broken into other shuffles and the legalizer can
6756   //    try the lowering again.
6757   //
6758   // The general idea is that no vector_shuffle operation should be left to
6759   // be matched during isel, all of them must be converted to a target specific
6760   // node here.
6761
6762   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6763   // narrowing and commutation of operands should be handled. The actual code
6764   // doesn't include all of those, work in progress...
6765   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6766   if (NewOp.getNode())
6767     return NewOp;
6768
6769   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6770
6771   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6772   // unpckh_undef). Only use pshufd if speed is more important than size.
6773   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6774     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6775   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6776     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6777
6778   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6779       V2IsUndef && MayFoldVectorLoad(V1))
6780     return getMOVDDup(Op, dl, V1, DAG);
6781
6782   if (isMOVHLPS_v_undef_Mask(M, VT))
6783     return getMOVHighToLow(Op, dl, DAG);
6784
6785   // Use to match splats
6786   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6787       (VT == MVT::v2f64 || VT == MVT::v2i64))
6788     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6789
6790   if (isPSHUFDMask(M, VT)) {
6791     // The actual implementation will match the mask in the if above and then
6792     // during isel it can match several different instructions, not only pshufd
6793     // as its name says, sad but true, emulate the behavior for now...
6794     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6795       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6796
6797     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6798
6799     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6800       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6801
6802     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6803       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6804                                   DAG);
6805
6806     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6807                                 TargetMask, DAG);
6808   }
6809
6810   // Check if this can be converted into a logical shift.
6811   bool isLeft = false;
6812   unsigned ShAmt = 0;
6813   SDValue ShVal;
6814   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6815   if (isShift && ShVal.hasOneUse()) {
6816     // If the shifted value has multiple uses, it may be cheaper to use
6817     // v_set0 + movlhps or movhlps, etc.
6818     EVT EltVT = VT.getVectorElementType();
6819     ShAmt *= EltVT.getSizeInBits();
6820     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6821   }
6822
6823   if (isMOVLMask(M, VT)) {
6824     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6825       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6826     if (!isMOVLPMask(M, VT)) {
6827       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6828         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6829
6830       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6831         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6832     }
6833   }
6834
6835   // FIXME: fold these into legal mask.
6836   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6837     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6838
6839   if (isMOVHLPSMask(M, VT))
6840     return getMOVHighToLow(Op, dl, DAG);
6841
6842   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6843     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6844
6845   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6846     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6847
6848   if (isMOVLPMask(M, VT))
6849     return getMOVLP(Op, dl, DAG, HasSSE2);
6850
6851   if (ShouldXformToMOVHLPS(M, VT) ||
6852       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6853     return CommuteVectorShuffle(SVOp, DAG);
6854
6855   if (isShift) {
6856     // No better options. Use a vshldq / vsrldq.
6857     EVT EltVT = VT.getVectorElementType();
6858     ShAmt *= EltVT.getSizeInBits();
6859     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6860   }
6861
6862   bool Commuted = false;
6863   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6864   // 1,1,1,1 -> v8i16 though.
6865   V1IsSplat = isSplatVector(V1.getNode());
6866   V2IsSplat = isSplatVector(V2.getNode());
6867
6868   // Canonicalize the splat or undef, if present, to be on the RHS.
6869   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6870     CommuteVectorShuffleMask(M, NumElems);
6871     std::swap(V1, V2);
6872     std::swap(V1IsSplat, V2IsSplat);
6873     Commuted = true;
6874   }
6875
6876   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6877     // Shuffling low element of v1 into undef, just return v1.
6878     if (V2IsUndef)
6879       return V1;
6880     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6881     // the instruction selector will not match, so get a canonical MOVL with
6882     // swapped operands to undo the commute.
6883     return getMOVL(DAG, dl, VT, V2, V1);
6884   }
6885
6886   if (isUNPCKLMask(M, VT, HasInt256))
6887     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6888
6889   if (isUNPCKHMask(M, VT, HasInt256))
6890     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6891
6892   if (V2IsSplat) {
6893     // Normalize mask so all entries that point to V2 points to its first
6894     // element then try to match unpck{h|l} again. If match, return a
6895     // new vector_shuffle with the corrected mask.p
6896     SmallVector<int, 8> NewMask(M.begin(), M.end());
6897     NormalizeMask(NewMask, NumElems);
6898     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6899       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6900     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6901       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6902   }
6903
6904   if (Commuted) {
6905     // Commute is back and try unpck* again.
6906     // FIXME: this seems wrong.
6907     CommuteVectorShuffleMask(M, NumElems);
6908     std::swap(V1, V2);
6909     std::swap(V1IsSplat, V2IsSplat);
6910     Commuted = false;
6911
6912     if (isUNPCKLMask(M, VT, HasInt256))
6913       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6914
6915     if (isUNPCKHMask(M, VT, HasInt256))
6916       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6917   }
6918
6919   // Normalize the node to match x86 shuffle ops if needed
6920   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6921     return CommuteVectorShuffle(SVOp, DAG);
6922
6923   // The checks below are all present in isShuffleMaskLegal, but they are
6924   // inlined here right now to enable us to directly emit target specific
6925   // nodes, and remove one by one until they don't return Op anymore.
6926
6927   if (isPALIGNRMask(M, VT, Subtarget))
6928     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6929                                 getShufflePALIGNRImmediate(SVOp),
6930                                 DAG);
6931
6932   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6933       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6934     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6935       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6936   }
6937
6938   if (isPSHUFHWMask(M, VT, HasInt256))
6939     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6940                                 getShufflePSHUFHWImmediate(SVOp),
6941                                 DAG);
6942
6943   if (isPSHUFLWMask(M, VT, HasInt256))
6944     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6945                                 getShufflePSHUFLWImmediate(SVOp),
6946                                 DAG);
6947
6948   if (isSHUFPMask(M, VT, HasFp256))
6949     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6950                                 getShuffleSHUFImmediate(SVOp), DAG);
6951
6952   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6953     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6954   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6955     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6956
6957   //===--------------------------------------------------------------------===//
6958   // Generate target specific nodes for 128 or 256-bit shuffles only
6959   // supported in the AVX instruction set.
6960   //
6961
6962   // Handle VMOVDDUPY permutations
6963   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6964     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6965
6966   // Handle VPERMILPS/D* permutations
6967   if (isVPERMILPMask(M, VT, HasFp256)) {
6968     if (HasInt256 && VT == MVT::v8i32)
6969       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6970                                   getShuffleSHUFImmediate(SVOp), DAG);
6971     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6972                                 getShuffleSHUFImmediate(SVOp), DAG);
6973   }
6974
6975   // Handle VPERM2F128/VPERM2I128 permutations
6976   if (isVPERM2X128Mask(M, VT, HasFp256))
6977     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6978                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6979
6980   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6981   if (BlendOp.getNode())
6982     return BlendOp;
6983
6984   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6985     SmallVector<SDValue, 8> permclMask;
6986     for (unsigned i = 0; i != 8; ++i) {
6987       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6988     }
6989     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6990                                &permclMask[0], 8);
6991     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6992     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6993                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6994   }
6995
6996   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6997     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6998                                 getShuffleCLImmediate(SVOp), DAG);
6999
7000
7001   //===--------------------------------------------------------------------===//
7002   // Since no target specific shuffle was selected for this generic one,
7003   // lower it into other known shuffles. FIXME: this isn't true yet, but
7004   // this is the plan.
7005   //
7006
7007   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7008   if (VT == MVT::v8i16) {
7009     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7010     if (NewOp.getNode())
7011       return NewOp;
7012   }
7013
7014   if (VT == MVT::v16i8) {
7015     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7016     if (NewOp.getNode())
7017       return NewOp;
7018   }
7019
7020   if (VT == MVT::v32i8) {
7021     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7022     if (NewOp.getNode())
7023       return NewOp;
7024   }
7025
7026   // Handle all 128-bit wide vectors with 4 elements, and match them with
7027   // several different shuffle types.
7028   if (NumElems == 4 && VT.is128BitVector())
7029     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7030
7031   // Handle general 256-bit shuffles
7032   if (VT.is256BitVector())
7033     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7034
7035   return SDValue();
7036 }
7037
7038 SDValue
7039 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7040                                                 SelectionDAG &DAG) const {
7041   EVT VT = Op.getValueType();
7042   DebugLoc dl = Op.getDebugLoc();
7043
7044   if (!Op.getOperand(0).getValueType().is128BitVector())
7045     return SDValue();
7046
7047   if (VT.getSizeInBits() == 8) {
7048     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7049                                   Op.getOperand(0), Op.getOperand(1));
7050     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7051                                   DAG.getValueType(VT));
7052     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7053   }
7054
7055   if (VT.getSizeInBits() == 16) {
7056     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7057     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7058     if (Idx == 0)
7059       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7060                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7061                                      DAG.getNode(ISD::BITCAST, dl,
7062                                                  MVT::v4i32,
7063                                                  Op.getOperand(0)),
7064                                      Op.getOperand(1)));
7065     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7066                                   Op.getOperand(0), Op.getOperand(1));
7067     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7068                                   DAG.getValueType(VT));
7069     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7070   }
7071
7072   if (VT == MVT::f32) {
7073     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7074     // the result back to FR32 register. It's only worth matching if the
7075     // result has a single use which is a store or a bitcast to i32.  And in
7076     // the case of a store, it's not worth it if the index is a constant 0,
7077     // because a MOVSSmr can be used instead, which is smaller and faster.
7078     if (!Op.hasOneUse())
7079       return SDValue();
7080     SDNode *User = *Op.getNode()->use_begin();
7081     if ((User->getOpcode() != ISD::STORE ||
7082          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7083           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7084         (User->getOpcode() != ISD::BITCAST ||
7085          User->getValueType(0) != MVT::i32))
7086       return SDValue();
7087     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7088                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7089                                               Op.getOperand(0)),
7090                                               Op.getOperand(1));
7091     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7092   }
7093
7094   if (VT == MVT::i32 || VT == MVT::i64) {
7095     // ExtractPS/pextrq works with constant index.
7096     if (isa<ConstantSDNode>(Op.getOperand(1)))
7097       return Op;
7098   }
7099   return SDValue();
7100 }
7101
7102
7103 SDValue
7104 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7105                                            SelectionDAG &DAG) const {
7106   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7107     return SDValue();
7108
7109   SDValue Vec = Op.getOperand(0);
7110   EVT VecVT = Vec.getValueType();
7111
7112   // If this is a 256-bit vector result, first extract the 128-bit vector and
7113   // then extract the element from the 128-bit vector.
7114   if (VecVT.is256BitVector()) {
7115     DebugLoc dl = Op.getNode()->getDebugLoc();
7116     unsigned NumElems = VecVT.getVectorNumElements();
7117     SDValue Idx = Op.getOperand(1);
7118     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7119
7120     // Get the 128-bit vector.
7121     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7122
7123     if (IdxVal >= NumElems/2)
7124       IdxVal -= NumElems/2;
7125     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7126                        DAG.getConstant(IdxVal, MVT::i32));
7127   }
7128
7129   assert(VecVT.is128BitVector() && "Unexpected vector length");
7130
7131   if (Subtarget->hasSSE41()) {
7132     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7133     if (Res.getNode())
7134       return Res;
7135   }
7136
7137   EVT VT = Op.getValueType();
7138   DebugLoc dl = Op.getDebugLoc();
7139   // TODO: handle v16i8.
7140   if (VT.getSizeInBits() == 16) {
7141     SDValue Vec = Op.getOperand(0);
7142     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7143     if (Idx == 0)
7144       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7145                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7146                                      DAG.getNode(ISD::BITCAST, dl,
7147                                                  MVT::v4i32, Vec),
7148                                      Op.getOperand(1)));
7149     // Transform it so it match pextrw which produces a 32-bit result.
7150     EVT EltVT = MVT::i32;
7151     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7152                                   Op.getOperand(0), Op.getOperand(1));
7153     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7154                                   DAG.getValueType(VT));
7155     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7156   }
7157
7158   if (VT.getSizeInBits() == 32) {
7159     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7160     if (Idx == 0)
7161       return Op;
7162
7163     // SHUFPS the element to the lowest double word, then movss.
7164     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7165     EVT VVT = Op.getOperand(0).getValueType();
7166     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7167                                        DAG.getUNDEF(VVT), Mask);
7168     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7169                        DAG.getIntPtrConstant(0));
7170   }
7171
7172   if (VT.getSizeInBits() == 64) {
7173     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7174     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7175     //        to match extract_elt for f64.
7176     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7177     if (Idx == 0)
7178       return Op;
7179
7180     // UNPCKHPD the element to the lowest double word, then movsd.
7181     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7182     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7183     int Mask[2] = { 1, -1 };
7184     EVT VVT = Op.getOperand(0).getValueType();
7185     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7186                                        DAG.getUNDEF(VVT), Mask);
7187     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7188                        DAG.getIntPtrConstant(0));
7189   }
7190
7191   return SDValue();
7192 }
7193
7194 SDValue
7195 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7196                                                SelectionDAG &DAG) const {
7197   EVT VT = Op.getValueType();
7198   EVT EltVT = VT.getVectorElementType();
7199   DebugLoc dl = Op.getDebugLoc();
7200
7201   SDValue N0 = Op.getOperand(0);
7202   SDValue N1 = Op.getOperand(1);
7203   SDValue N2 = Op.getOperand(2);
7204
7205   if (!VT.is128BitVector())
7206     return SDValue();
7207
7208   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7209       isa<ConstantSDNode>(N2)) {
7210     unsigned Opc;
7211     if (VT == MVT::v8i16)
7212       Opc = X86ISD::PINSRW;
7213     else if (VT == MVT::v16i8)
7214       Opc = X86ISD::PINSRB;
7215     else
7216       Opc = X86ISD::PINSRB;
7217
7218     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7219     // argument.
7220     if (N1.getValueType() != MVT::i32)
7221       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7222     if (N2.getValueType() != MVT::i32)
7223       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7224     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7225   }
7226
7227   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7228     // Bits [7:6] of the constant are the source select.  This will always be
7229     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7230     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7231     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7232     // Bits [5:4] of the constant are the destination select.  This is the
7233     //  value of the incoming immediate.
7234     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7235     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7236     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7237     // Create this as a scalar to vector..
7238     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7239     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7240   }
7241
7242   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7243     // PINSR* works with constant index.
7244     return Op;
7245   }
7246   return SDValue();
7247 }
7248
7249 SDValue
7250 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7251   EVT VT = Op.getValueType();
7252   EVT EltVT = VT.getVectorElementType();
7253
7254   DebugLoc dl = Op.getDebugLoc();
7255   SDValue N0 = Op.getOperand(0);
7256   SDValue N1 = Op.getOperand(1);
7257   SDValue N2 = Op.getOperand(2);
7258
7259   // If this is a 256-bit vector result, first extract the 128-bit vector,
7260   // insert the element into the extracted half and then place it back.
7261   if (VT.is256BitVector()) {
7262     if (!isa<ConstantSDNode>(N2))
7263       return SDValue();
7264
7265     // Get the desired 128-bit vector half.
7266     unsigned NumElems = VT.getVectorNumElements();
7267     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7268     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7269
7270     // Insert the element into the desired half.
7271     bool Upper = IdxVal >= NumElems/2;
7272     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7273                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7274
7275     // Insert the changed part back to the 256-bit vector
7276     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7277   }
7278
7279   if (Subtarget->hasSSE41())
7280     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7281
7282   if (EltVT == MVT::i8)
7283     return SDValue();
7284
7285   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7286     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7287     // as its second argument.
7288     if (N1.getValueType() != MVT::i32)
7289       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7290     if (N2.getValueType() != MVT::i32)
7291       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7292     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7293   }
7294   return SDValue();
7295 }
7296
7297 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7298   LLVMContext *Context = DAG.getContext();
7299   DebugLoc dl = Op.getDebugLoc();
7300   EVT OpVT = Op.getValueType();
7301
7302   // If this is a 256-bit vector result, first insert into a 128-bit
7303   // vector and then insert into the 256-bit vector.
7304   if (!OpVT.is128BitVector()) {
7305     // Insert into a 128-bit vector.
7306     EVT VT128 = EVT::getVectorVT(*Context,
7307                                  OpVT.getVectorElementType(),
7308                                  OpVT.getVectorNumElements() / 2);
7309
7310     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7311
7312     // Insert the 128-bit vector.
7313     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7314   }
7315
7316   if (OpVT == MVT::v1i64 &&
7317       Op.getOperand(0).getValueType() == MVT::i64)
7318     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7319
7320   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7321   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7322   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7323                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7324 }
7325
7326 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7327 // a simple subregister reference or explicit instructions to grab
7328 // upper bits of a vector.
7329 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7330                                       SelectionDAG &DAG) {
7331   if (Subtarget->hasFp256()) {
7332     DebugLoc dl = Op.getNode()->getDebugLoc();
7333     SDValue Vec = Op.getNode()->getOperand(0);
7334     SDValue Idx = Op.getNode()->getOperand(1);
7335
7336     if (Op.getNode()->getValueType(0).is128BitVector() &&
7337         Vec.getNode()->getValueType(0).is256BitVector() &&
7338         isa<ConstantSDNode>(Idx)) {
7339       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7340       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7341     }
7342   }
7343   return SDValue();
7344 }
7345
7346 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7347 // simple superregister reference or explicit instructions to insert
7348 // the upper bits of a vector.
7349 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7350                                      SelectionDAG &DAG) {
7351   if (Subtarget->hasFp256()) {
7352     DebugLoc dl = Op.getNode()->getDebugLoc();
7353     SDValue Vec = Op.getNode()->getOperand(0);
7354     SDValue SubVec = Op.getNode()->getOperand(1);
7355     SDValue Idx = Op.getNode()->getOperand(2);
7356
7357     if (Op.getNode()->getValueType(0).is256BitVector() &&
7358         SubVec.getNode()->getValueType(0).is128BitVector() &&
7359         isa<ConstantSDNode>(Idx)) {
7360       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7361       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7362     }
7363   }
7364   return SDValue();
7365 }
7366
7367 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7368 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7369 // one of the above mentioned nodes. It has to be wrapped because otherwise
7370 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7371 // be used to form addressing mode. These wrapped nodes will be selected
7372 // into MOV32ri.
7373 SDValue
7374 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7375   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7376
7377   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7378   // global base reg.
7379   unsigned char OpFlag = 0;
7380   unsigned WrapperKind = X86ISD::Wrapper;
7381   CodeModel::Model M = getTargetMachine().getCodeModel();
7382
7383   if (Subtarget->isPICStyleRIPRel() &&
7384       (M == CodeModel::Small || M == CodeModel::Kernel))
7385     WrapperKind = X86ISD::WrapperRIP;
7386   else if (Subtarget->isPICStyleGOT())
7387     OpFlag = X86II::MO_GOTOFF;
7388   else if (Subtarget->isPICStyleStubPIC())
7389     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7390
7391   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7392                                              CP->getAlignment(),
7393                                              CP->getOffset(), OpFlag);
7394   DebugLoc DL = CP->getDebugLoc();
7395   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7396   // With PIC, the address is actually $g + Offset.
7397   if (OpFlag) {
7398     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7399                          DAG.getNode(X86ISD::GlobalBaseReg,
7400                                      DebugLoc(), getPointerTy()),
7401                          Result);
7402   }
7403
7404   return Result;
7405 }
7406
7407 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7408   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7409
7410   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7411   // global base reg.
7412   unsigned char OpFlag = 0;
7413   unsigned WrapperKind = X86ISD::Wrapper;
7414   CodeModel::Model M = getTargetMachine().getCodeModel();
7415
7416   if (Subtarget->isPICStyleRIPRel() &&
7417       (M == CodeModel::Small || M == CodeModel::Kernel))
7418     WrapperKind = X86ISD::WrapperRIP;
7419   else if (Subtarget->isPICStyleGOT())
7420     OpFlag = X86II::MO_GOTOFF;
7421   else if (Subtarget->isPICStyleStubPIC())
7422     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7423
7424   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7425                                           OpFlag);
7426   DebugLoc DL = JT->getDebugLoc();
7427   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7428
7429   // With PIC, the address is actually $g + Offset.
7430   if (OpFlag)
7431     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7432                          DAG.getNode(X86ISD::GlobalBaseReg,
7433                                      DebugLoc(), getPointerTy()),
7434                          Result);
7435
7436   return Result;
7437 }
7438
7439 SDValue
7440 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7441   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7442
7443   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7444   // global base reg.
7445   unsigned char OpFlag = 0;
7446   unsigned WrapperKind = X86ISD::Wrapper;
7447   CodeModel::Model M = getTargetMachine().getCodeModel();
7448
7449   if (Subtarget->isPICStyleRIPRel() &&
7450       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7451     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7452       OpFlag = X86II::MO_GOTPCREL;
7453     WrapperKind = X86ISD::WrapperRIP;
7454   } else if (Subtarget->isPICStyleGOT()) {
7455     OpFlag = X86II::MO_GOT;
7456   } else if (Subtarget->isPICStyleStubPIC()) {
7457     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7458   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7459     OpFlag = X86II::MO_DARWIN_NONLAZY;
7460   }
7461
7462   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7463
7464   DebugLoc DL = Op.getDebugLoc();
7465   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7466
7467
7468   // With PIC, the address is actually $g + Offset.
7469   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7470       !Subtarget->is64Bit()) {
7471     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7472                          DAG.getNode(X86ISD::GlobalBaseReg,
7473                                      DebugLoc(), getPointerTy()),
7474                          Result);
7475   }
7476
7477   // For symbols that require a load from a stub to get the address, emit the
7478   // load.
7479   if (isGlobalStubReference(OpFlag))
7480     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7481                          MachinePointerInfo::getGOT(), false, false, false, 0);
7482
7483   return Result;
7484 }
7485
7486 SDValue
7487 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7488   // Create the TargetBlockAddressAddress node.
7489   unsigned char OpFlags =
7490     Subtarget->ClassifyBlockAddressReference();
7491   CodeModel::Model M = getTargetMachine().getCodeModel();
7492   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7493   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7494   DebugLoc dl = Op.getDebugLoc();
7495   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7496                                              OpFlags);
7497
7498   if (Subtarget->isPICStyleRIPRel() &&
7499       (M == CodeModel::Small || M == CodeModel::Kernel))
7500     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7501   else
7502     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7503
7504   // With PIC, the address is actually $g + Offset.
7505   if (isGlobalRelativeToPICBase(OpFlags)) {
7506     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7507                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7508                          Result);
7509   }
7510
7511   return Result;
7512 }
7513
7514 SDValue
7515 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7516                                       int64_t Offset,
7517                                       SelectionDAG &DAG) const {
7518   // Create the TargetGlobalAddress node, folding in the constant
7519   // offset if it is legal.
7520   unsigned char OpFlags =
7521     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7522   CodeModel::Model M = getTargetMachine().getCodeModel();
7523   SDValue Result;
7524   if (OpFlags == X86II::MO_NO_FLAG &&
7525       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7526     // A direct static reference to a global.
7527     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7528     Offset = 0;
7529   } else {
7530     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7531   }
7532
7533   if (Subtarget->isPICStyleRIPRel() &&
7534       (M == CodeModel::Small || M == CodeModel::Kernel))
7535     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7536   else
7537     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7538
7539   // With PIC, the address is actually $g + Offset.
7540   if (isGlobalRelativeToPICBase(OpFlags)) {
7541     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7542                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7543                          Result);
7544   }
7545
7546   // For globals that require a load from a stub to get the address, emit the
7547   // load.
7548   if (isGlobalStubReference(OpFlags))
7549     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7550                          MachinePointerInfo::getGOT(), false, false, false, 0);
7551
7552   // If there was a non-zero offset that we didn't fold, create an explicit
7553   // addition for it.
7554   if (Offset != 0)
7555     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7556                          DAG.getConstant(Offset, getPointerTy()));
7557
7558   return Result;
7559 }
7560
7561 SDValue
7562 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7563   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7564   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7565   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7566 }
7567
7568 static SDValue
7569 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7570            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7571            unsigned char OperandFlags, bool LocalDynamic = false) {
7572   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7573   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7574   DebugLoc dl = GA->getDebugLoc();
7575   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7576                                            GA->getValueType(0),
7577                                            GA->getOffset(),
7578                                            OperandFlags);
7579
7580   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7581                                            : X86ISD::TLSADDR;
7582
7583   if (InFlag) {
7584     SDValue Ops[] = { Chain,  TGA, *InFlag };
7585     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7586   } else {
7587     SDValue Ops[]  = { Chain, TGA };
7588     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7589   }
7590
7591   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7592   MFI->setAdjustsStack(true);
7593
7594   SDValue Flag = Chain.getValue(1);
7595   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7596 }
7597
7598 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7599 static SDValue
7600 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7601                                 const EVT PtrVT) {
7602   SDValue InFlag;
7603   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7604   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7605                                    DAG.getNode(X86ISD::GlobalBaseReg,
7606                                                DebugLoc(), PtrVT), InFlag);
7607   InFlag = Chain.getValue(1);
7608
7609   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7610 }
7611
7612 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7613 static SDValue
7614 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7615                                 const EVT PtrVT) {
7616   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7617                     X86::RAX, X86II::MO_TLSGD);
7618 }
7619
7620 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7621                                            SelectionDAG &DAG,
7622                                            const EVT PtrVT,
7623                                            bool is64Bit) {
7624   DebugLoc dl = GA->getDebugLoc();
7625
7626   // Get the start address of the TLS block for this module.
7627   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7628       .getInfo<X86MachineFunctionInfo>();
7629   MFI->incNumLocalDynamicTLSAccesses();
7630
7631   SDValue Base;
7632   if (is64Bit) {
7633     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7634                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7635   } else {
7636     SDValue InFlag;
7637     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7638         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7639     InFlag = Chain.getValue(1);
7640     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7641                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7642   }
7643
7644   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7645   // of Base.
7646
7647   // Build x@dtpoff.
7648   unsigned char OperandFlags = X86II::MO_DTPOFF;
7649   unsigned WrapperKind = X86ISD::Wrapper;
7650   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7651                                            GA->getValueType(0),
7652                                            GA->getOffset(), OperandFlags);
7653   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7654
7655   // Add x@dtpoff with the base.
7656   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7657 }
7658
7659 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7660 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7661                                    const EVT PtrVT, TLSModel::Model model,
7662                                    bool is64Bit, bool isPIC) {
7663   DebugLoc dl = GA->getDebugLoc();
7664
7665   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7666   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7667                                                          is64Bit ? 257 : 256));
7668
7669   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7670                                       DAG.getIntPtrConstant(0),
7671                                       MachinePointerInfo(Ptr),
7672                                       false, false, false, 0);
7673
7674   unsigned char OperandFlags = 0;
7675   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7676   // initialexec.
7677   unsigned WrapperKind = X86ISD::Wrapper;
7678   if (model == TLSModel::LocalExec) {
7679     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7680   } else if (model == TLSModel::InitialExec) {
7681     if (is64Bit) {
7682       OperandFlags = X86II::MO_GOTTPOFF;
7683       WrapperKind = X86ISD::WrapperRIP;
7684     } else {
7685       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7686     }
7687   } else {
7688     llvm_unreachable("Unexpected model");
7689   }
7690
7691   // emit "addl x@ntpoff,%eax" (local exec)
7692   // or "addl x@indntpoff,%eax" (initial exec)
7693   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7694   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7695                                            GA->getValueType(0),
7696                                            GA->getOffset(), OperandFlags);
7697   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7698
7699   if (model == TLSModel::InitialExec) {
7700     if (isPIC && !is64Bit) {
7701       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7702                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7703                            Offset);
7704     }
7705
7706     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7707                          MachinePointerInfo::getGOT(), false, false, false,
7708                          0);
7709   }
7710
7711   // The address of the thread local variable is the add of the thread
7712   // pointer with the offset of the variable.
7713   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7714 }
7715
7716 SDValue
7717 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7718
7719   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7720   const GlobalValue *GV = GA->getGlobal();
7721
7722   if (Subtarget->isTargetELF()) {
7723     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7724
7725     switch (model) {
7726       case TLSModel::GeneralDynamic:
7727         if (Subtarget->is64Bit())
7728           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7729         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7730       case TLSModel::LocalDynamic:
7731         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7732                                            Subtarget->is64Bit());
7733       case TLSModel::InitialExec:
7734       case TLSModel::LocalExec:
7735         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7736                                    Subtarget->is64Bit(),
7737                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7738     }
7739     llvm_unreachable("Unknown TLS model.");
7740   }
7741
7742   if (Subtarget->isTargetDarwin()) {
7743     // Darwin only has one model of TLS.  Lower to that.
7744     unsigned char OpFlag = 0;
7745     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7746                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7747
7748     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7749     // global base reg.
7750     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7751                   !Subtarget->is64Bit();
7752     if (PIC32)
7753       OpFlag = X86II::MO_TLVP_PIC_BASE;
7754     else
7755       OpFlag = X86II::MO_TLVP;
7756     DebugLoc DL = Op.getDebugLoc();
7757     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7758                                                 GA->getValueType(0),
7759                                                 GA->getOffset(), OpFlag);
7760     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7761
7762     // With PIC32, the address is actually $g + Offset.
7763     if (PIC32)
7764       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7765                            DAG.getNode(X86ISD::GlobalBaseReg,
7766                                        DebugLoc(), getPointerTy()),
7767                            Offset);
7768
7769     // Lowering the machine isd will make sure everything is in the right
7770     // location.
7771     SDValue Chain = DAG.getEntryNode();
7772     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7773     SDValue Args[] = { Chain, Offset };
7774     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7775
7776     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7777     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7778     MFI->setAdjustsStack(true);
7779
7780     // And our return value (tls address) is in the standard call return value
7781     // location.
7782     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7783     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7784                               Chain.getValue(1));
7785   }
7786
7787   if (Subtarget->isTargetWindows()) {
7788     // Just use the implicit TLS architecture
7789     // Need to generate someting similar to:
7790     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7791     //                                  ; from TEB
7792     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7793     //   mov     rcx, qword [rdx+rcx*8]
7794     //   mov     eax, .tls$:tlsvar
7795     //   [rax+rcx] contains the address
7796     // Windows 64bit: gs:0x58
7797     // Windows 32bit: fs:__tls_array
7798
7799     // If GV is an alias then use the aliasee for determining
7800     // thread-localness.
7801     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7802       GV = GA->resolveAliasedGlobal(false);
7803     DebugLoc dl = GA->getDebugLoc();
7804     SDValue Chain = DAG.getEntryNode();
7805
7806     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7807     // %gs:0x58 (64-bit).
7808     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7809                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7810                                                              256)
7811                                         : Type::getInt32PtrTy(*DAG.getContext(),
7812                                                               257));
7813
7814     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7815                                         Subtarget->is64Bit()
7816                                         ? DAG.getIntPtrConstant(0x58)
7817                                         : DAG.getExternalSymbol("_tls_array",
7818                                                                 getPointerTy()),
7819                                         MachinePointerInfo(Ptr),
7820                                         false, false, false, 0);
7821
7822     // Load the _tls_index variable
7823     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7824     if (Subtarget->is64Bit())
7825       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7826                            IDX, MachinePointerInfo(), MVT::i32,
7827                            false, false, 0);
7828     else
7829       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7830                         false, false, false, 0);
7831
7832     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7833                                     getPointerTy());
7834     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7835
7836     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7837     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7838                       false, false, false, 0);
7839
7840     // Get the offset of start of .tls section
7841     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7842                                              GA->getValueType(0),
7843                                              GA->getOffset(), X86II::MO_SECREL);
7844     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7845
7846     // The address of the thread local variable is the add of the thread
7847     // pointer with the offset of the variable.
7848     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7849   }
7850
7851   llvm_unreachable("TLS not implemented for this target.");
7852 }
7853
7854
7855 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7856 /// and take a 2 x i32 value to shift plus a shift amount.
7857 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7858   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7859   EVT VT = Op.getValueType();
7860   unsigned VTBits = VT.getSizeInBits();
7861   DebugLoc dl = Op.getDebugLoc();
7862   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7863   SDValue ShOpLo = Op.getOperand(0);
7864   SDValue ShOpHi = Op.getOperand(1);
7865   SDValue ShAmt  = Op.getOperand(2);
7866   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7867                                      DAG.getConstant(VTBits - 1, MVT::i8))
7868                        : DAG.getConstant(0, VT);
7869
7870   SDValue Tmp2, Tmp3;
7871   if (Op.getOpcode() == ISD::SHL_PARTS) {
7872     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7873     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7874   } else {
7875     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7876     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7877   }
7878
7879   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7880                                 DAG.getConstant(VTBits, MVT::i8));
7881   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7882                              AndNode, DAG.getConstant(0, MVT::i8));
7883
7884   SDValue Hi, Lo;
7885   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7886   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7887   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7888
7889   if (Op.getOpcode() == ISD::SHL_PARTS) {
7890     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7891     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7892   } else {
7893     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7894     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7895   }
7896
7897   SDValue Ops[2] = { Lo, Hi };
7898   return DAG.getMergeValues(Ops, 2, dl);
7899 }
7900
7901 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7902                                            SelectionDAG &DAG) const {
7903   EVT SrcVT = Op.getOperand(0).getValueType();
7904
7905   if (SrcVT.isVector())
7906     return SDValue();
7907
7908   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7909          "Unknown SINT_TO_FP to lower!");
7910
7911   // These are really Legal; return the operand so the caller accepts it as
7912   // Legal.
7913   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7914     return Op;
7915   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7916       Subtarget->is64Bit()) {
7917     return Op;
7918   }
7919
7920   DebugLoc dl = Op.getDebugLoc();
7921   unsigned Size = SrcVT.getSizeInBits()/8;
7922   MachineFunction &MF = DAG.getMachineFunction();
7923   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7924   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7925   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7926                                StackSlot,
7927                                MachinePointerInfo::getFixedStack(SSFI),
7928                                false, false, 0);
7929   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7930 }
7931
7932 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7933                                      SDValue StackSlot,
7934                                      SelectionDAG &DAG) const {
7935   // Build the FILD
7936   DebugLoc DL = Op.getDebugLoc();
7937   SDVTList Tys;
7938   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7939   if (useSSE)
7940     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7941   else
7942     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7943
7944   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7945
7946   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7947   MachineMemOperand *MMO;
7948   if (FI) {
7949     int SSFI = FI->getIndex();
7950     MMO =
7951       DAG.getMachineFunction()
7952       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7953                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7954   } else {
7955     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7956     StackSlot = StackSlot.getOperand(1);
7957   }
7958   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7959   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7960                                            X86ISD::FILD, DL,
7961                                            Tys, Ops, array_lengthof(Ops),
7962                                            SrcVT, MMO);
7963
7964   if (useSSE) {
7965     Chain = Result.getValue(1);
7966     SDValue InFlag = Result.getValue(2);
7967
7968     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7969     // shouldn't be necessary except that RFP cannot be live across
7970     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7971     MachineFunction &MF = DAG.getMachineFunction();
7972     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7973     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7974     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7975     Tys = DAG.getVTList(MVT::Other);
7976     SDValue Ops[] = {
7977       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7978     };
7979     MachineMemOperand *MMO =
7980       DAG.getMachineFunction()
7981       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7982                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7983
7984     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7985                                     Ops, array_lengthof(Ops),
7986                                     Op.getValueType(), MMO);
7987     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7988                          MachinePointerInfo::getFixedStack(SSFI),
7989                          false, false, false, 0);
7990   }
7991
7992   return Result;
7993 }
7994
7995 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7996 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7997                                                SelectionDAG &DAG) const {
7998   // This algorithm is not obvious. Here it is what we're trying to output:
7999   /*
8000      movq       %rax,  %xmm0
8001      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8002      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8003      #ifdef __SSE3__
8004        haddpd   %xmm0, %xmm0
8005      #else
8006        pshufd   $0x4e, %xmm0, %xmm1
8007        addpd    %xmm1, %xmm0
8008      #endif
8009   */
8010
8011   DebugLoc dl = Op.getDebugLoc();
8012   LLVMContext *Context = DAG.getContext();
8013
8014   // Build some magic constants.
8015   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8016   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8017   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8018
8019   SmallVector<Constant*,2> CV1;
8020   CV1.push_back(
8021         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8022   CV1.push_back(
8023         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8024   Constant *C1 = ConstantVector::get(CV1);
8025   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8026
8027   // Load the 64-bit value into an XMM register.
8028   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8029                             Op.getOperand(0));
8030   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8031                               MachinePointerInfo::getConstantPool(),
8032                               false, false, false, 16);
8033   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8034                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8035                               CLod0);
8036
8037   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8038                               MachinePointerInfo::getConstantPool(),
8039                               false, false, false, 16);
8040   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8041   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8042   SDValue Result;
8043
8044   if (Subtarget->hasSSE3()) {
8045     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8046     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8047   } else {
8048     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8049     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8050                                            S2F, 0x4E, DAG);
8051     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8052                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8053                          Sub);
8054   }
8055
8056   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8057                      DAG.getIntPtrConstant(0));
8058 }
8059
8060 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8061 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8062                                                SelectionDAG &DAG) const {
8063   DebugLoc dl = Op.getDebugLoc();
8064   // FP constant to bias correct the final result.
8065   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8066                                    MVT::f64);
8067
8068   // Load the 32-bit value into an XMM register.
8069   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8070                              Op.getOperand(0));
8071
8072   // Zero out the upper parts of the register.
8073   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8074
8075   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8077                      DAG.getIntPtrConstant(0));
8078
8079   // Or the load with the bias.
8080   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8081                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8082                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8083                                                    MVT::v2f64, Load)),
8084                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8085                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8086                                                    MVT::v2f64, Bias)));
8087   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8088                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8089                    DAG.getIntPtrConstant(0));
8090
8091   // Subtract the bias.
8092   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8093
8094   // Handle final rounding.
8095   EVT DestVT = Op.getValueType();
8096
8097   if (DestVT.bitsLT(MVT::f64))
8098     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8099                        DAG.getIntPtrConstant(0));
8100   if (DestVT.bitsGT(MVT::f64))
8101     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8102
8103   // Handle final rounding.
8104   return Sub;
8105 }
8106
8107 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8108                                                SelectionDAG &DAG) const {
8109   SDValue N0 = Op.getOperand(0);
8110   EVT SVT = N0.getValueType();
8111   DebugLoc dl = Op.getDebugLoc();
8112
8113   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8114           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8115          "Custom UINT_TO_FP is not supported!");
8116
8117   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8118   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8119                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8120 }
8121
8122 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8123                                            SelectionDAG &DAG) const {
8124   SDValue N0 = Op.getOperand(0);
8125   DebugLoc dl = Op.getDebugLoc();
8126
8127   if (Op.getValueType().isVector())
8128     return lowerUINT_TO_FP_vec(Op, DAG);
8129
8130   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8131   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8132   // the optimization here.
8133   if (DAG.SignBitIsZero(N0))
8134     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8135
8136   EVT SrcVT = N0.getValueType();
8137   EVT DstVT = Op.getValueType();
8138   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8139     return LowerUINT_TO_FP_i64(Op, DAG);
8140   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8141     return LowerUINT_TO_FP_i32(Op, DAG);
8142   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8143     return SDValue();
8144
8145   // Make a 64-bit buffer, and use it to build an FILD.
8146   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8147   if (SrcVT == MVT::i32) {
8148     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8149     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8150                                      getPointerTy(), StackSlot, WordOff);
8151     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8152                                   StackSlot, MachinePointerInfo(),
8153                                   false, false, 0);
8154     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8155                                   OffsetSlot, MachinePointerInfo(),
8156                                   false, false, 0);
8157     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8158     return Fild;
8159   }
8160
8161   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8162   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8163                                StackSlot, MachinePointerInfo(),
8164                                false, false, 0);
8165   // For i64 source, we need to add the appropriate power of 2 if the input
8166   // was negative.  This is the same as the optimization in
8167   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8168   // we must be careful to do the computation in x87 extended precision, not
8169   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8170   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8171   MachineMemOperand *MMO =
8172     DAG.getMachineFunction()
8173     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8174                           MachineMemOperand::MOLoad, 8, 8);
8175
8176   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8177   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8178   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8179                                          MVT::i64, MMO);
8180
8181   APInt FF(32, 0x5F800000ULL);
8182
8183   // Check whether the sign bit is set.
8184   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8185                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8186                                  ISD::SETLT);
8187
8188   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8189   SDValue FudgePtr = DAG.getConstantPool(
8190                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8191                                          getPointerTy());
8192
8193   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8194   SDValue Zero = DAG.getIntPtrConstant(0);
8195   SDValue Four = DAG.getIntPtrConstant(4);
8196   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8197                                Zero, Four);
8198   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8199
8200   // Load the value out, extending it from f32 to f80.
8201   // FIXME: Avoid the extend by constructing the right constant pool?
8202   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8203                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8204                                  MVT::f32, false, false, 4);
8205   // Extend everything to 80 bits to force it to be done on x87.
8206   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8207   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8208 }
8209
8210 std::pair<SDValue,SDValue> X86TargetLowering::
8211 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8212   DebugLoc DL = Op.getDebugLoc();
8213
8214   EVT DstTy = Op.getValueType();
8215
8216   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8217     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8218     DstTy = MVT::i64;
8219   }
8220
8221   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8222          DstTy.getSimpleVT() >= MVT::i16 &&
8223          "Unknown FP_TO_INT to lower!");
8224
8225   // These are really Legal.
8226   if (DstTy == MVT::i32 &&
8227       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8228     return std::make_pair(SDValue(), SDValue());
8229   if (Subtarget->is64Bit() &&
8230       DstTy == MVT::i64 &&
8231       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8232     return std::make_pair(SDValue(), SDValue());
8233
8234   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8235   // stack slot, or into the FTOL runtime function.
8236   MachineFunction &MF = DAG.getMachineFunction();
8237   unsigned MemSize = DstTy.getSizeInBits()/8;
8238   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8239   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8240
8241   unsigned Opc;
8242   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8243     Opc = X86ISD::WIN_FTOL;
8244   else
8245     switch (DstTy.getSimpleVT().SimpleTy) {
8246     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8247     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8248     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8249     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8250     }
8251
8252   SDValue Chain = DAG.getEntryNode();
8253   SDValue Value = Op.getOperand(0);
8254   EVT TheVT = Op.getOperand(0).getValueType();
8255   // FIXME This causes a redundant load/store if the SSE-class value is already
8256   // in memory, such as if it is on the callstack.
8257   if (isScalarFPTypeInSSEReg(TheVT)) {
8258     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8259     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8260                          MachinePointerInfo::getFixedStack(SSFI),
8261                          false, false, 0);
8262     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8263     SDValue Ops[] = {
8264       Chain, StackSlot, DAG.getValueType(TheVT)
8265     };
8266
8267     MachineMemOperand *MMO =
8268       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8269                               MachineMemOperand::MOLoad, MemSize, MemSize);
8270     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8271                                     DstTy, MMO);
8272     Chain = Value.getValue(1);
8273     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8274     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8275   }
8276
8277   MachineMemOperand *MMO =
8278     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8279                             MachineMemOperand::MOStore, MemSize, MemSize);
8280
8281   if (Opc != X86ISD::WIN_FTOL) {
8282     // Build the FP_TO_INT*_IN_MEM
8283     SDValue Ops[] = { Chain, Value, StackSlot };
8284     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8285                                            Ops, 3, DstTy, MMO);
8286     return std::make_pair(FIST, StackSlot);
8287   } else {
8288     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8289       DAG.getVTList(MVT::Other, MVT::Glue),
8290       Chain, Value);
8291     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8292       MVT::i32, ftol.getValue(1));
8293     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8294       MVT::i32, eax.getValue(2));
8295     SDValue Ops[] = { eax, edx };
8296     SDValue pair = IsReplace
8297       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8298       : DAG.getMergeValues(Ops, 2, DL);
8299     return std::make_pair(pair, SDValue());
8300   }
8301 }
8302
8303 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8304   DebugLoc DL = Op.getDebugLoc();
8305   EVT VT = Op.getValueType();
8306   SDValue In = Op.getOperand(0);
8307   EVT SVT = In.getValueType();
8308
8309   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8310       VT.getVectorNumElements() != SVT.getVectorNumElements())
8311     return SDValue();
8312
8313   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8314
8315   // AVX2 has better support of integer extending.
8316   if (Subtarget->hasInt256())
8317     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8318
8319   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8320   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8321   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8322                            DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8323
8324   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8325 }
8326
8327 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8328   DebugLoc DL = Op.getDebugLoc();
8329   EVT VT = Op.getValueType();
8330   EVT SVT = Op.getOperand(0).getValueType();
8331
8332   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8333       VT.getVectorNumElements() != SVT.getVectorNumElements())
8334     return SDValue();
8335
8336   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8337
8338   unsigned NumElems = VT.getVectorNumElements();
8339   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8340                              NumElems * 2);
8341
8342   SDValue In = Op.getOperand(0);
8343   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8344   // Prepare truncation shuffle mask
8345   for (unsigned i = 0; i != NumElems; ++i)
8346     MaskVec[i] = i * 2;
8347   SDValue V = DAG.getVectorShuffle(NVT, DL,
8348                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8349                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8350   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8351                      DAG.getIntPtrConstant(0));
8352 }
8353
8354 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8355                                            SelectionDAG &DAG) const {
8356   if (Op.getValueType().isVector()) {
8357     if (Op.getValueType() == MVT::v8i16)
8358       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8359                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8360                                      MVT::v8i32, Op.getOperand(0)));
8361     return SDValue();
8362   }
8363
8364   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8365     /*IsSigned=*/ true, /*IsReplace=*/ false);
8366   SDValue FIST = Vals.first, StackSlot = Vals.second;
8367   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8368   if (FIST.getNode() == 0) return Op;
8369
8370   if (StackSlot.getNode())
8371     // Load the result.
8372     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8373                        FIST, StackSlot, MachinePointerInfo(),
8374                        false, false, false, 0);
8375
8376   // The node is the result.
8377   return FIST;
8378 }
8379
8380 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8381                                            SelectionDAG &DAG) const {
8382   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8383     /*IsSigned=*/ false, /*IsReplace=*/ false);
8384   SDValue FIST = Vals.first, StackSlot = Vals.second;
8385   assert(FIST.getNode() && "Unexpected failure");
8386
8387   if (StackSlot.getNode())
8388     // Load the result.
8389     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8390                        FIST, StackSlot, MachinePointerInfo(),
8391                        false, false, false, 0);
8392
8393   // The node is the result.
8394   return FIST;
8395 }
8396
8397 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8398                                           SelectionDAG &DAG) const {
8399   DebugLoc DL = Op.getDebugLoc();
8400   EVT VT = Op.getValueType();
8401   SDValue In = Op.getOperand(0);
8402   EVT SVT = In.getValueType();
8403
8404   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8405
8406   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8407                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8408                                  In, DAG.getUNDEF(SVT)));
8409 }
8410
8411 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8412   LLVMContext *Context = DAG.getContext();
8413   DebugLoc dl = Op.getDebugLoc();
8414   EVT VT = Op.getValueType();
8415   EVT EltVT = VT;
8416   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8417   if (VT.isVector()) {
8418     EltVT = VT.getVectorElementType();
8419     NumElts = VT.getVectorNumElements();
8420   }
8421   Constant *C;
8422   if (EltVT == MVT::f64)
8423     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8424   else
8425     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8426   C = ConstantVector::getSplat(NumElts, C);
8427   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8428   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8429   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8430                              MachinePointerInfo::getConstantPool(),
8431                              false, false, false, Alignment);
8432   if (VT.isVector()) {
8433     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8434     return DAG.getNode(ISD::BITCAST, dl, VT,
8435                        DAG.getNode(ISD::AND, dl, ANDVT,
8436                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8437                                                Op.getOperand(0)),
8438                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8439   }
8440   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8441 }
8442
8443 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8444   LLVMContext *Context = DAG.getContext();
8445   DebugLoc dl = Op.getDebugLoc();
8446   EVT VT = Op.getValueType();
8447   EVT EltVT = VT;
8448   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8449   if (VT.isVector()) {
8450     EltVT = VT.getVectorElementType();
8451     NumElts = VT.getVectorNumElements();
8452   }
8453   Constant *C;
8454   if (EltVT == MVT::f64)
8455     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8456   else
8457     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8458   C = ConstantVector::getSplat(NumElts, C);
8459   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8460   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8461   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8462                              MachinePointerInfo::getConstantPool(),
8463                              false, false, false, Alignment);
8464   if (VT.isVector()) {
8465     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8466     return DAG.getNode(ISD::BITCAST, dl, VT,
8467                        DAG.getNode(ISD::XOR, dl, XORVT,
8468                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8469                                                Op.getOperand(0)),
8470                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8471   }
8472
8473   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8474 }
8475
8476 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8477   LLVMContext *Context = DAG.getContext();
8478   SDValue Op0 = Op.getOperand(0);
8479   SDValue Op1 = Op.getOperand(1);
8480   DebugLoc dl = Op.getDebugLoc();
8481   EVT VT = Op.getValueType();
8482   EVT SrcVT = Op1.getValueType();
8483
8484   // If second operand is smaller, extend it first.
8485   if (SrcVT.bitsLT(VT)) {
8486     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8487     SrcVT = VT;
8488   }
8489   // And if it is bigger, shrink it first.
8490   if (SrcVT.bitsGT(VT)) {
8491     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8492     SrcVT = VT;
8493   }
8494
8495   // At this point the operands and the result should have the same
8496   // type, and that won't be f80 since that is not custom lowered.
8497
8498   // First get the sign bit of second operand.
8499   SmallVector<Constant*,4> CV;
8500   if (SrcVT == MVT::f64) {
8501     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8502     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8503   } else {
8504     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8505     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8506     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8507     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8508   }
8509   Constant *C = ConstantVector::get(CV);
8510   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8511   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8512                               MachinePointerInfo::getConstantPool(),
8513                               false, false, false, 16);
8514   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8515
8516   // Shift sign bit right or left if the two operands have different types.
8517   if (SrcVT.bitsGT(VT)) {
8518     // Op0 is MVT::f32, Op1 is MVT::f64.
8519     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8520     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8521                           DAG.getConstant(32, MVT::i32));
8522     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8523     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8524                           DAG.getIntPtrConstant(0));
8525   }
8526
8527   // Clear first operand sign bit.
8528   CV.clear();
8529   if (VT == MVT::f64) {
8530     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8531     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8532   } else {
8533     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8534     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8535     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8536     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8537   }
8538   C = ConstantVector::get(CV);
8539   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8540   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8541                               MachinePointerInfo::getConstantPool(),
8542                               false, false, false, 16);
8543   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8544
8545   // Or the value with the sign bit.
8546   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8547 }
8548
8549 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8550   SDValue N0 = Op.getOperand(0);
8551   DebugLoc dl = Op.getDebugLoc();
8552   EVT VT = Op.getValueType();
8553
8554   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8555   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8556                                   DAG.getConstant(1, VT));
8557   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8558 }
8559
8560 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8561 //
8562 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8563   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8564
8565   if (!Subtarget->hasSSE41())
8566     return SDValue();
8567
8568   if (!Op->hasOneUse())
8569     return SDValue();
8570
8571   SDNode *N = Op.getNode();
8572   DebugLoc DL = N->getDebugLoc();
8573
8574   SmallVector<SDValue, 8> Opnds;
8575   DenseMap<SDValue, unsigned> VecInMap;
8576   EVT VT = MVT::Other;
8577
8578   // Recognize a special case where a vector is casted into wide integer to
8579   // test all 0s.
8580   Opnds.push_back(N->getOperand(0));
8581   Opnds.push_back(N->getOperand(1));
8582
8583   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8584     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8585     // BFS traverse all OR'd operands.
8586     if (I->getOpcode() == ISD::OR) {
8587       Opnds.push_back(I->getOperand(0));
8588       Opnds.push_back(I->getOperand(1));
8589       // Re-evaluate the number of nodes to be traversed.
8590       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8591       continue;
8592     }
8593
8594     // Quit if a non-EXTRACT_VECTOR_ELT
8595     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8596       return SDValue();
8597
8598     // Quit if without a constant index.
8599     SDValue Idx = I->getOperand(1);
8600     if (!isa<ConstantSDNode>(Idx))
8601       return SDValue();
8602
8603     SDValue ExtractedFromVec = I->getOperand(0);
8604     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8605     if (M == VecInMap.end()) {
8606       VT = ExtractedFromVec.getValueType();
8607       // Quit if not 128/256-bit vector.
8608       if (!VT.is128BitVector() && !VT.is256BitVector())
8609         return SDValue();
8610       // Quit if not the same type.
8611       if (VecInMap.begin() != VecInMap.end() &&
8612           VT != VecInMap.begin()->first.getValueType())
8613         return SDValue();
8614       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8615     }
8616     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8617   }
8618
8619   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8620          "Not extracted from 128-/256-bit vector.");
8621
8622   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8623   SmallVector<SDValue, 8> VecIns;
8624
8625   for (DenseMap<SDValue, unsigned>::const_iterator
8626         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8627     // Quit if not all elements are used.
8628     if (I->second != FullMask)
8629       return SDValue();
8630     VecIns.push_back(I->first);
8631   }
8632
8633   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8634
8635   // Cast all vectors into TestVT for PTEST.
8636   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8637     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8638
8639   // If more than one full vectors are evaluated, OR them first before PTEST.
8640   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8641     // Each iteration will OR 2 nodes and append the result until there is only
8642     // 1 node left, i.e. the final OR'd value of all vectors.
8643     SDValue LHS = VecIns[Slot];
8644     SDValue RHS = VecIns[Slot + 1];
8645     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8646   }
8647
8648   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8649                      VecIns.back(), VecIns.back());
8650 }
8651
8652 /// Emit nodes that will be selected as "test Op0,Op0", or something
8653 /// equivalent.
8654 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8655                                     SelectionDAG &DAG) const {
8656   DebugLoc dl = Op.getDebugLoc();
8657
8658   // CF and OF aren't always set the way we want. Determine which
8659   // of these we need.
8660   bool NeedCF = false;
8661   bool NeedOF = false;
8662   switch (X86CC) {
8663   default: break;
8664   case X86::COND_A: case X86::COND_AE:
8665   case X86::COND_B: case X86::COND_BE:
8666     NeedCF = true;
8667     break;
8668   case X86::COND_G: case X86::COND_GE:
8669   case X86::COND_L: case X86::COND_LE:
8670   case X86::COND_O: case X86::COND_NO:
8671     NeedOF = true;
8672     break;
8673   }
8674
8675   // See if we can use the EFLAGS value from the operand instead of
8676   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8677   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8678   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8679     // Emit a CMP with 0, which is the TEST pattern.
8680     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8681                        DAG.getConstant(0, Op.getValueType()));
8682
8683   unsigned Opcode = 0;
8684   unsigned NumOperands = 0;
8685
8686   // Truncate operations may prevent the merge of the SETCC instruction
8687   // and the arithmetic intruction before it. Attempt to truncate the operands
8688   // of the arithmetic instruction and use a reduced bit-width instruction.
8689   bool NeedTruncation = false;
8690   SDValue ArithOp = Op;
8691   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8692     SDValue Arith = Op->getOperand(0);
8693     // Both the trunc and the arithmetic op need to have one user each.
8694     if (Arith->hasOneUse())
8695       switch (Arith.getOpcode()) {
8696         default: break;
8697         case ISD::ADD:
8698         case ISD::SUB:
8699         case ISD::AND:
8700         case ISD::OR:
8701         case ISD::XOR: {
8702           NeedTruncation = true;
8703           ArithOp = Arith;
8704         }
8705       }
8706   }
8707
8708   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8709   // which may be the result of a CAST.  We use the variable 'Op', which is the
8710   // non-casted variable when we check for possible users.
8711   switch (ArithOp.getOpcode()) {
8712   case ISD::ADD:
8713     // Due to an isel shortcoming, be conservative if this add is likely to be
8714     // selected as part of a load-modify-store instruction. When the root node
8715     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8716     // uses of other nodes in the match, such as the ADD in this case. This
8717     // leads to the ADD being left around and reselected, with the result being
8718     // two adds in the output.  Alas, even if none our users are stores, that
8719     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8720     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8721     // climbing the DAG back to the root, and it doesn't seem to be worth the
8722     // effort.
8723     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8724          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8725       if (UI->getOpcode() != ISD::CopyToReg &&
8726           UI->getOpcode() != ISD::SETCC &&
8727           UI->getOpcode() != ISD::STORE)
8728         goto default_case;
8729
8730     if (ConstantSDNode *C =
8731         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8732       // An add of one will be selected as an INC.
8733       if (C->getAPIntValue() == 1) {
8734         Opcode = X86ISD::INC;
8735         NumOperands = 1;
8736         break;
8737       }
8738
8739       // An add of negative one (subtract of one) will be selected as a DEC.
8740       if (C->getAPIntValue().isAllOnesValue()) {
8741         Opcode = X86ISD::DEC;
8742         NumOperands = 1;
8743         break;
8744       }
8745     }
8746
8747     // Otherwise use a regular EFLAGS-setting add.
8748     Opcode = X86ISD::ADD;
8749     NumOperands = 2;
8750     break;
8751   case ISD::AND: {
8752     // If the primary and result isn't used, don't bother using X86ISD::AND,
8753     // because a TEST instruction will be better.
8754     bool NonFlagUse = false;
8755     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8756            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8757       SDNode *User = *UI;
8758       unsigned UOpNo = UI.getOperandNo();
8759       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8760         // Look pass truncate.
8761         UOpNo = User->use_begin().getOperandNo();
8762         User = *User->use_begin();
8763       }
8764
8765       if (User->getOpcode() != ISD::BRCOND &&
8766           User->getOpcode() != ISD::SETCC &&
8767           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8768         NonFlagUse = true;
8769         break;
8770       }
8771     }
8772
8773     if (!NonFlagUse)
8774       break;
8775   }
8776     // FALL THROUGH
8777   case ISD::SUB:
8778   case ISD::OR:
8779   case ISD::XOR:
8780     // Due to the ISEL shortcoming noted above, be conservative if this op is
8781     // likely to be selected as part of a load-modify-store instruction.
8782     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8783            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8784       if (UI->getOpcode() == ISD::STORE)
8785         goto default_case;
8786
8787     // Otherwise use a regular EFLAGS-setting instruction.
8788     switch (ArithOp.getOpcode()) {
8789     default: llvm_unreachable("unexpected operator!");
8790     case ISD::SUB: Opcode = X86ISD::SUB; break;
8791     case ISD::XOR: Opcode = X86ISD::XOR; break;
8792     case ISD::AND: Opcode = X86ISD::AND; break;
8793     case ISD::OR: {
8794       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8795         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8796         if (EFLAGS.getNode())
8797           return EFLAGS;
8798       }
8799       Opcode = X86ISD::OR;
8800       break;
8801     }
8802     }
8803
8804     NumOperands = 2;
8805     break;
8806   case X86ISD::ADD:
8807   case X86ISD::SUB:
8808   case X86ISD::INC:
8809   case X86ISD::DEC:
8810   case X86ISD::OR:
8811   case X86ISD::XOR:
8812   case X86ISD::AND:
8813     return SDValue(Op.getNode(), 1);
8814   default:
8815   default_case:
8816     break;
8817   }
8818
8819   // If we found that truncation is beneficial, perform the truncation and
8820   // update 'Op'.
8821   if (NeedTruncation) {
8822     EVT VT = Op.getValueType();
8823     SDValue WideVal = Op->getOperand(0);
8824     EVT WideVT = WideVal.getValueType();
8825     unsigned ConvertedOp = 0;
8826     // Use a target machine opcode to prevent further DAGCombine
8827     // optimizations that may separate the arithmetic operations
8828     // from the setcc node.
8829     switch (WideVal.getOpcode()) {
8830       default: break;
8831       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8832       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8833       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8834       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8835       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8836     }
8837
8838     if (ConvertedOp) {
8839       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8840       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8841         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8842         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8843         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8844       }
8845     }
8846   }
8847
8848   if (Opcode == 0)
8849     // Emit a CMP with 0, which is the TEST pattern.
8850     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8851                        DAG.getConstant(0, Op.getValueType()));
8852
8853   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8854   SmallVector<SDValue, 4> Ops;
8855   for (unsigned i = 0; i != NumOperands; ++i)
8856     Ops.push_back(Op.getOperand(i));
8857
8858   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8859   DAG.ReplaceAllUsesWith(Op, New);
8860   return SDValue(New.getNode(), 1);
8861 }
8862
8863 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8864 /// equivalent.
8865 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8866                                    SelectionDAG &DAG) const {
8867   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8868     if (C->getAPIntValue() == 0)
8869       return EmitTest(Op0, X86CC, DAG);
8870
8871   DebugLoc dl = Op0.getDebugLoc();
8872   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8873        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8874     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8875     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8876     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8877                               Op0, Op1);
8878     return SDValue(Sub.getNode(), 1);
8879   }
8880   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8881 }
8882
8883 /// Convert a comparison if required by the subtarget.
8884 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8885                                                  SelectionDAG &DAG) const {
8886   // If the subtarget does not support the FUCOMI instruction, floating-point
8887   // comparisons have to be converted.
8888   if (Subtarget->hasCMov() ||
8889       Cmp.getOpcode() != X86ISD::CMP ||
8890       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8891       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8892     return Cmp;
8893
8894   // The instruction selector will select an FUCOM instruction instead of
8895   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8896   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8897   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8898   DebugLoc dl = Cmp.getDebugLoc();
8899   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8900   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8901   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8902                             DAG.getConstant(8, MVT::i8));
8903   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8904   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8905 }
8906
8907 static bool isAllOnes(SDValue V) {
8908   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8909   return C && C->isAllOnesValue();
8910 }
8911
8912 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8913 /// if it's possible.
8914 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8915                                      DebugLoc dl, SelectionDAG &DAG) const {
8916   SDValue Op0 = And.getOperand(0);
8917   SDValue Op1 = And.getOperand(1);
8918   if (Op0.getOpcode() == ISD::TRUNCATE)
8919     Op0 = Op0.getOperand(0);
8920   if (Op1.getOpcode() == ISD::TRUNCATE)
8921     Op1 = Op1.getOperand(0);
8922
8923   SDValue LHS, RHS;
8924   if (Op1.getOpcode() == ISD::SHL)
8925     std::swap(Op0, Op1);
8926   if (Op0.getOpcode() == ISD::SHL) {
8927     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8928       if (And00C->getZExtValue() == 1) {
8929         // If we looked past a truncate, check that it's only truncating away
8930         // known zeros.
8931         unsigned BitWidth = Op0.getValueSizeInBits();
8932         unsigned AndBitWidth = And.getValueSizeInBits();
8933         if (BitWidth > AndBitWidth) {
8934           APInt Zeros, Ones;
8935           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8936           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8937             return SDValue();
8938         }
8939         LHS = Op1;
8940         RHS = Op0.getOperand(1);
8941       }
8942   } else if (Op1.getOpcode() == ISD::Constant) {
8943     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8944     uint64_t AndRHSVal = AndRHS->getZExtValue();
8945     SDValue AndLHS = Op0;
8946
8947     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8948       LHS = AndLHS.getOperand(0);
8949       RHS = AndLHS.getOperand(1);
8950     }
8951
8952     // Use BT if the immediate can't be encoded in a TEST instruction.
8953     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8954       LHS = AndLHS;
8955       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8956     }
8957   }
8958
8959   if (LHS.getNode()) {
8960     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
8961     // the condition code later.
8962     bool Invert = false;
8963     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
8964       Invert = true;
8965       LHS = LHS.getOperand(0);
8966     }
8967
8968     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8969     // instruction.  Since the shift amount is in-range-or-undefined, we know
8970     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8971     // the encoding for the i16 version is larger than the i32 version.
8972     // Also promote i16 to i32 for performance / code size reason.
8973     if (LHS.getValueType() == MVT::i8 ||
8974         LHS.getValueType() == MVT::i16)
8975       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8976
8977     // If the operand types disagree, extend the shift amount to match.  Since
8978     // BT ignores high bits (like shifts) we can use anyextend.
8979     if (LHS.getValueType() != RHS.getValueType())
8980       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8981
8982     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8983     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8984     // Flip the condition if the LHS was a not instruction
8985     if (Invert)
8986       Cond = X86::GetOppositeBranchCondition(Cond);
8987     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8988                        DAG.getConstant(Cond, MVT::i8), BT);
8989   }
8990
8991   return SDValue();
8992 }
8993
8994 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8995
8996   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8997
8998   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8999   SDValue Op0 = Op.getOperand(0);
9000   SDValue Op1 = Op.getOperand(1);
9001   DebugLoc dl = Op.getDebugLoc();
9002   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9003
9004   // Optimize to BT if possible.
9005   // Lower (X & (1 << N)) == 0 to BT(X, N).
9006   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9007   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9008   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9009       Op1.getOpcode() == ISD::Constant &&
9010       cast<ConstantSDNode>(Op1)->isNullValue() &&
9011       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9012     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9013     if (NewSetCC.getNode())
9014       return NewSetCC;
9015   }
9016
9017   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9018   // these.
9019   if (Op1.getOpcode() == ISD::Constant &&
9020       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9021        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9022       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9023
9024     // If the input is a setcc, then reuse the input setcc or use a new one with
9025     // the inverted condition.
9026     if (Op0.getOpcode() == X86ISD::SETCC) {
9027       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9028       bool Invert = (CC == ISD::SETNE) ^
9029         cast<ConstantSDNode>(Op1)->isNullValue();
9030       if (!Invert) return Op0;
9031
9032       CCode = X86::GetOppositeBranchCondition(CCode);
9033       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9034                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9035     }
9036   }
9037
9038   bool isFP = Op1.getValueType().isFloatingPoint();
9039   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9040   if (X86CC == X86::COND_INVALID)
9041     return SDValue();
9042
9043   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9044   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9045   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9046                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9047 }
9048
9049 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9050 // ones, and then concatenate the result back.
9051 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9052   EVT VT = Op.getValueType();
9053
9054   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9055          "Unsupported value type for operation");
9056
9057   unsigned NumElems = VT.getVectorNumElements();
9058   DebugLoc dl = Op.getDebugLoc();
9059   SDValue CC = Op.getOperand(2);
9060
9061   // Extract the LHS vectors
9062   SDValue LHS = Op.getOperand(0);
9063   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9064   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9065
9066   // Extract the RHS vectors
9067   SDValue RHS = Op.getOperand(1);
9068   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9069   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9070
9071   // Issue the operation on the smaller types and concatenate the result back
9072   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9073   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9074   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9075                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9076                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9077 }
9078
9079
9080 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9081   SDValue Cond;
9082   SDValue Op0 = Op.getOperand(0);
9083   SDValue Op1 = Op.getOperand(1);
9084   SDValue CC = Op.getOperand(2);
9085   EVT VT = Op.getValueType();
9086   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9087   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9088   DebugLoc dl = Op.getDebugLoc();
9089
9090   if (isFP) {
9091 #ifndef NDEBUG
9092     EVT EltVT = Op0.getValueType().getVectorElementType();
9093     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9094 #endif
9095
9096     unsigned SSECC;
9097     bool Swap = false;
9098
9099     // SSE Condition code mapping:
9100     //  0 - EQ
9101     //  1 - LT
9102     //  2 - LE
9103     //  3 - UNORD
9104     //  4 - NEQ
9105     //  5 - NLT
9106     //  6 - NLE
9107     //  7 - ORD
9108     switch (SetCCOpcode) {
9109     default: llvm_unreachable("Unexpected SETCC condition");
9110     case ISD::SETOEQ:
9111     case ISD::SETEQ:  SSECC = 0; break;
9112     case ISD::SETOGT:
9113     case ISD::SETGT: Swap = true; // Fallthrough
9114     case ISD::SETLT:
9115     case ISD::SETOLT: SSECC = 1; break;
9116     case ISD::SETOGE:
9117     case ISD::SETGE: Swap = true; // Fallthrough
9118     case ISD::SETLE:
9119     case ISD::SETOLE: SSECC = 2; break;
9120     case ISD::SETUO:  SSECC = 3; break;
9121     case ISD::SETUNE:
9122     case ISD::SETNE:  SSECC = 4; break;
9123     case ISD::SETULE: Swap = true; // Fallthrough
9124     case ISD::SETUGE: SSECC = 5; break;
9125     case ISD::SETULT: Swap = true; // Fallthrough
9126     case ISD::SETUGT: SSECC = 6; break;
9127     case ISD::SETO:   SSECC = 7; break;
9128     case ISD::SETUEQ:
9129     case ISD::SETONE: SSECC = 8; break;
9130     }
9131     if (Swap)
9132       std::swap(Op0, Op1);
9133
9134     // In the two special cases we can't handle, emit two comparisons.
9135     if (SSECC == 8) {
9136       unsigned CC0, CC1;
9137       unsigned CombineOpc;
9138       if (SetCCOpcode == ISD::SETUEQ) {
9139         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9140       } else {
9141         assert(SetCCOpcode == ISD::SETONE);
9142         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9143       }
9144
9145       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9146                                  DAG.getConstant(CC0, MVT::i8));
9147       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9148                                  DAG.getConstant(CC1, MVT::i8));
9149       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9150     }
9151     // Handle all other FP comparisons here.
9152     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9153                        DAG.getConstant(SSECC, MVT::i8));
9154   }
9155
9156   // Break 256-bit integer vector compare into smaller ones.
9157   if (VT.is256BitVector() && !Subtarget->hasInt256())
9158     return Lower256IntVSETCC(Op, DAG);
9159
9160   // We are handling one of the integer comparisons here.  Since SSE only has
9161   // GT and EQ comparisons for integer, swapping operands and multiple
9162   // operations may be required for some comparisons.
9163   unsigned Opc;
9164   bool Swap = false, Invert = false, FlipSigns = false;
9165
9166   switch (SetCCOpcode) {
9167   default: llvm_unreachable("Unexpected SETCC condition");
9168   case ISD::SETNE:  Invert = true;
9169   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9170   case ISD::SETLT:  Swap = true;
9171   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9172   case ISD::SETGE:  Swap = true;
9173   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9174   case ISD::SETULT: Swap = true;
9175   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9176   case ISD::SETUGE: Swap = true;
9177   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9178   }
9179   if (Swap)
9180     std::swap(Op0, Op1);
9181
9182   // Check that the operation in question is available (most are plain SSE2,
9183   // but PCMPGTQ and PCMPEQQ have different requirements).
9184   if (VT == MVT::v2i64) {
9185     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9186       return SDValue();
9187     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9188       return SDValue();
9189   }
9190
9191   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9192   // bits of the inputs before performing those operations.
9193   if (FlipSigns) {
9194     EVT EltVT = VT.getVectorElementType();
9195     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9196                                       EltVT);
9197     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9198     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9199                                     SignBits.size());
9200     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9201     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9202   }
9203
9204   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9205
9206   // If the logical-not of the result is required, perform that now.
9207   if (Invert)
9208     Result = DAG.getNOT(dl, Result, VT);
9209
9210   return Result;
9211 }
9212
9213 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9214 static bool isX86LogicalCmp(SDValue Op) {
9215   unsigned Opc = Op.getNode()->getOpcode();
9216   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9217       Opc == X86ISD::SAHF)
9218     return true;
9219   if (Op.getResNo() == 1 &&
9220       (Opc == X86ISD::ADD ||
9221        Opc == X86ISD::SUB ||
9222        Opc == X86ISD::ADC ||
9223        Opc == X86ISD::SBB ||
9224        Opc == X86ISD::SMUL ||
9225        Opc == X86ISD::UMUL ||
9226        Opc == X86ISD::INC ||
9227        Opc == X86ISD::DEC ||
9228        Opc == X86ISD::OR ||
9229        Opc == X86ISD::XOR ||
9230        Opc == X86ISD::AND))
9231     return true;
9232
9233   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9234     return true;
9235
9236   return false;
9237 }
9238
9239 static bool isZero(SDValue V) {
9240   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9241   return C && C->isNullValue();
9242 }
9243
9244 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9245   if (V.getOpcode() != ISD::TRUNCATE)
9246     return false;
9247
9248   SDValue VOp0 = V.getOperand(0);
9249   unsigned InBits = VOp0.getValueSizeInBits();
9250   unsigned Bits = V.getValueSizeInBits();
9251   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9252 }
9253
9254 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9255   bool addTest = true;
9256   SDValue Cond  = Op.getOperand(0);
9257   SDValue Op1 = Op.getOperand(1);
9258   SDValue Op2 = Op.getOperand(2);
9259   DebugLoc DL = Op.getDebugLoc();
9260   SDValue CC;
9261
9262   if (Cond.getOpcode() == ISD::SETCC) {
9263     SDValue NewCond = LowerSETCC(Cond, DAG);
9264     if (NewCond.getNode())
9265       Cond = NewCond;
9266   }
9267
9268   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9269   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9270   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9271   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9272   if (Cond.getOpcode() == X86ISD::SETCC &&
9273       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9274       isZero(Cond.getOperand(1).getOperand(1))) {
9275     SDValue Cmp = Cond.getOperand(1);
9276
9277     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9278
9279     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9280         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9281       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9282
9283       SDValue CmpOp0 = Cmp.getOperand(0);
9284       // Apply further optimizations for special cases
9285       // (select (x != 0), -1, 0) -> neg & sbb
9286       // (select (x == 0), 0, -1) -> neg & sbb
9287       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9288         if (YC->isNullValue() &&
9289             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9290           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9291           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9292                                     DAG.getConstant(0, CmpOp0.getValueType()),
9293                                     CmpOp0);
9294           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9295                                     DAG.getConstant(X86::COND_B, MVT::i8),
9296                                     SDValue(Neg.getNode(), 1));
9297           return Res;
9298         }
9299
9300       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9301                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9302       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9303
9304       SDValue Res =   // Res = 0 or -1.
9305         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9306                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9307
9308       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9309         Res = DAG.getNOT(DL, Res, Res.getValueType());
9310
9311       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9312       if (N2C == 0 || !N2C->isNullValue())
9313         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9314       return Res;
9315     }
9316   }
9317
9318   // Look past (and (setcc_carry (cmp ...)), 1).
9319   if (Cond.getOpcode() == ISD::AND &&
9320       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9321     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9322     if (C && C->getAPIntValue() == 1)
9323       Cond = Cond.getOperand(0);
9324   }
9325
9326   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9327   // setting operand in place of the X86ISD::SETCC.
9328   unsigned CondOpcode = Cond.getOpcode();
9329   if (CondOpcode == X86ISD::SETCC ||
9330       CondOpcode == X86ISD::SETCC_CARRY) {
9331     CC = Cond.getOperand(0);
9332
9333     SDValue Cmp = Cond.getOperand(1);
9334     unsigned Opc = Cmp.getOpcode();
9335     EVT VT = Op.getValueType();
9336
9337     bool IllegalFPCMov = false;
9338     if (VT.isFloatingPoint() && !VT.isVector() &&
9339         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9340       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9341
9342     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9343         Opc == X86ISD::BT) { // FIXME
9344       Cond = Cmp;
9345       addTest = false;
9346     }
9347   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9348              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9349              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9350               Cond.getOperand(0).getValueType() != MVT::i8)) {
9351     SDValue LHS = Cond.getOperand(0);
9352     SDValue RHS = Cond.getOperand(1);
9353     unsigned X86Opcode;
9354     unsigned X86Cond;
9355     SDVTList VTs;
9356     switch (CondOpcode) {
9357     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9358     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9359     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9360     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9361     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9362     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9363     default: llvm_unreachable("unexpected overflowing operator");
9364     }
9365     if (CondOpcode == ISD::UMULO)
9366       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9367                           MVT::i32);
9368     else
9369       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9370
9371     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9372
9373     if (CondOpcode == ISD::UMULO)
9374       Cond = X86Op.getValue(2);
9375     else
9376       Cond = X86Op.getValue(1);
9377
9378     CC = DAG.getConstant(X86Cond, MVT::i8);
9379     addTest = false;
9380   }
9381
9382   if (addTest) {
9383     // Look pass the truncate if the high bits are known zero.
9384     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9385         Cond = Cond.getOperand(0);
9386
9387     // We know the result of AND is compared against zero. Try to match
9388     // it to BT.
9389     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9390       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9391       if (NewSetCC.getNode()) {
9392         CC = NewSetCC.getOperand(0);
9393         Cond = NewSetCC.getOperand(1);
9394         addTest = false;
9395       }
9396     }
9397   }
9398
9399   if (addTest) {
9400     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9401     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9402   }
9403
9404   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9405   // a <  b ?  0 : -1 -> RES = setcc_carry
9406   // a >= b ? -1 :  0 -> RES = setcc_carry
9407   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9408   if (Cond.getOpcode() == X86ISD::SUB) {
9409     Cond = ConvertCmpIfNecessary(Cond, DAG);
9410     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9411
9412     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9413         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9414       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9415                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9416       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9417         return DAG.getNOT(DL, Res, Res.getValueType());
9418       return Res;
9419     }
9420   }
9421
9422   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9423   // widen the cmov and push the truncate through. This avoids introducing a new
9424   // branch during isel and doesn't add any extensions.
9425   if (Op.getValueType() == MVT::i8 &&
9426       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9427     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9428     if (T1.getValueType() == T2.getValueType() &&
9429         // Blacklist CopyFromReg to avoid partial register stalls.
9430         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9431       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9432       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9433       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9434     }
9435   }
9436
9437   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9438   // condition is true.
9439   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9440   SDValue Ops[] = { Op2, Op1, CC, Cond };
9441   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9442 }
9443
9444 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9445 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9446 // from the AND / OR.
9447 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9448   Opc = Op.getOpcode();
9449   if (Opc != ISD::OR && Opc != ISD::AND)
9450     return false;
9451   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9452           Op.getOperand(0).hasOneUse() &&
9453           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9454           Op.getOperand(1).hasOneUse());
9455 }
9456
9457 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9458 // 1 and that the SETCC node has a single use.
9459 static bool isXor1OfSetCC(SDValue Op) {
9460   if (Op.getOpcode() != ISD::XOR)
9461     return false;
9462   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9463   if (N1C && N1C->getAPIntValue() == 1) {
9464     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9465       Op.getOperand(0).hasOneUse();
9466   }
9467   return false;
9468 }
9469
9470 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9471   bool addTest = true;
9472   SDValue Chain = Op.getOperand(0);
9473   SDValue Cond  = Op.getOperand(1);
9474   SDValue Dest  = Op.getOperand(2);
9475   DebugLoc dl = Op.getDebugLoc();
9476   SDValue CC;
9477   bool Inverted = false;
9478
9479   if (Cond.getOpcode() == ISD::SETCC) {
9480     // Check for setcc([su]{add,sub,mul}o == 0).
9481     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9482         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9483         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9484         Cond.getOperand(0).getResNo() == 1 &&
9485         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9486          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9487          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9488          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9489          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9490          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9491       Inverted = true;
9492       Cond = Cond.getOperand(0);
9493     } else {
9494       SDValue NewCond = LowerSETCC(Cond, DAG);
9495       if (NewCond.getNode())
9496         Cond = NewCond;
9497     }
9498   }
9499 #if 0
9500   // FIXME: LowerXALUO doesn't handle these!!
9501   else if (Cond.getOpcode() == X86ISD::ADD  ||
9502            Cond.getOpcode() == X86ISD::SUB  ||
9503            Cond.getOpcode() == X86ISD::SMUL ||
9504            Cond.getOpcode() == X86ISD::UMUL)
9505     Cond = LowerXALUO(Cond, DAG);
9506 #endif
9507
9508   // Look pass (and (setcc_carry (cmp ...)), 1).
9509   if (Cond.getOpcode() == ISD::AND &&
9510       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9511     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9512     if (C && C->getAPIntValue() == 1)
9513       Cond = Cond.getOperand(0);
9514   }
9515
9516   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9517   // setting operand in place of the X86ISD::SETCC.
9518   unsigned CondOpcode = Cond.getOpcode();
9519   if (CondOpcode == X86ISD::SETCC ||
9520       CondOpcode == X86ISD::SETCC_CARRY) {
9521     CC = Cond.getOperand(0);
9522
9523     SDValue Cmp = Cond.getOperand(1);
9524     unsigned Opc = Cmp.getOpcode();
9525     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9526     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9527       Cond = Cmp;
9528       addTest = false;
9529     } else {
9530       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9531       default: break;
9532       case X86::COND_O:
9533       case X86::COND_B:
9534         // These can only come from an arithmetic instruction with overflow,
9535         // e.g. SADDO, UADDO.
9536         Cond = Cond.getNode()->getOperand(1);
9537         addTest = false;
9538         break;
9539       }
9540     }
9541   }
9542   CondOpcode = Cond.getOpcode();
9543   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9544       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9545       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9546        Cond.getOperand(0).getValueType() != MVT::i8)) {
9547     SDValue LHS = Cond.getOperand(0);
9548     SDValue RHS = Cond.getOperand(1);
9549     unsigned X86Opcode;
9550     unsigned X86Cond;
9551     SDVTList VTs;
9552     switch (CondOpcode) {
9553     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9554     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9555     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9556     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9557     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9558     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9559     default: llvm_unreachable("unexpected overflowing operator");
9560     }
9561     if (Inverted)
9562       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9563     if (CondOpcode == ISD::UMULO)
9564       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9565                           MVT::i32);
9566     else
9567       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9568
9569     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9570
9571     if (CondOpcode == ISD::UMULO)
9572       Cond = X86Op.getValue(2);
9573     else
9574       Cond = X86Op.getValue(1);
9575
9576     CC = DAG.getConstant(X86Cond, MVT::i8);
9577     addTest = false;
9578   } else {
9579     unsigned CondOpc;
9580     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9581       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9582       if (CondOpc == ISD::OR) {
9583         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9584         // two branches instead of an explicit OR instruction with a
9585         // separate test.
9586         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9587             isX86LogicalCmp(Cmp)) {
9588           CC = Cond.getOperand(0).getOperand(0);
9589           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9590                               Chain, Dest, CC, Cmp);
9591           CC = Cond.getOperand(1).getOperand(0);
9592           Cond = Cmp;
9593           addTest = false;
9594         }
9595       } else { // ISD::AND
9596         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9597         // two branches instead of an explicit AND instruction with a
9598         // separate test. However, we only do this if this block doesn't
9599         // have a fall-through edge, because this requires an explicit
9600         // jmp when the condition is false.
9601         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9602             isX86LogicalCmp(Cmp) &&
9603             Op.getNode()->hasOneUse()) {
9604           X86::CondCode CCode =
9605             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9606           CCode = X86::GetOppositeBranchCondition(CCode);
9607           CC = DAG.getConstant(CCode, MVT::i8);
9608           SDNode *User = *Op.getNode()->use_begin();
9609           // Look for an unconditional branch following this conditional branch.
9610           // We need this because we need to reverse the successors in order
9611           // to implement FCMP_OEQ.
9612           if (User->getOpcode() == ISD::BR) {
9613             SDValue FalseBB = User->getOperand(1);
9614             SDNode *NewBR =
9615               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9616             assert(NewBR == User);
9617             (void)NewBR;
9618             Dest = FalseBB;
9619
9620             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9621                                 Chain, Dest, CC, Cmp);
9622             X86::CondCode CCode =
9623               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9624             CCode = X86::GetOppositeBranchCondition(CCode);
9625             CC = DAG.getConstant(CCode, MVT::i8);
9626             Cond = Cmp;
9627             addTest = false;
9628           }
9629         }
9630       }
9631     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9632       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9633       // It should be transformed during dag combiner except when the condition
9634       // is set by a arithmetics with overflow node.
9635       X86::CondCode CCode =
9636         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9637       CCode = X86::GetOppositeBranchCondition(CCode);
9638       CC = DAG.getConstant(CCode, MVT::i8);
9639       Cond = Cond.getOperand(0).getOperand(1);
9640       addTest = false;
9641     } else if (Cond.getOpcode() == ISD::SETCC &&
9642                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9643       // For FCMP_OEQ, we can emit
9644       // two branches instead of an explicit AND instruction with a
9645       // separate test. However, we only do this if this block doesn't
9646       // have a fall-through edge, because this requires an explicit
9647       // jmp when the condition is false.
9648       if (Op.getNode()->hasOneUse()) {
9649         SDNode *User = *Op.getNode()->use_begin();
9650         // Look for an unconditional branch following this conditional branch.
9651         // We need this because we need to reverse the successors in order
9652         // to implement FCMP_OEQ.
9653         if (User->getOpcode() == ISD::BR) {
9654           SDValue FalseBB = User->getOperand(1);
9655           SDNode *NewBR =
9656             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9657           assert(NewBR == User);
9658           (void)NewBR;
9659           Dest = FalseBB;
9660
9661           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9662                                     Cond.getOperand(0), Cond.getOperand(1));
9663           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9664           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9665           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9666                               Chain, Dest, CC, Cmp);
9667           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9668           Cond = Cmp;
9669           addTest = false;
9670         }
9671       }
9672     } else if (Cond.getOpcode() == ISD::SETCC &&
9673                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9674       // For FCMP_UNE, we can emit
9675       // two branches instead of an explicit AND instruction with a
9676       // separate test. However, we only do this if this block doesn't
9677       // have a fall-through edge, because this requires an explicit
9678       // jmp when the condition is false.
9679       if (Op.getNode()->hasOneUse()) {
9680         SDNode *User = *Op.getNode()->use_begin();
9681         // Look for an unconditional branch following this conditional branch.
9682         // We need this because we need to reverse the successors in order
9683         // to implement FCMP_UNE.
9684         if (User->getOpcode() == ISD::BR) {
9685           SDValue FalseBB = User->getOperand(1);
9686           SDNode *NewBR =
9687             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9688           assert(NewBR == User);
9689           (void)NewBR;
9690
9691           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9692                                     Cond.getOperand(0), Cond.getOperand(1));
9693           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9694           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9695           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9696                               Chain, Dest, CC, Cmp);
9697           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9698           Cond = Cmp;
9699           addTest = false;
9700           Dest = FalseBB;
9701         }
9702       }
9703     }
9704   }
9705
9706   if (addTest) {
9707     // Look pass the truncate if the high bits are known zero.
9708     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9709         Cond = Cond.getOperand(0);
9710
9711     // We know the result of AND is compared against zero. Try to match
9712     // it to BT.
9713     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9714       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9715       if (NewSetCC.getNode()) {
9716         CC = NewSetCC.getOperand(0);
9717         Cond = NewSetCC.getOperand(1);
9718         addTest = false;
9719       }
9720     }
9721   }
9722
9723   if (addTest) {
9724     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9725     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9726   }
9727   Cond = ConvertCmpIfNecessary(Cond, DAG);
9728   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9729                      Chain, Dest, CC, Cond);
9730 }
9731
9732
9733 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9734 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9735 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9736 // that the guard pages used by the OS virtual memory manager are allocated in
9737 // correct sequence.
9738 SDValue
9739 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9740                                            SelectionDAG &DAG) const {
9741   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9742           getTargetMachine().Options.EnableSegmentedStacks) &&
9743          "This should be used only on Windows targets or when segmented stacks "
9744          "are being used");
9745   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9746   DebugLoc dl = Op.getDebugLoc();
9747
9748   // Get the inputs.
9749   SDValue Chain = Op.getOperand(0);
9750   SDValue Size  = Op.getOperand(1);
9751   // FIXME: Ensure alignment here
9752
9753   bool Is64Bit = Subtarget->is64Bit();
9754   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9755
9756   if (getTargetMachine().Options.EnableSegmentedStacks) {
9757     MachineFunction &MF = DAG.getMachineFunction();
9758     MachineRegisterInfo &MRI = MF.getRegInfo();
9759
9760     if (Is64Bit) {
9761       // The 64 bit implementation of segmented stacks needs to clobber both r10
9762       // r11. This makes it impossible to use it along with nested parameters.
9763       const Function *F = MF.getFunction();
9764
9765       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9766            I != E; ++I)
9767         if (I->hasNestAttr())
9768           report_fatal_error("Cannot use segmented stacks with functions that "
9769                              "have nested arguments.");
9770     }
9771
9772     const TargetRegisterClass *AddrRegClass =
9773       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9774     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9775     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9776     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9777                                 DAG.getRegister(Vreg, SPTy));
9778     SDValue Ops1[2] = { Value, Chain };
9779     return DAG.getMergeValues(Ops1, 2, dl);
9780   } else {
9781     SDValue Flag;
9782     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9783
9784     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9785     Flag = Chain.getValue(1);
9786     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9787
9788     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9789     Flag = Chain.getValue(1);
9790
9791     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
9792                                SPTy).getValue(1);
9793
9794     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9795     return DAG.getMergeValues(Ops1, 2, dl);
9796   }
9797 }
9798
9799 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9800   MachineFunction &MF = DAG.getMachineFunction();
9801   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9802
9803   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9804   DebugLoc DL = Op.getDebugLoc();
9805
9806   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9807     // vastart just stores the address of the VarArgsFrameIndex slot into the
9808     // memory location argument.
9809     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9810                                    getPointerTy());
9811     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9812                         MachinePointerInfo(SV), false, false, 0);
9813   }
9814
9815   // __va_list_tag:
9816   //   gp_offset         (0 - 6 * 8)
9817   //   fp_offset         (48 - 48 + 8 * 16)
9818   //   overflow_arg_area (point to parameters coming in memory).
9819   //   reg_save_area
9820   SmallVector<SDValue, 8> MemOps;
9821   SDValue FIN = Op.getOperand(1);
9822   // Store gp_offset
9823   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9824                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9825                                                MVT::i32),
9826                                FIN, MachinePointerInfo(SV), false, false, 0);
9827   MemOps.push_back(Store);
9828
9829   // Store fp_offset
9830   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9831                     FIN, DAG.getIntPtrConstant(4));
9832   Store = DAG.getStore(Op.getOperand(0), DL,
9833                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9834                                        MVT::i32),
9835                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9836   MemOps.push_back(Store);
9837
9838   // Store ptr to overflow_arg_area
9839   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9840                     FIN, DAG.getIntPtrConstant(4));
9841   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9842                                     getPointerTy());
9843   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9844                        MachinePointerInfo(SV, 8),
9845                        false, false, 0);
9846   MemOps.push_back(Store);
9847
9848   // Store ptr to reg_save_area.
9849   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9850                     FIN, DAG.getIntPtrConstant(8));
9851   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9852                                     getPointerTy());
9853   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9854                        MachinePointerInfo(SV, 16), false, false, 0);
9855   MemOps.push_back(Store);
9856   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9857                      &MemOps[0], MemOps.size());
9858 }
9859
9860 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9861   assert(Subtarget->is64Bit() &&
9862          "LowerVAARG only handles 64-bit va_arg!");
9863   assert((Subtarget->isTargetLinux() ||
9864           Subtarget->isTargetDarwin()) &&
9865           "Unhandled target in LowerVAARG");
9866   assert(Op.getNode()->getNumOperands() == 4);
9867   SDValue Chain = Op.getOperand(0);
9868   SDValue SrcPtr = Op.getOperand(1);
9869   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9870   unsigned Align = Op.getConstantOperandVal(3);
9871   DebugLoc dl = Op.getDebugLoc();
9872
9873   EVT ArgVT = Op.getNode()->getValueType(0);
9874   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9875   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9876   uint8_t ArgMode;
9877
9878   // Decide which area this value should be read from.
9879   // TODO: Implement the AMD64 ABI in its entirety. This simple
9880   // selection mechanism works only for the basic types.
9881   if (ArgVT == MVT::f80) {
9882     llvm_unreachable("va_arg for f80 not yet implemented");
9883   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9884     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9885   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9886     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9887   } else {
9888     llvm_unreachable("Unhandled argument type in LowerVAARG");
9889   }
9890
9891   if (ArgMode == 2) {
9892     // Sanity Check: Make sure using fp_offset makes sense.
9893     assert(!getTargetMachine().Options.UseSoftFloat &&
9894            !(DAG.getMachineFunction()
9895                 .getFunction()->getFnAttributes()
9896                 .hasAttribute(Attribute::NoImplicitFloat)) &&
9897            Subtarget->hasSSE1());
9898   }
9899
9900   // Insert VAARG_64 node into the DAG
9901   // VAARG_64 returns two values: Variable Argument Address, Chain
9902   SmallVector<SDValue, 11> InstOps;
9903   InstOps.push_back(Chain);
9904   InstOps.push_back(SrcPtr);
9905   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9906   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9907   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9908   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9909   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9910                                           VTs, &InstOps[0], InstOps.size(),
9911                                           MVT::i64,
9912                                           MachinePointerInfo(SV),
9913                                           /*Align=*/0,
9914                                           /*Volatile=*/false,
9915                                           /*ReadMem=*/true,
9916                                           /*WriteMem=*/true);
9917   Chain = VAARG.getValue(1);
9918
9919   // Load the next argument and return it
9920   return DAG.getLoad(ArgVT, dl,
9921                      Chain,
9922                      VAARG,
9923                      MachinePointerInfo(),
9924                      false, false, false, 0);
9925 }
9926
9927 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9928                            SelectionDAG &DAG) {
9929   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9930   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9931   SDValue Chain = Op.getOperand(0);
9932   SDValue DstPtr = Op.getOperand(1);
9933   SDValue SrcPtr = Op.getOperand(2);
9934   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9935   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9936   DebugLoc DL = Op.getDebugLoc();
9937
9938   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9939                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9940                        false,
9941                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9942 }
9943
9944 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9945 // may or may not be a constant. Takes immediate version of shift as input.
9946 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9947                                    SDValue SrcOp, SDValue ShAmt,
9948                                    SelectionDAG &DAG) {
9949   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9950
9951   if (isa<ConstantSDNode>(ShAmt)) {
9952     // Constant may be a TargetConstant. Use a regular constant.
9953     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9954     switch (Opc) {
9955       default: llvm_unreachable("Unknown target vector shift node");
9956       case X86ISD::VSHLI:
9957       case X86ISD::VSRLI:
9958       case X86ISD::VSRAI:
9959         return DAG.getNode(Opc, dl, VT, SrcOp,
9960                            DAG.getConstant(ShiftAmt, MVT::i32));
9961     }
9962   }
9963
9964   // Change opcode to non-immediate version
9965   switch (Opc) {
9966     default: llvm_unreachable("Unknown target vector shift node");
9967     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9968     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9969     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9970   }
9971
9972   // Need to build a vector containing shift amount
9973   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9974   SDValue ShOps[4];
9975   ShOps[0] = ShAmt;
9976   ShOps[1] = DAG.getConstant(0, MVT::i32);
9977   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9978   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9979
9980   // The return type has to be a 128-bit type with the same element
9981   // type as the input type.
9982   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9983   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9984
9985   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9986   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9987 }
9988
9989 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9990   DebugLoc dl = Op.getDebugLoc();
9991   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9992   switch (IntNo) {
9993   default: return SDValue();    // Don't custom lower most intrinsics.
9994   // Comparison intrinsics.
9995   case Intrinsic::x86_sse_comieq_ss:
9996   case Intrinsic::x86_sse_comilt_ss:
9997   case Intrinsic::x86_sse_comile_ss:
9998   case Intrinsic::x86_sse_comigt_ss:
9999   case Intrinsic::x86_sse_comige_ss:
10000   case Intrinsic::x86_sse_comineq_ss:
10001   case Intrinsic::x86_sse_ucomieq_ss:
10002   case Intrinsic::x86_sse_ucomilt_ss:
10003   case Intrinsic::x86_sse_ucomile_ss:
10004   case Intrinsic::x86_sse_ucomigt_ss:
10005   case Intrinsic::x86_sse_ucomige_ss:
10006   case Intrinsic::x86_sse_ucomineq_ss:
10007   case Intrinsic::x86_sse2_comieq_sd:
10008   case Intrinsic::x86_sse2_comilt_sd:
10009   case Intrinsic::x86_sse2_comile_sd:
10010   case Intrinsic::x86_sse2_comigt_sd:
10011   case Intrinsic::x86_sse2_comige_sd:
10012   case Intrinsic::x86_sse2_comineq_sd:
10013   case Intrinsic::x86_sse2_ucomieq_sd:
10014   case Intrinsic::x86_sse2_ucomilt_sd:
10015   case Intrinsic::x86_sse2_ucomile_sd:
10016   case Intrinsic::x86_sse2_ucomigt_sd:
10017   case Intrinsic::x86_sse2_ucomige_sd:
10018   case Intrinsic::x86_sse2_ucomineq_sd: {
10019     unsigned Opc;
10020     ISD::CondCode CC;
10021     switch (IntNo) {
10022     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10023     case Intrinsic::x86_sse_comieq_ss:
10024     case Intrinsic::x86_sse2_comieq_sd:
10025       Opc = X86ISD::COMI;
10026       CC = ISD::SETEQ;
10027       break;
10028     case Intrinsic::x86_sse_comilt_ss:
10029     case Intrinsic::x86_sse2_comilt_sd:
10030       Opc = X86ISD::COMI;
10031       CC = ISD::SETLT;
10032       break;
10033     case Intrinsic::x86_sse_comile_ss:
10034     case Intrinsic::x86_sse2_comile_sd:
10035       Opc = X86ISD::COMI;
10036       CC = ISD::SETLE;
10037       break;
10038     case Intrinsic::x86_sse_comigt_ss:
10039     case Intrinsic::x86_sse2_comigt_sd:
10040       Opc = X86ISD::COMI;
10041       CC = ISD::SETGT;
10042       break;
10043     case Intrinsic::x86_sse_comige_ss:
10044     case Intrinsic::x86_sse2_comige_sd:
10045       Opc = X86ISD::COMI;
10046       CC = ISD::SETGE;
10047       break;
10048     case Intrinsic::x86_sse_comineq_ss:
10049     case Intrinsic::x86_sse2_comineq_sd:
10050       Opc = X86ISD::COMI;
10051       CC = ISD::SETNE;
10052       break;
10053     case Intrinsic::x86_sse_ucomieq_ss:
10054     case Intrinsic::x86_sse2_ucomieq_sd:
10055       Opc = X86ISD::UCOMI;
10056       CC = ISD::SETEQ;
10057       break;
10058     case Intrinsic::x86_sse_ucomilt_ss:
10059     case Intrinsic::x86_sse2_ucomilt_sd:
10060       Opc = X86ISD::UCOMI;
10061       CC = ISD::SETLT;
10062       break;
10063     case Intrinsic::x86_sse_ucomile_ss:
10064     case Intrinsic::x86_sse2_ucomile_sd:
10065       Opc = X86ISD::UCOMI;
10066       CC = ISD::SETLE;
10067       break;
10068     case Intrinsic::x86_sse_ucomigt_ss:
10069     case Intrinsic::x86_sse2_ucomigt_sd:
10070       Opc = X86ISD::UCOMI;
10071       CC = ISD::SETGT;
10072       break;
10073     case Intrinsic::x86_sse_ucomige_ss:
10074     case Intrinsic::x86_sse2_ucomige_sd:
10075       Opc = X86ISD::UCOMI;
10076       CC = ISD::SETGE;
10077       break;
10078     case Intrinsic::x86_sse_ucomineq_ss:
10079     case Intrinsic::x86_sse2_ucomineq_sd:
10080       Opc = X86ISD::UCOMI;
10081       CC = ISD::SETNE;
10082       break;
10083     }
10084
10085     SDValue LHS = Op.getOperand(1);
10086     SDValue RHS = Op.getOperand(2);
10087     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10088     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10089     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10090     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10091                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10092     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10093   }
10094
10095   // Arithmetic intrinsics.
10096   case Intrinsic::x86_sse2_pmulu_dq:
10097   case Intrinsic::x86_avx2_pmulu_dq:
10098     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10099                        Op.getOperand(1), Op.getOperand(2));
10100
10101   // SSE2/AVX2 sub with unsigned saturation intrinsics
10102   case Intrinsic::x86_sse2_psubus_b:
10103   case Intrinsic::x86_sse2_psubus_w:
10104   case Intrinsic::x86_avx2_psubus_b:
10105   case Intrinsic::x86_avx2_psubus_w:
10106     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10107                        Op.getOperand(1), Op.getOperand(2));
10108
10109   // SSE3/AVX horizontal add/sub intrinsics
10110   case Intrinsic::x86_sse3_hadd_ps:
10111   case Intrinsic::x86_sse3_hadd_pd:
10112   case Intrinsic::x86_avx_hadd_ps_256:
10113   case Intrinsic::x86_avx_hadd_pd_256:
10114   case Intrinsic::x86_sse3_hsub_ps:
10115   case Intrinsic::x86_sse3_hsub_pd:
10116   case Intrinsic::x86_avx_hsub_ps_256:
10117   case Intrinsic::x86_avx_hsub_pd_256:
10118   case Intrinsic::x86_ssse3_phadd_w_128:
10119   case Intrinsic::x86_ssse3_phadd_d_128:
10120   case Intrinsic::x86_avx2_phadd_w:
10121   case Intrinsic::x86_avx2_phadd_d:
10122   case Intrinsic::x86_ssse3_phsub_w_128:
10123   case Intrinsic::x86_ssse3_phsub_d_128:
10124   case Intrinsic::x86_avx2_phsub_w:
10125   case Intrinsic::x86_avx2_phsub_d: {
10126     unsigned Opcode;
10127     switch (IntNo) {
10128     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10129     case Intrinsic::x86_sse3_hadd_ps:
10130     case Intrinsic::x86_sse3_hadd_pd:
10131     case Intrinsic::x86_avx_hadd_ps_256:
10132     case Intrinsic::x86_avx_hadd_pd_256:
10133       Opcode = X86ISD::FHADD;
10134       break;
10135     case Intrinsic::x86_sse3_hsub_ps:
10136     case Intrinsic::x86_sse3_hsub_pd:
10137     case Intrinsic::x86_avx_hsub_ps_256:
10138     case Intrinsic::x86_avx_hsub_pd_256:
10139       Opcode = X86ISD::FHSUB;
10140       break;
10141     case Intrinsic::x86_ssse3_phadd_w_128:
10142     case Intrinsic::x86_ssse3_phadd_d_128:
10143     case Intrinsic::x86_avx2_phadd_w:
10144     case Intrinsic::x86_avx2_phadd_d:
10145       Opcode = X86ISD::HADD;
10146       break;
10147     case Intrinsic::x86_ssse3_phsub_w_128:
10148     case Intrinsic::x86_ssse3_phsub_d_128:
10149     case Intrinsic::x86_avx2_phsub_w:
10150     case Intrinsic::x86_avx2_phsub_d:
10151       Opcode = X86ISD::HSUB;
10152       break;
10153     }
10154     return DAG.getNode(Opcode, dl, Op.getValueType(),
10155                        Op.getOperand(1), Op.getOperand(2));
10156   }
10157
10158   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10159   case Intrinsic::x86_sse2_pmaxu_b:
10160   case Intrinsic::x86_sse41_pmaxuw:
10161   case Intrinsic::x86_sse41_pmaxud:
10162   case Intrinsic::x86_avx2_pmaxu_b:
10163   case Intrinsic::x86_avx2_pmaxu_w:
10164   case Intrinsic::x86_avx2_pmaxu_d:
10165     return DAG.getNode(X86ISD::UMAX, dl, Op.getValueType(),
10166                        Op.getOperand(1), Op.getOperand(2));
10167   case Intrinsic::x86_sse2_pminu_b:
10168   case Intrinsic::x86_sse41_pminuw:
10169   case Intrinsic::x86_sse41_pminud:
10170   case Intrinsic::x86_avx2_pminu_b:
10171   case Intrinsic::x86_avx2_pminu_w:
10172   case Intrinsic::x86_avx2_pminu_d:
10173     return DAG.getNode(X86ISD::UMIN, dl, Op.getValueType(),
10174                        Op.getOperand(1), Op.getOperand(2));
10175   case Intrinsic::x86_sse41_pmaxsb:
10176   case Intrinsic::x86_sse2_pmaxs_w:
10177   case Intrinsic::x86_sse41_pmaxsd:
10178   case Intrinsic::x86_avx2_pmaxs_b:
10179   case Intrinsic::x86_avx2_pmaxs_w:
10180   case Intrinsic::x86_avx2_pmaxs_d:
10181     return DAG.getNode(X86ISD::SMAX, dl, Op.getValueType(),
10182                        Op.getOperand(1), Op.getOperand(2));
10183   case Intrinsic::x86_sse41_pminsb:
10184   case Intrinsic::x86_sse2_pmins_w:
10185   case Intrinsic::x86_sse41_pminsd:
10186   case Intrinsic::x86_avx2_pmins_b:
10187   case Intrinsic::x86_avx2_pmins_w:
10188   case Intrinsic::x86_avx2_pmins_d:
10189     return DAG.getNode(X86ISD::SMIN, dl, Op.getValueType(),
10190                        Op.getOperand(1), Op.getOperand(2));
10191
10192   // AVX2 variable shift intrinsics
10193   case Intrinsic::x86_avx2_psllv_d:
10194   case Intrinsic::x86_avx2_psllv_q:
10195   case Intrinsic::x86_avx2_psllv_d_256:
10196   case Intrinsic::x86_avx2_psllv_q_256:
10197   case Intrinsic::x86_avx2_psrlv_d:
10198   case Intrinsic::x86_avx2_psrlv_q:
10199   case Intrinsic::x86_avx2_psrlv_d_256:
10200   case Intrinsic::x86_avx2_psrlv_q_256:
10201   case Intrinsic::x86_avx2_psrav_d:
10202   case Intrinsic::x86_avx2_psrav_d_256: {
10203     unsigned Opcode;
10204     switch (IntNo) {
10205     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10206     case Intrinsic::x86_avx2_psllv_d:
10207     case Intrinsic::x86_avx2_psllv_q:
10208     case Intrinsic::x86_avx2_psllv_d_256:
10209     case Intrinsic::x86_avx2_psllv_q_256:
10210       Opcode = ISD::SHL;
10211       break;
10212     case Intrinsic::x86_avx2_psrlv_d:
10213     case Intrinsic::x86_avx2_psrlv_q:
10214     case Intrinsic::x86_avx2_psrlv_d_256:
10215     case Intrinsic::x86_avx2_psrlv_q_256:
10216       Opcode = ISD::SRL;
10217       break;
10218     case Intrinsic::x86_avx2_psrav_d:
10219     case Intrinsic::x86_avx2_psrav_d_256:
10220       Opcode = ISD::SRA;
10221       break;
10222     }
10223     return DAG.getNode(Opcode, dl, Op.getValueType(),
10224                        Op.getOperand(1), Op.getOperand(2));
10225   }
10226
10227   case Intrinsic::x86_ssse3_pshuf_b_128:
10228   case Intrinsic::x86_avx2_pshuf_b:
10229     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10230                        Op.getOperand(1), Op.getOperand(2));
10231
10232   case Intrinsic::x86_ssse3_psign_b_128:
10233   case Intrinsic::x86_ssse3_psign_w_128:
10234   case Intrinsic::x86_ssse3_psign_d_128:
10235   case Intrinsic::x86_avx2_psign_b:
10236   case Intrinsic::x86_avx2_psign_w:
10237   case Intrinsic::x86_avx2_psign_d:
10238     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10239                        Op.getOperand(1), Op.getOperand(2));
10240
10241   case Intrinsic::x86_sse41_insertps:
10242     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10243                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10244
10245   case Intrinsic::x86_avx_vperm2f128_ps_256:
10246   case Intrinsic::x86_avx_vperm2f128_pd_256:
10247   case Intrinsic::x86_avx_vperm2f128_si_256:
10248   case Intrinsic::x86_avx2_vperm2i128:
10249     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10250                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10251
10252   case Intrinsic::x86_avx2_permd:
10253   case Intrinsic::x86_avx2_permps:
10254     // Operands intentionally swapped. Mask is last operand to intrinsic,
10255     // but second operand for node/intruction.
10256     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10257                        Op.getOperand(2), Op.getOperand(1));
10258
10259   // ptest and testp intrinsics. The intrinsic these come from are designed to
10260   // return an integer value, not just an instruction so lower it to the ptest
10261   // or testp pattern and a setcc for the result.
10262   case Intrinsic::x86_sse41_ptestz:
10263   case Intrinsic::x86_sse41_ptestc:
10264   case Intrinsic::x86_sse41_ptestnzc:
10265   case Intrinsic::x86_avx_ptestz_256:
10266   case Intrinsic::x86_avx_ptestc_256:
10267   case Intrinsic::x86_avx_ptestnzc_256:
10268   case Intrinsic::x86_avx_vtestz_ps:
10269   case Intrinsic::x86_avx_vtestc_ps:
10270   case Intrinsic::x86_avx_vtestnzc_ps:
10271   case Intrinsic::x86_avx_vtestz_pd:
10272   case Intrinsic::x86_avx_vtestc_pd:
10273   case Intrinsic::x86_avx_vtestnzc_pd:
10274   case Intrinsic::x86_avx_vtestz_ps_256:
10275   case Intrinsic::x86_avx_vtestc_ps_256:
10276   case Intrinsic::x86_avx_vtestnzc_ps_256:
10277   case Intrinsic::x86_avx_vtestz_pd_256:
10278   case Intrinsic::x86_avx_vtestc_pd_256:
10279   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10280     bool IsTestPacked = false;
10281     unsigned X86CC;
10282     switch (IntNo) {
10283     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10284     case Intrinsic::x86_avx_vtestz_ps:
10285     case Intrinsic::x86_avx_vtestz_pd:
10286     case Intrinsic::x86_avx_vtestz_ps_256:
10287     case Intrinsic::x86_avx_vtestz_pd_256:
10288       IsTestPacked = true; // Fallthrough
10289     case Intrinsic::x86_sse41_ptestz:
10290     case Intrinsic::x86_avx_ptestz_256:
10291       // ZF = 1
10292       X86CC = X86::COND_E;
10293       break;
10294     case Intrinsic::x86_avx_vtestc_ps:
10295     case Intrinsic::x86_avx_vtestc_pd:
10296     case Intrinsic::x86_avx_vtestc_ps_256:
10297     case Intrinsic::x86_avx_vtestc_pd_256:
10298       IsTestPacked = true; // Fallthrough
10299     case Intrinsic::x86_sse41_ptestc:
10300     case Intrinsic::x86_avx_ptestc_256:
10301       // CF = 1
10302       X86CC = X86::COND_B;
10303       break;
10304     case Intrinsic::x86_avx_vtestnzc_ps:
10305     case Intrinsic::x86_avx_vtestnzc_pd:
10306     case Intrinsic::x86_avx_vtestnzc_ps_256:
10307     case Intrinsic::x86_avx_vtestnzc_pd_256:
10308       IsTestPacked = true; // Fallthrough
10309     case Intrinsic::x86_sse41_ptestnzc:
10310     case Intrinsic::x86_avx_ptestnzc_256:
10311       // ZF and CF = 0
10312       X86CC = X86::COND_A;
10313       break;
10314     }
10315
10316     SDValue LHS = Op.getOperand(1);
10317     SDValue RHS = Op.getOperand(2);
10318     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10319     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10320     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10321     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10322     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10323   }
10324
10325   // SSE/AVX shift intrinsics
10326   case Intrinsic::x86_sse2_psll_w:
10327   case Intrinsic::x86_sse2_psll_d:
10328   case Intrinsic::x86_sse2_psll_q:
10329   case Intrinsic::x86_avx2_psll_w:
10330   case Intrinsic::x86_avx2_psll_d:
10331   case Intrinsic::x86_avx2_psll_q:
10332   case Intrinsic::x86_sse2_psrl_w:
10333   case Intrinsic::x86_sse2_psrl_d:
10334   case Intrinsic::x86_sse2_psrl_q:
10335   case Intrinsic::x86_avx2_psrl_w:
10336   case Intrinsic::x86_avx2_psrl_d:
10337   case Intrinsic::x86_avx2_psrl_q:
10338   case Intrinsic::x86_sse2_psra_w:
10339   case Intrinsic::x86_sse2_psra_d:
10340   case Intrinsic::x86_avx2_psra_w:
10341   case Intrinsic::x86_avx2_psra_d: {
10342     unsigned Opcode;
10343     switch (IntNo) {
10344     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10345     case Intrinsic::x86_sse2_psll_w:
10346     case Intrinsic::x86_sse2_psll_d:
10347     case Intrinsic::x86_sse2_psll_q:
10348     case Intrinsic::x86_avx2_psll_w:
10349     case Intrinsic::x86_avx2_psll_d:
10350     case Intrinsic::x86_avx2_psll_q:
10351       Opcode = X86ISD::VSHL;
10352       break;
10353     case Intrinsic::x86_sse2_psrl_w:
10354     case Intrinsic::x86_sse2_psrl_d:
10355     case Intrinsic::x86_sse2_psrl_q:
10356     case Intrinsic::x86_avx2_psrl_w:
10357     case Intrinsic::x86_avx2_psrl_d:
10358     case Intrinsic::x86_avx2_psrl_q:
10359       Opcode = X86ISD::VSRL;
10360       break;
10361     case Intrinsic::x86_sse2_psra_w:
10362     case Intrinsic::x86_sse2_psra_d:
10363     case Intrinsic::x86_avx2_psra_w:
10364     case Intrinsic::x86_avx2_psra_d:
10365       Opcode = X86ISD::VSRA;
10366       break;
10367     }
10368     return DAG.getNode(Opcode, dl, Op.getValueType(),
10369                        Op.getOperand(1), Op.getOperand(2));
10370   }
10371
10372   // SSE/AVX immediate shift intrinsics
10373   case Intrinsic::x86_sse2_pslli_w:
10374   case Intrinsic::x86_sse2_pslli_d:
10375   case Intrinsic::x86_sse2_pslli_q:
10376   case Intrinsic::x86_avx2_pslli_w:
10377   case Intrinsic::x86_avx2_pslli_d:
10378   case Intrinsic::x86_avx2_pslli_q:
10379   case Intrinsic::x86_sse2_psrli_w:
10380   case Intrinsic::x86_sse2_psrli_d:
10381   case Intrinsic::x86_sse2_psrli_q:
10382   case Intrinsic::x86_avx2_psrli_w:
10383   case Intrinsic::x86_avx2_psrli_d:
10384   case Intrinsic::x86_avx2_psrli_q:
10385   case Intrinsic::x86_sse2_psrai_w:
10386   case Intrinsic::x86_sse2_psrai_d:
10387   case Intrinsic::x86_avx2_psrai_w:
10388   case Intrinsic::x86_avx2_psrai_d: {
10389     unsigned Opcode;
10390     switch (IntNo) {
10391     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10392     case Intrinsic::x86_sse2_pslli_w:
10393     case Intrinsic::x86_sse2_pslli_d:
10394     case Intrinsic::x86_sse2_pslli_q:
10395     case Intrinsic::x86_avx2_pslli_w:
10396     case Intrinsic::x86_avx2_pslli_d:
10397     case Intrinsic::x86_avx2_pslli_q:
10398       Opcode = X86ISD::VSHLI;
10399       break;
10400     case Intrinsic::x86_sse2_psrli_w:
10401     case Intrinsic::x86_sse2_psrli_d:
10402     case Intrinsic::x86_sse2_psrli_q:
10403     case Intrinsic::x86_avx2_psrli_w:
10404     case Intrinsic::x86_avx2_psrli_d:
10405     case Intrinsic::x86_avx2_psrli_q:
10406       Opcode = X86ISD::VSRLI;
10407       break;
10408     case Intrinsic::x86_sse2_psrai_w:
10409     case Intrinsic::x86_sse2_psrai_d:
10410     case Intrinsic::x86_avx2_psrai_w:
10411     case Intrinsic::x86_avx2_psrai_d:
10412       Opcode = X86ISD::VSRAI;
10413       break;
10414     }
10415     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10416                                Op.getOperand(1), Op.getOperand(2), DAG);
10417   }
10418
10419   case Intrinsic::x86_sse42_pcmpistria128:
10420   case Intrinsic::x86_sse42_pcmpestria128:
10421   case Intrinsic::x86_sse42_pcmpistric128:
10422   case Intrinsic::x86_sse42_pcmpestric128:
10423   case Intrinsic::x86_sse42_pcmpistrio128:
10424   case Intrinsic::x86_sse42_pcmpestrio128:
10425   case Intrinsic::x86_sse42_pcmpistris128:
10426   case Intrinsic::x86_sse42_pcmpestris128:
10427   case Intrinsic::x86_sse42_pcmpistriz128:
10428   case Intrinsic::x86_sse42_pcmpestriz128: {
10429     unsigned Opcode;
10430     unsigned X86CC;
10431     switch (IntNo) {
10432     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10433     case Intrinsic::x86_sse42_pcmpistria128:
10434       Opcode = X86ISD::PCMPISTRI;
10435       X86CC = X86::COND_A;
10436       break;
10437     case Intrinsic::x86_sse42_pcmpestria128:
10438       Opcode = X86ISD::PCMPESTRI;
10439       X86CC = X86::COND_A;
10440       break;
10441     case Intrinsic::x86_sse42_pcmpistric128:
10442       Opcode = X86ISD::PCMPISTRI;
10443       X86CC = X86::COND_B;
10444       break;
10445     case Intrinsic::x86_sse42_pcmpestric128:
10446       Opcode = X86ISD::PCMPESTRI;
10447       X86CC = X86::COND_B;
10448       break;
10449     case Intrinsic::x86_sse42_pcmpistrio128:
10450       Opcode = X86ISD::PCMPISTRI;
10451       X86CC = X86::COND_O;
10452       break;
10453     case Intrinsic::x86_sse42_pcmpestrio128:
10454       Opcode = X86ISD::PCMPESTRI;
10455       X86CC = X86::COND_O;
10456       break;
10457     case Intrinsic::x86_sse42_pcmpistris128:
10458       Opcode = X86ISD::PCMPISTRI;
10459       X86CC = X86::COND_S;
10460       break;
10461     case Intrinsic::x86_sse42_pcmpestris128:
10462       Opcode = X86ISD::PCMPESTRI;
10463       X86CC = X86::COND_S;
10464       break;
10465     case Intrinsic::x86_sse42_pcmpistriz128:
10466       Opcode = X86ISD::PCMPISTRI;
10467       X86CC = X86::COND_E;
10468       break;
10469     case Intrinsic::x86_sse42_pcmpestriz128:
10470       Opcode = X86ISD::PCMPESTRI;
10471       X86CC = X86::COND_E;
10472       break;
10473     }
10474     SmallVector<SDValue, 5> NewOps;
10475     NewOps.append(Op->op_begin()+1, Op->op_end());
10476     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10477     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10478     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10479                                 DAG.getConstant(X86CC, MVT::i8),
10480                                 SDValue(PCMP.getNode(), 1));
10481     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10482   }
10483
10484   case Intrinsic::x86_sse42_pcmpistri128:
10485   case Intrinsic::x86_sse42_pcmpestri128: {
10486     unsigned Opcode;
10487     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10488       Opcode = X86ISD::PCMPISTRI;
10489     else
10490       Opcode = X86ISD::PCMPESTRI;
10491
10492     SmallVector<SDValue, 5> NewOps;
10493     NewOps.append(Op->op_begin()+1, Op->op_end());
10494     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10495     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10496   }
10497   case Intrinsic::x86_fma_vfmadd_ps:
10498   case Intrinsic::x86_fma_vfmadd_pd:
10499   case Intrinsic::x86_fma_vfmsub_ps:
10500   case Intrinsic::x86_fma_vfmsub_pd:
10501   case Intrinsic::x86_fma_vfnmadd_ps:
10502   case Intrinsic::x86_fma_vfnmadd_pd:
10503   case Intrinsic::x86_fma_vfnmsub_ps:
10504   case Intrinsic::x86_fma_vfnmsub_pd:
10505   case Intrinsic::x86_fma_vfmaddsub_ps:
10506   case Intrinsic::x86_fma_vfmaddsub_pd:
10507   case Intrinsic::x86_fma_vfmsubadd_ps:
10508   case Intrinsic::x86_fma_vfmsubadd_pd:
10509   case Intrinsic::x86_fma_vfmadd_ps_256:
10510   case Intrinsic::x86_fma_vfmadd_pd_256:
10511   case Intrinsic::x86_fma_vfmsub_ps_256:
10512   case Intrinsic::x86_fma_vfmsub_pd_256:
10513   case Intrinsic::x86_fma_vfnmadd_ps_256:
10514   case Intrinsic::x86_fma_vfnmadd_pd_256:
10515   case Intrinsic::x86_fma_vfnmsub_ps_256:
10516   case Intrinsic::x86_fma_vfnmsub_pd_256:
10517   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10518   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10519   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10520   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10521     unsigned Opc;
10522     switch (IntNo) {
10523     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10524     case Intrinsic::x86_fma_vfmadd_ps:
10525     case Intrinsic::x86_fma_vfmadd_pd:
10526     case Intrinsic::x86_fma_vfmadd_ps_256:
10527     case Intrinsic::x86_fma_vfmadd_pd_256:
10528       Opc = X86ISD::FMADD;
10529       break;
10530     case Intrinsic::x86_fma_vfmsub_ps:
10531     case Intrinsic::x86_fma_vfmsub_pd:
10532     case Intrinsic::x86_fma_vfmsub_ps_256:
10533     case Intrinsic::x86_fma_vfmsub_pd_256:
10534       Opc = X86ISD::FMSUB;
10535       break;
10536     case Intrinsic::x86_fma_vfnmadd_ps:
10537     case Intrinsic::x86_fma_vfnmadd_pd:
10538     case Intrinsic::x86_fma_vfnmadd_ps_256:
10539     case Intrinsic::x86_fma_vfnmadd_pd_256:
10540       Opc = X86ISD::FNMADD;
10541       break;
10542     case Intrinsic::x86_fma_vfnmsub_ps:
10543     case Intrinsic::x86_fma_vfnmsub_pd:
10544     case Intrinsic::x86_fma_vfnmsub_ps_256:
10545     case Intrinsic::x86_fma_vfnmsub_pd_256:
10546       Opc = X86ISD::FNMSUB;
10547       break;
10548     case Intrinsic::x86_fma_vfmaddsub_ps:
10549     case Intrinsic::x86_fma_vfmaddsub_pd:
10550     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10551     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10552       Opc = X86ISD::FMADDSUB;
10553       break;
10554     case Intrinsic::x86_fma_vfmsubadd_ps:
10555     case Intrinsic::x86_fma_vfmsubadd_pd:
10556     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10557     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10558       Opc = X86ISD::FMSUBADD;
10559       break;
10560     }
10561
10562     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10563                        Op.getOperand(2), Op.getOperand(3));
10564   }
10565   }
10566 }
10567
10568 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10569   DebugLoc dl = Op.getDebugLoc();
10570   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10571   switch (IntNo) {
10572   default: return SDValue();    // Don't custom lower most intrinsics.
10573
10574   // RDRAND intrinsics.
10575   case Intrinsic::x86_rdrand_16:
10576   case Intrinsic::x86_rdrand_32:
10577   case Intrinsic::x86_rdrand_64: {
10578     // Emit the node with the right value type.
10579     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10580     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10581
10582     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10583     // return the value from Rand, which is always 0, casted to i32.
10584     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10585                       DAG.getConstant(1, Op->getValueType(1)),
10586                       DAG.getConstant(X86::COND_B, MVT::i32),
10587                       SDValue(Result.getNode(), 1) };
10588     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10589                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10590                                   Ops, 4);
10591
10592     // Return { result, isValid, chain }.
10593     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10594                        SDValue(Result.getNode(), 2));
10595   }
10596   }
10597 }
10598
10599 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10600                                            SelectionDAG &DAG) const {
10601   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10602   MFI->setReturnAddressIsTaken(true);
10603
10604   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10605   DebugLoc dl = Op.getDebugLoc();
10606   EVT PtrVT = getPointerTy();
10607
10608   if (Depth > 0) {
10609     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10610     SDValue Offset =
10611       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10612     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10613                        DAG.getNode(ISD::ADD, dl, PtrVT,
10614                                    FrameAddr, Offset),
10615                        MachinePointerInfo(), false, false, false, 0);
10616   }
10617
10618   // Just load the return address.
10619   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10620   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10621                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10622 }
10623
10624 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10625   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10626   MFI->setFrameAddressIsTaken(true);
10627
10628   EVT VT = Op.getValueType();
10629   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10630   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10631   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10632   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10633   while (Depth--)
10634     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10635                             MachinePointerInfo(),
10636                             false, false, false, 0);
10637   return FrameAddr;
10638 }
10639
10640 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10641                                                      SelectionDAG &DAG) const {
10642   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10643 }
10644
10645 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10646   SDValue Chain     = Op.getOperand(0);
10647   SDValue Offset    = Op.getOperand(1);
10648   SDValue Handler   = Op.getOperand(2);
10649   DebugLoc dl       = Op.getDebugLoc();
10650
10651   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10652                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10653                                      getPointerTy());
10654   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10655
10656   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10657                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10658   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10659   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10660                        false, false, 0);
10661   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10662
10663   return DAG.getNode(X86ISD::EH_RETURN, dl,
10664                      MVT::Other,
10665                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10666 }
10667
10668 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10669                                                SelectionDAG &DAG) const {
10670   DebugLoc DL = Op.getDebugLoc();
10671   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10672                      DAG.getVTList(MVT::i32, MVT::Other),
10673                      Op.getOperand(0), Op.getOperand(1));
10674 }
10675
10676 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10677                                                 SelectionDAG &DAG) const {
10678   DebugLoc DL = Op.getDebugLoc();
10679   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10680                      Op.getOperand(0), Op.getOperand(1));
10681 }
10682
10683 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10684   return Op.getOperand(0);
10685 }
10686
10687 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10688                                                 SelectionDAG &DAG) const {
10689   SDValue Root = Op.getOperand(0);
10690   SDValue Trmp = Op.getOperand(1); // trampoline
10691   SDValue FPtr = Op.getOperand(2); // nested function
10692   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10693   DebugLoc dl  = Op.getDebugLoc();
10694
10695   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10696   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10697
10698   if (Subtarget->is64Bit()) {
10699     SDValue OutChains[6];
10700
10701     // Large code-model.
10702     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10703     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10704
10705     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10706     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10707
10708     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10709
10710     // Load the pointer to the nested function into R11.
10711     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10712     SDValue Addr = Trmp;
10713     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10714                                 Addr, MachinePointerInfo(TrmpAddr),
10715                                 false, false, 0);
10716
10717     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10718                        DAG.getConstant(2, MVT::i64));
10719     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10720                                 MachinePointerInfo(TrmpAddr, 2),
10721                                 false, false, 2);
10722
10723     // Load the 'nest' parameter value into R10.
10724     // R10 is specified in X86CallingConv.td
10725     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10726     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10727                        DAG.getConstant(10, MVT::i64));
10728     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10729                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10730                                 false, false, 0);
10731
10732     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10733                        DAG.getConstant(12, MVT::i64));
10734     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10735                                 MachinePointerInfo(TrmpAddr, 12),
10736                                 false, false, 2);
10737
10738     // Jump to the nested function.
10739     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10740     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10741                        DAG.getConstant(20, MVT::i64));
10742     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10743                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10744                                 false, false, 0);
10745
10746     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10747     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10748                        DAG.getConstant(22, MVT::i64));
10749     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10750                                 MachinePointerInfo(TrmpAddr, 22),
10751                                 false, false, 0);
10752
10753     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10754   } else {
10755     const Function *Func =
10756       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10757     CallingConv::ID CC = Func->getCallingConv();
10758     unsigned NestReg;
10759
10760     switch (CC) {
10761     default:
10762       llvm_unreachable("Unsupported calling convention");
10763     case CallingConv::C:
10764     case CallingConv::X86_StdCall: {
10765       // Pass 'nest' parameter in ECX.
10766       // Must be kept in sync with X86CallingConv.td
10767       NestReg = X86::ECX;
10768
10769       // Check that ECX wasn't needed by an 'inreg' parameter.
10770       FunctionType *FTy = Func->getFunctionType();
10771       const AttributeSet &Attrs = Func->getAttributes();
10772
10773       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10774         unsigned InRegCount = 0;
10775         unsigned Idx = 1;
10776
10777         for (FunctionType::param_iterator I = FTy->param_begin(),
10778              E = FTy->param_end(); I != E; ++I, ++Idx)
10779           if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
10780             // FIXME: should only count parameters that are lowered to integers.
10781             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10782
10783         if (InRegCount > 2) {
10784           report_fatal_error("Nest register in use - reduce number of inreg"
10785                              " parameters!");
10786         }
10787       }
10788       break;
10789     }
10790     case CallingConv::X86_FastCall:
10791     case CallingConv::X86_ThisCall:
10792     case CallingConv::Fast:
10793       // Pass 'nest' parameter in EAX.
10794       // Must be kept in sync with X86CallingConv.td
10795       NestReg = X86::EAX;
10796       break;
10797     }
10798
10799     SDValue OutChains[4];
10800     SDValue Addr, Disp;
10801
10802     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10803                        DAG.getConstant(10, MVT::i32));
10804     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10805
10806     // This is storing the opcode for MOV32ri.
10807     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10808     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10809     OutChains[0] = DAG.getStore(Root, dl,
10810                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10811                                 Trmp, MachinePointerInfo(TrmpAddr),
10812                                 false, false, 0);
10813
10814     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10815                        DAG.getConstant(1, MVT::i32));
10816     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10817                                 MachinePointerInfo(TrmpAddr, 1),
10818                                 false, false, 1);
10819
10820     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10821     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10822                        DAG.getConstant(5, MVT::i32));
10823     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10824                                 MachinePointerInfo(TrmpAddr, 5),
10825                                 false, false, 1);
10826
10827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10828                        DAG.getConstant(6, MVT::i32));
10829     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10830                                 MachinePointerInfo(TrmpAddr, 6),
10831                                 false, false, 1);
10832
10833     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10834   }
10835 }
10836
10837 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10838                                             SelectionDAG &DAG) const {
10839   /*
10840    The rounding mode is in bits 11:10 of FPSR, and has the following
10841    settings:
10842      00 Round to nearest
10843      01 Round to -inf
10844      10 Round to +inf
10845      11 Round to 0
10846
10847   FLT_ROUNDS, on the other hand, expects the following:
10848     -1 Undefined
10849      0 Round to 0
10850      1 Round to nearest
10851      2 Round to +inf
10852      3 Round to -inf
10853
10854   To perform the conversion, we do:
10855     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10856   */
10857
10858   MachineFunction &MF = DAG.getMachineFunction();
10859   const TargetMachine &TM = MF.getTarget();
10860   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10861   unsigned StackAlignment = TFI.getStackAlignment();
10862   EVT VT = Op.getValueType();
10863   DebugLoc DL = Op.getDebugLoc();
10864
10865   // Save FP Control Word to stack slot
10866   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10867   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10868
10869
10870   MachineMemOperand *MMO =
10871    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10872                            MachineMemOperand::MOStore, 2, 2);
10873
10874   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10875   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10876                                           DAG.getVTList(MVT::Other),
10877                                           Ops, 2, MVT::i16, MMO);
10878
10879   // Load FP Control Word from stack slot
10880   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10881                             MachinePointerInfo(), false, false, false, 0);
10882
10883   // Transform as necessary
10884   SDValue CWD1 =
10885     DAG.getNode(ISD::SRL, DL, MVT::i16,
10886                 DAG.getNode(ISD::AND, DL, MVT::i16,
10887                             CWD, DAG.getConstant(0x800, MVT::i16)),
10888                 DAG.getConstant(11, MVT::i8));
10889   SDValue CWD2 =
10890     DAG.getNode(ISD::SRL, DL, MVT::i16,
10891                 DAG.getNode(ISD::AND, DL, MVT::i16,
10892                             CWD, DAG.getConstant(0x400, MVT::i16)),
10893                 DAG.getConstant(9, MVT::i8));
10894
10895   SDValue RetVal =
10896     DAG.getNode(ISD::AND, DL, MVT::i16,
10897                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10898                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10899                             DAG.getConstant(1, MVT::i16)),
10900                 DAG.getConstant(3, MVT::i16));
10901
10902
10903   return DAG.getNode((VT.getSizeInBits() < 16 ?
10904                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10905 }
10906
10907 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10908   EVT VT = Op.getValueType();
10909   EVT OpVT = VT;
10910   unsigned NumBits = VT.getSizeInBits();
10911   DebugLoc dl = Op.getDebugLoc();
10912
10913   Op = Op.getOperand(0);
10914   if (VT == MVT::i8) {
10915     // Zero extend to i32 since there is not an i8 bsr.
10916     OpVT = MVT::i32;
10917     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10918   }
10919
10920   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10921   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10922   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10923
10924   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10925   SDValue Ops[] = {
10926     Op,
10927     DAG.getConstant(NumBits+NumBits-1, OpVT),
10928     DAG.getConstant(X86::COND_E, MVT::i8),
10929     Op.getValue(1)
10930   };
10931   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10932
10933   // Finally xor with NumBits-1.
10934   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10935
10936   if (VT == MVT::i8)
10937     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10938   return Op;
10939 }
10940
10941 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10942   EVT VT = Op.getValueType();
10943   EVT OpVT = VT;
10944   unsigned NumBits = VT.getSizeInBits();
10945   DebugLoc dl = Op.getDebugLoc();
10946
10947   Op = Op.getOperand(0);
10948   if (VT == MVT::i8) {
10949     // Zero extend to i32 since there is not an i8 bsr.
10950     OpVT = MVT::i32;
10951     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10952   }
10953
10954   // Issue a bsr (scan bits in reverse).
10955   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10956   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10957
10958   // And xor with NumBits-1.
10959   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10960
10961   if (VT == MVT::i8)
10962     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10963   return Op;
10964 }
10965
10966 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10967   EVT VT = Op.getValueType();
10968   unsigned NumBits = VT.getSizeInBits();
10969   DebugLoc dl = Op.getDebugLoc();
10970   Op = Op.getOperand(0);
10971
10972   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10973   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10974   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10975
10976   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10977   SDValue Ops[] = {
10978     Op,
10979     DAG.getConstant(NumBits, VT),
10980     DAG.getConstant(X86::COND_E, MVT::i8),
10981     Op.getValue(1)
10982   };
10983   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10984 }
10985
10986 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10987 // ones, and then concatenate the result back.
10988 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10989   EVT VT = Op.getValueType();
10990
10991   assert(VT.is256BitVector() && VT.isInteger() &&
10992          "Unsupported value type for operation");
10993
10994   unsigned NumElems = VT.getVectorNumElements();
10995   DebugLoc dl = Op.getDebugLoc();
10996
10997   // Extract the LHS vectors
10998   SDValue LHS = Op.getOperand(0);
10999   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11000   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11001
11002   // Extract the RHS vectors
11003   SDValue RHS = Op.getOperand(1);
11004   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11005   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11006
11007   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11008   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11009
11010   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11011                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11012                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11013 }
11014
11015 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11016   assert(Op.getValueType().is256BitVector() &&
11017          Op.getValueType().isInteger() &&
11018          "Only handle AVX 256-bit vector integer operation");
11019   return Lower256IntArith(Op, DAG);
11020 }
11021
11022 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11023   assert(Op.getValueType().is256BitVector() &&
11024          Op.getValueType().isInteger() &&
11025          "Only handle AVX 256-bit vector integer operation");
11026   return Lower256IntArith(Op, DAG);
11027 }
11028
11029 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11030                         SelectionDAG &DAG) {
11031   DebugLoc dl = Op.getDebugLoc();
11032   EVT VT = Op.getValueType();
11033
11034   // Decompose 256-bit ops into smaller 128-bit ops.
11035   if (VT.is256BitVector() && !Subtarget->hasInt256())
11036     return Lower256IntArith(Op, DAG);
11037
11038   SDValue A = Op.getOperand(0);
11039   SDValue B = Op.getOperand(1);
11040
11041   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11042   if (VT == MVT::v4i32) {
11043     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11044            "Should not custom lower when pmuldq is available!");
11045
11046     // Extract the odd parts.
11047     const int UnpackMask[] = { 1, -1, 3, -1 };
11048     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11049     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11050
11051     // Multiply the even parts.
11052     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11053     // Now multiply odd parts.
11054     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11055
11056     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11057     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11058
11059     // Merge the two vectors back together with a shuffle. This expands into 2
11060     // shuffles.
11061     const int ShufMask[] = { 0, 4, 2, 6 };
11062     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11063   }
11064
11065   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11066          "Only know how to lower V2I64/V4I64 multiply");
11067
11068   //  Ahi = psrlqi(a, 32);
11069   //  Bhi = psrlqi(b, 32);
11070   //
11071   //  AloBlo = pmuludq(a, b);
11072   //  AloBhi = pmuludq(a, Bhi);
11073   //  AhiBlo = pmuludq(Ahi, b);
11074
11075   //  AloBhi = psllqi(AloBhi, 32);
11076   //  AhiBlo = psllqi(AhiBlo, 32);
11077   //  return AloBlo + AloBhi + AhiBlo;
11078
11079   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11080
11081   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11082   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11083
11084   // Bit cast to 32-bit vectors for MULUDQ
11085   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11086   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11087   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11088   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11089   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11090
11091   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11092   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11093   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11094
11095   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11096   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11097
11098   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11099   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11100 }
11101
11102 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11103
11104   EVT VT = Op.getValueType();
11105   DebugLoc dl = Op.getDebugLoc();
11106   SDValue R = Op.getOperand(0);
11107   SDValue Amt = Op.getOperand(1);
11108   LLVMContext *Context = DAG.getContext();
11109
11110   if (!Subtarget->hasSSE2())
11111     return SDValue();
11112
11113   // Optimize shl/srl/sra with constant shift amount.
11114   if (isSplatVector(Amt.getNode())) {
11115     SDValue SclrAmt = Amt->getOperand(0);
11116     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11117       uint64_t ShiftAmt = C->getZExtValue();
11118
11119       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11120           (Subtarget->hasInt256() &&
11121            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11122         if (Op.getOpcode() == ISD::SHL)
11123           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11124                              DAG.getConstant(ShiftAmt, MVT::i32));
11125         if (Op.getOpcode() == ISD::SRL)
11126           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11127                              DAG.getConstant(ShiftAmt, MVT::i32));
11128         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11129           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11130                              DAG.getConstant(ShiftAmt, MVT::i32));
11131       }
11132
11133       if (VT == MVT::v16i8) {
11134         if (Op.getOpcode() == ISD::SHL) {
11135           // Make a large shift.
11136           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11137                                     DAG.getConstant(ShiftAmt, MVT::i32));
11138           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11139           // Zero out the rightmost bits.
11140           SmallVector<SDValue, 16> V(16,
11141                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11142                                                      MVT::i8));
11143           return DAG.getNode(ISD::AND, dl, VT, SHL,
11144                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11145         }
11146         if (Op.getOpcode() == ISD::SRL) {
11147           // Make a large shift.
11148           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11149                                     DAG.getConstant(ShiftAmt, MVT::i32));
11150           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11151           // Zero out the leftmost bits.
11152           SmallVector<SDValue, 16> V(16,
11153                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11154                                                      MVT::i8));
11155           return DAG.getNode(ISD::AND, dl, VT, SRL,
11156                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11157         }
11158         if (Op.getOpcode() == ISD::SRA) {
11159           if (ShiftAmt == 7) {
11160             // R s>> 7  ===  R s< 0
11161             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11162             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11163           }
11164
11165           // R s>> a === ((R u>> a) ^ m) - m
11166           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11167           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11168                                                          MVT::i8));
11169           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11170           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11171           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11172           return Res;
11173         }
11174         llvm_unreachable("Unknown shift opcode.");
11175       }
11176
11177       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11178         if (Op.getOpcode() == ISD::SHL) {
11179           // Make a large shift.
11180           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11181                                     DAG.getConstant(ShiftAmt, MVT::i32));
11182           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11183           // Zero out the rightmost bits.
11184           SmallVector<SDValue, 32> V(32,
11185                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11186                                                      MVT::i8));
11187           return DAG.getNode(ISD::AND, dl, VT, SHL,
11188                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11189         }
11190         if (Op.getOpcode() == ISD::SRL) {
11191           // Make a large shift.
11192           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11193                                     DAG.getConstant(ShiftAmt, MVT::i32));
11194           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11195           // Zero out the leftmost bits.
11196           SmallVector<SDValue, 32> V(32,
11197                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11198                                                      MVT::i8));
11199           return DAG.getNode(ISD::AND, dl, VT, SRL,
11200                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11201         }
11202         if (Op.getOpcode() == ISD::SRA) {
11203           if (ShiftAmt == 7) {
11204             // R s>> 7  ===  R s< 0
11205             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11206             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11207           }
11208
11209           // R s>> a === ((R u>> a) ^ m) - m
11210           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11211           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11212                                                          MVT::i8));
11213           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11214           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11215           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11216           return Res;
11217         }
11218         llvm_unreachable("Unknown shift opcode.");
11219       }
11220     }
11221   }
11222
11223   // Lower SHL with variable shift amount.
11224   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11225     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11226                      DAG.getConstant(23, MVT::i32));
11227
11228     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11229     Constant *C = ConstantDataVector::get(*Context, CV);
11230     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11231     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11232                                  MachinePointerInfo::getConstantPool(),
11233                                  false, false, false, 16);
11234
11235     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11236     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11237     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11238     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11239   }
11240   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11241     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11242
11243     // a = a << 5;
11244     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11245                      DAG.getConstant(5, MVT::i32));
11246     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11247
11248     // Turn 'a' into a mask suitable for VSELECT
11249     SDValue VSelM = DAG.getConstant(0x80, VT);
11250     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11251     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11252
11253     SDValue CM1 = DAG.getConstant(0x0f, VT);
11254     SDValue CM2 = DAG.getConstant(0x3f, VT);
11255
11256     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11257     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11258     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11259                             DAG.getConstant(4, MVT::i32), DAG);
11260     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11261     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11262
11263     // a += a
11264     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11265     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11266     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11267
11268     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11269     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11270     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11271                             DAG.getConstant(2, MVT::i32), DAG);
11272     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11273     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11274
11275     // a += a
11276     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11277     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11278     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11279
11280     // return VSELECT(r, r+r, a);
11281     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11282                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11283     return R;
11284   }
11285
11286   // Decompose 256-bit shifts into smaller 128-bit shifts.
11287   if (VT.is256BitVector()) {
11288     unsigned NumElems = VT.getVectorNumElements();
11289     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11290     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11291
11292     // Extract the two vectors
11293     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11294     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11295
11296     // Recreate the shift amount vectors
11297     SDValue Amt1, Amt2;
11298     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11299       // Constant shift amount
11300       SmallVector<SDValue, 4> Amt1Csts;
11301       SmallVector<SDValue, 4> Amt2Csts;
11302       for (unsigned i = 0; i != NumElems/2; ++i)
11303         Amt1Csts.push_back(Amt->getOperand(i));
11304       for (unsigned i = NumElems/2; i != NumElems; ++i)
11305         Amt2Csts.push_back(Amt->getOperand(i));
11306
11307       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11308                                  &Amt1Csts[0], NumElems/2);
11309       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11310                                  &Amt2Csts[0], NumElems/2);
11311     } else {
11312       // Variable shift amount
11313       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11314       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11315     }
11316
11317     // Issue new vector shifts for the smaller types
11318     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11319     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11320
11321     // Concatenate the result back
11322     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11323   }
11324
11325   return SDValue();
11326 }
11327
11328 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11329   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11330   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11331   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11332   // has only one use.
11333   SDNode *N = Op.getNode();
11334   SDValue LHS = N->getOperand(0);
11335   SDValue RHS = N->getOperand(1);
11336   unsigned BaseOp = 0;
11337   unsigned Cond = 0;
11338   DebugLoc DL = Op.getDebugLoc();
11339   switch (Op.getOpcode()) {
11340   default: llvm_unreachable("Unknown ovf instruction!");
11341   case ISD::SADDO:
11342     // A subtract of one will be selected as a INC. Note that INC doesn't
11343     // set CF, so we can't do this for UADDO.
11344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11345       if (C->isOne()) {
11346         BaseOp = X86ISD::INC;
11347         Cond = X86::COND_O;
11348         break;
11349       }
11350     BaseOp = X86ISD::ADD;
11351     Cond = X86::COND_O;
11352     break;
11353   case ISD::UADDO:
11354     BaseOp = X86ISD::ADD;
11355     Cond = X86::COND_B;
11356     break;
11357   case ISD::SSUBO:
11358     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11359     // set CF, so we can't do this for USUBO.
11360     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11361       if (C->isOne()) {
11362         BaseOp = X86ISD::DEC;
11363         Cond = X86::COND_O;
11364         break;
11365       }
11366     BaseOp = X86ISD::SUB;
11367     Cond = X86::COND_O;
11368     break;
11369   case ISD::USUBO:
11370     BaseOp = X86ISD::SUB;
11371     Cond = X86::COND_B;
11372     break;
11373   case ISD::SMULO:
11374     BaseOp = X86ISD::SMUL;
11375     Cond = X86::COND_O;
11376     break;
11377   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11378     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11379                                  MVT::i32);
11380     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11381
11382     SDValue SetCC =
11383       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11384                   DAG.getConstant(X86::COND_O, MVT::i32),
11385                   SDValue(Sum.getNode(), 2));
11386
11387     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11388   }
11389   }
11390
11391   // Also sets EFLAGS.
11392   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11393   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11394
11395   SDValue SetCC =
11396     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11397                 DAG.getConstant(Cond, MVT::i32),
11398                 SDValue(Sum.getNode(), 1));
11399
11400   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11401 }
11402
11403 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11404                                                   SelectionDAG &DAG) const {
11405   DebugLoc dl = Op.getDebugLoc();
11406   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11407   EVT VT = Op.getValueType();
11408
11409   if (!Subtarget->hasSSE2() || !VT.isVector())
11410     return SDValue();
11411
11412   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11413                       ExtraVT.getScalarType().getSizeInBits();
11414   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11415
11416   switch (VT.getSimpleVT().SimpleTy) {
11417     default: return SDValue();
11418     case MVT::v8i32:
11419     case MVT::v16i16:
11420       if (!Subtarget->hasFp256())
11421         return SDValue();
11422       if (!Subtarget->hasInt256()) {
11423         // needs to be split
11424         unsigned NumElems = VT.getVectorNumElements();
11425
11426         // Extract the LHS vectors
11427         SDValue LHS = Op.getOperand(0);
11428         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11429         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11430
11431         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11432         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11433
11434         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11435         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11436         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11437                                    ExtraNumElems/2);
11438         SDValue Extra = DAG.getValueType(ExtraVT);
11439
11440         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11441         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11442
11443         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11444       }
11445       // fall through
11446     case MVT::v4i32:
11447     case MVT::v8i16: {
11448       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11449                                          Op.getOperand(0), ShAmt, DAG);
11450       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11451     }
11452   }
11453 }
11454
11455
11456 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11457                               SelectionDAG &DAG) {
11458   DebugLoc dl = Op.getDebugLoc();
11459
11460   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11461   // There isn't any reason to disable it if the target processor supports it.
11462   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11463     SDValue Chain = Op.getOperand(0);
11464     SDValue Zero = DAG.getConstant(0, MVT::i32);
11465     SDValue Ops[] = {
11466       DAG.getRegister(X86::ESP, MVT::i32), // Base
11467       DAG.getTargetConstant(1, MVT::i8),   // Scale
11468       DAG.getRegister(0, MVT::i32),        // Index
11469       DAG.getTargetConstant(0, MVT::i32),  // Disp
11470       DAG.getRegister(0, MVT::i32),        // Segment.
11471       Zero,
11472       Chain
11473     };
11474     SDNode *Res =
11475       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11476                           array_lengthof(Ops));
11477     return SDValue(Res, 0);
11478   }
11479
11480   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11481   if (!isDev)
11482     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11483
11484   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11485   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11486   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11487   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11488
11489   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11490   if (!Op1 && !Op2 && !Op3 && Op4)
11491     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11492
11493   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11494   if (Op1 && !Op2 && !Op3 && !Op4)
11495     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11496
11497   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11498   //           (MFENCE)>;
11499   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11500 }
11501
11502 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11503                                  SelectionDAG &DAG) {
11504   DebugLoc dl = Op.getDebugLoc();
11505   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11506     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11507   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11508     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11509
11510   // The only fence that needs an instruction is a sequentially-consistent
11511   // cross-thread fence.
11512   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11513     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11514     // no-sse2). There isn't any reason to disable it if the target processor
11515     // supports it.
11516     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11517       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11518
11519     SDValue Chain = Op.getOperand(0);
11520     SDValue Zero = DAG.getConstant(0, MVT::i32);
11521     SDValue Ops[] = {
11522       DAG.getRegister(X86::ESP, MVT::i32), // Base
11523       DAG.getTargetConstant(1, MVT::i8),   // Scale
11524       DAG.getRegister(0, MVT::i32),        // Index
11525       DAG.getTargetConstant(0, MVT::i32),  // Disp
11526       DAG.getRegister(0, MVT::i32),        // Segment.
11527       Zero,
11528       Chain
11529     };
11530     SDNode *Res =
11531       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11532                          array_lengthof(Ops));
11533     return SDValue(Res, 0);
11534   }
11535
11536   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11537   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11538 }
11539
11540
11541 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11542                              SelectionDAG &DAG) {
11543   EVT T = Op.getValueType();
11544   DebugLoc DL = Op.getDebugLoc();
11545   unsigned Reg = 0;
11546   unsigned size = 0;
11547   switch(T.getSimpleVT().SimpleTy) {
11548   default: llvm_unreachable("Invalid value type!");
11549   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11550   case MVT::i16: Reg = X86::AX;  size = 2; break;
11551   case MVT::i32: Reg = X86::EAX; size = 4; break;
11552   case MVT::i64:
11553     assert(Subtarget->is64Bit() && "Node not type legal!");
11554     Reg = X86::RAX; size = 8;
11555     break;
11556   }
11557   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11558                                     Op.getOperand(2), SDValue());
11559   SDValue Ops[] = { cpIn.getValue(0),
11560                     Op.getOperand(1),
11561                     Op.getOperand(3),
11562                     DAG.getTargetConstant(size, MVT::i8),
11563                     cpIn.getValue(1) };
11564   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11565   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11566   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11567                                            Ops, 5, T, MMO);
11568   SDValue cpOut =
11569     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11570   return cpOut;
11571 }
11572
11573 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11574                                      SelectionDAG &DAG) {
11575   assert(Subtarget->is64Bit() && "Result not type legalized?");
11576   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11577   SDValue TheChain = Op.getOperand(0);
11578   DebugLoc dl = Op.getDebugLoc();
11579   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11580   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11581   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11582                                    rax.getValue(2));
11583   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11584                             DAG.getConstant(32, MVT::i8));
11585   SDValue Ops[] = {
11586     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11587     rdx.getValue(1)
11588   };
11589   return DAG.getMergeValues(Ops, 2, dl);
11590 }
11591
11592 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11593   EVT SrcVT = Op.getOperand(0).getValueType();
11594   EVT DstVT = Op.getValueType();
11595   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11596          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11597   assert((DstVT == MVT::i64 ||
11598           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11599          "Unexpected custom BITCAST");
11600   // i64 <=> MMX conversions are Legal.
11601   if (SrcVT==MVT::i64 && DstVT.isVector())
11602     return Op;
11603   if (DstVT==MVT::i64 && SrcVT.isVector())
11604     return Op;
11605   // MMX <=> MMX conversions are Legal.
11606   if (SrcVT.isVector() && DstVT.isVector())
11607     return Op;
11608   // All other conversions need to be expanded.
11609   return SDValue();
11610 }
11611
11612 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11613   SDNode *Node = Op.getNode();
11614   DebugLoc dl = Node->getDebugLoc();
11615   EVT T = Node->getValueType(0);
11616   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11617                               DAG.getConstant(0, T), Node->getOperand(2));
11618   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11619                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11620                        Node->getOperand(0),
11621                        Node->getOperand(1), negOp,
11622                        cast<AtomicSDNode>(Node)->getSrcValue(),
11623                        cast<AtomicSDNode>(Node)->getAlignment(),
11624                        cast<AtomicSDNode>(Node)->getOrdering(),
11625                        cast<AtomicSDNode>(Node)->getSynchScope());
11626 }
11627
11628 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11629   SDNode *Node = Op.getNode();
11630   DebugLoc dl = Node->getDebugLoc();
11631   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11632
11633   // Convert seq_cst store -> xchg
11634   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11635   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11636   //        (The only way to get a 16-byte store is cmpxchg16b)
11637   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11638   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11639       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11640     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11641                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11642                                  Node->getOperand(0),
11643                                  Node->getOperand(1), Node->getOperand(2),
11644                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11645                                  cast<AtomicSDNode>(Node)->getOrdering(),
11646                                  cast<AtomicSDNode>(Node)->getSynchScope());
11647     return Swap.getValue(1);
11648   }
11649   // Other atomic stores have a simple pattern.
11650   return Op;
11651 }
11652
11653 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11654   EVT VT = Op.getNode()->getValueType(0);
11655
11656   // Let legalize expand this if it isn't a legal type yet.
11657   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11658     return SDValue();
11659
11660   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11661
11662   unsigned Opc;
11663   bool ExtraOp = false;
11664   switch (Op.getOpcode()) {
11665   default: llvm_unreachable("Invalid code");
11666   case ISD::ADDC: Opc = X86ISD::ADD; break;
11667   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11668   case ISD::SUBC: Opc = X86ISD::SUB; break;
11669   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11670   }
11671
11672   if (!ExtraOp)
11673     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11674                        Op.getOperand(1));
11675   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11676                      Op.getOperand(1), Op.getOperand(2));
11677 }
11678
11679 /// LowerOperation - Provide custom lowering hooks for some operations.
11680 ///
11681 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11682   switch (Op.getOpcode()) {
11683   default: llvm_unreachable("Should not custom lower this!");
11684   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11685   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11686   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11687   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11688   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11689   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11690   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11691   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11692   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11693   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11694   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11695   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11696   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11697   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11698   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11699   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11700   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11701   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11702   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11703   case ISD::SHL_PARTS:
11704   case ISD::SRA_PARTS:
11705   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11706   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11707   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11708   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11709   case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11710   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11711   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11712   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11713   case ISD::FABS:               return LowerFABS(Op, DAG);
11714   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11715   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11716   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11717   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11718   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11719   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11720   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11721   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11722   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11723   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11724   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11725   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11726   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11727   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11728   case ISD::FRAME_TO_ARGS_OFFSET:
11729                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11730   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11731   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11732   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11733   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11734   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11735   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11736   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11737   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11738   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11739   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11740   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11741   case ISD::SRA:
11742   case ISD::SRL:
11743   case ISD::SHL:                return LowerShift(Op, DAG);
11744   case ISD::SADDO:
11745   case ISD::UADDO:
11746   case ISD::SSUBO:
11747   case ISD::USUBO:
11748   case ISD::SMULO:
11749   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11750   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11751   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11752   case ISD::ADDC:
11753   case ISD::ADDE:
11754   case ISD::SUBC:
11755   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11756   case ISD::ADD:                return LowerADD(Op, DAG);
11757   case ISD::SUB:                return LowerSUB(Op, DAG);
11758   }
11759 }
11760
11761 static void ReplaceATOMIC_LOAD(SDNode *Node,
11762                                   SmallVectorImpl<SDValue> &Results,
11763                                   SelectionDAG &DAG) {
11764   DebugLoc dl = Node->getDebugLoc();
11765   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11766
11767   // Convert wide load -> cmpxchg8b/cmpxchg16b
11768   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11769   //        (The only way to get a 16-byte load is cmpxchg16b)
11770   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11771   SDValue Zero = DAG.getConstant(0, VT);
11772   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11773                                Node->getOperand(0),
11774                                Node->getOperand(1), Zero, Zero,
11775                                cast<AtomicSDNode>(Node)->getMemOperand(),
11776                                cast<AtomicSDNode>(Node)->getOrdering(),
11777                                cast<AtomicSDNode>(Node)->getSynchScope());
11778   Results.push_back(Swap.getValue(0));
11779   Results.push_back(Swap.getValue(1));
11780 }
11781
11782 static void
11783 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11784                         SelectionDAG &DAG, unsigned NewOp) {
11785   DebugLoc dl = Node->getDebugLoc();
11786   assert (Node->getValueType(0) == MVT::i64 &&
11787           "Only know how to expand i64 atomics");
11788
11789   SDValue Chain = Node->getOperand(0);
11790   SDValue In1 = Node->getOperand(1);
11791   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11792                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11793   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11794                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11795   SDValue Ops[] = { Chain, In1, In2L, In2H };
11796   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11797   SDValue Result =
11798     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11799                             cast<MemSDNode>(Node)->getMemOperand());
11800   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11801   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11802   Results.push_back(Result.getValue(2));
11803 }
11804
11805 /// ReplaceNodeResults - Replace a node with an illegal result type
11806 /// with a new node built out of custom code.
11807 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11808                                            SmallVectorImpl<SDValue>&Results,
11809                                            SelectionDAG &DAG) const {
11810   DebugLoc dl = N->getDebugLoc();
11811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11812   switch (N->getOpcode()) {
11813   default:
11814     llvm_unreachable("Do not know how to custom type legalize this operation!");
11815   case ISD::SIGN_EXTEND_INREG:
11816   case ISD::ADDC:
11817   case ISD::ADDE:
11818   case ISD::SUBC:
11819   case ISD::SUBE:
11820     // We don't want to expand or promote these.
11821     return;
11822   case ISD::FP_TO_SINT:
11823   case ISD::FP_TO_UINT: {
11824     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11825
11826     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11827       return;
11828
11829     std::pair<SDValue,SDValue> Vals =
11830         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11831     SDValue FIST = Vals.first, StackSlot = Vals.second;
11832     if (FIST.getNode() != 0) {
11833       EVT VT = N->getValueType(0);
11834       // Return a load from the stack slot.
11835       if (StackSlot.getNode() != 0)
11836         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11837                                       MachinePointerInfo(),
11838                                       false, false, false, 0));
11839       else
11840         Results.push_back(FIST);
11841     }
11842     return;
11843   }
11844   case ISD::UINT_TO_FP: {
11845     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11846         N->getValueType(0) != MVT::v2f32)
11847       return;
11848     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11849                                  N->getOperand(0));
11850     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11851                                      MVT::f64);
11852     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11853     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11854                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11855     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11856     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11857     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11858     return;
11859   }
11860   case ISD::FP_ROUND: {
11861     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
11862         return;
11863     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11864     Results.push_back(V);
11865     return;
11866   }
11867   case ISD::READCYCLECOUNTER: {
11868     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11869     SDValue TheChain = N->getOperand(0);
11870     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11871     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11872                                      rd.getValue(1));
11873     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11874                                      eax.getValue(2));
11875     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11876     SDValue Ops[] = { eax, edx };
11877     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11878     Results.push_back(edx.getValue(1));
11879     return;
11880   }
11881   case ISD::ATOMIC_CMP_SWAP: {
11882     EVT T = N->getValueType(0);
11883     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11884     bool Regs64bit = T == MVT::i128;
11885     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11886     SDValue cpInL, cpInH;
11887     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11888                         DAG.getConstant(0, HalfT));
11889     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11890                         DAG.getConstant(1, HalfT));
11891     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11892                              Regs64bit ? X86::RAX : X86::EAX,
11893                              cpInL, SDValue());
11894     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11895                              Regs64bit ? X86::RDX : X86::EDX,
11896                              cpInH, cpInL.getValue(1));
11897     SDValue swapInL, swapInH;
11898     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11899                           DAG.getConstant(0, HalfT));
11900     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11901                           DAG.getConstant(1, HalfT));
11902     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11903                                Regs64bit ? X86::RBX : X86::EBX,
11904                                swapInL, cpInH.getValue(1));
11905     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11906                                Regs64bit ? X86::RCX : X86::ECX,
11907                                swapInH, swapInL.getValue(1));
11908     SDValue Ops[] = { swapInH.getValue(0),
11909                       N->getOperand(1),
11910                       swapInH.getValue(1) };
11911     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11912     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11913     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11914                                   X86ISD::LCMPXCHG8_DAG;
11915     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11916                                              Ops, 3, T, MMO);
11917     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11918                                         Regs64bit ? X86::RAX : X86::EAX,
11919                                         HalfT, Result.getValue(1));
11920     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11921                                         Regs64bit ? X86::RDX : X86::EDX,
11922                                         HalfT, cpOutL.getValue(2));
11923     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11924     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11925     Results.push_back(cpOutH.getValue(1));
11926     return;
11927   }
11928   case ISD::ATOMIC_LOAD_ADD:
11929   case ISD::ATOMIC_LOAD_AND:
11930   case ISD::ATOMIC_LOAD_NAND:
11931   case ISD::ATOMIC_LOAD_OR:
11932   case ISD::ATOMIC_LOAD_SUB:
11933   case ISD::ATOMIC_LOAD_XOR:
11934   case ISD::ATOMIC_LOAD_MAX:
11935   case ISD::ATOMIC_LOAD_MIN:
11936   case ISD::ATOMIC_LOAD_UMAX:
11937   case ISD::ATOMIC_LOAD_UMIN:
11938   case ISD::ATOMIC_SWAP: {
11939     unsigned Opc;
11940     switch (N->getOpcode()) {
11941     default: llvm_unreachable("Unexpected opcode");
11942     case ISD::ATOMIC_LOAD_ADD:
11943       Opc = X86ISD::ATOMADD64_DAG;
11944       break;
11945     case ISD::ATOMIC_LOAD_AND:
11946       Opc = X86ISD::ATOMAND64_DAG;
11947       break;
11948     case ISD::ATOMIC_LOAD_NAND:
11949       Opc = X86ISD::ATOMNAND64_DAG;
11950       break;
11951     case ISD::ATOMIC_LOAD_OR:
11952       Opc = X86ISD::ATOMOR64_DAG;
11953       break;
11954     case ISD::ATOMIC_LOAD_SUB:
11955       Opc = X86ISD::ATOMSUB64_DAG;
11956       break;
11957     case ISD::ATOMIC_LOAD_XOR:
11958       Opc = X86ISD::ATOMXOR64_DAG;
11959       break;
11960     case ISD::ATOMIC_LOAD_MAX:
11961       Opc = X86ISD::ATOMMAX64_DAG;
11962       break;
11963     case ISD::ATOMIC_LOAD_MIN:
11964       Opc = X86ISD::ATOMMIN64_DAG;
11965       break;
11966     case ISD::ATOMIC_LOAD_UMAX:
11967       Opc = X86ISD::ATOMUMAX64_DAG;
11968       break;
11969     case ISD::ATOMIC_LOAD_UMIN:
11970       Opc = X86ISD::ATOMUMIN64_DAG;
11971       break;
11972     case ISD::ATOMIC_SWAP:
11973       Opc = X86ISD::ATOMSWAP64_DAG;
11974       break;
11975     }
11976     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11977     return;
11978   }
11979   case ISD::ATOMIC_LOAD:
11980     ReplaceATOMIC_LOAD(N, Results, DAG);
11981   }
11982 }
11983
11984 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11985   switch (Opcode) {
11986   default: return NULL;
11987   case X86ISD::BSF:                return "X86ISD::BSF";
11988   case X86ISD::BSR:                return "X86ISD::BSR";
11989   case X86ISD::SHLD:               return "X86ISD::SHLD";
11990   case X86ISD::SHRD:               return "X86ISD::SHRD";
11991   case X86ISD::FAND:               return "X86ISD::FAND";
11992   case X86ISD::FOR:                return "X86ISD::FOR";
11993   case X86ISD::FXOR:               return "X86ISD::FXOR";
11994   case X86ISD::FSRL:               return "X86ISD::FSRL";
11995   case X86ISD::FILD:               return "X86ISD::FILD";
11996   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11997   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11998   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11999   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12000   case X86ISD::FLD:                return "X86ISD::FLD";
12001   case X86ISD::FST:                return "X86ISD::FST";
12002   case X86ISD::CALL:               return "X86ISD::CALL";
12003   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12004   case X86ISD::BT:                 return "X86ISD::BT";
12005   case X86ISD::CMP:                return "X86ISD::CMP";
12006   case X86ISD::COMI:               return "X86ISD::COMI";
12007   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12008   case X86ISD::SETCC:              return "X86ISD::SETCC";
12009   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12010   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12011   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12012   case X86ISD::CMOV:               return "X86ISD::CMOV";
12013   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12014   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12015   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12016   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12017   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12018   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12019   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12020   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12021   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12022   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12023   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12024   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12025   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12026   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12027   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12028   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12029   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12030   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12031   case X86ISD::HADD:               return "X86ISD::HADD";
12032   case X86ISD::HSUB:               return "X86ISD::HSUB";
12033   case X86ISD::FHADD:              return "X86ISD::FHADD";
12034   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12035   case X86ISD::UMAX:               return "X86ISD::UMAX";
12036   case X86ISD::UMIN:               return "X86ISD::UMIN";
12037   case X86ISD::SMAX:               return "X86ISD::SMAX";
12038   case X86ISD::SMIN:               return "X86ISD::SMIN";
12039   case X86ISD::FMAX:               return "X86ISD::FMAX";
12040   case X86ISD::FMIN:               return "X86ISD::FMIN";
12041   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12042   case X86ISD::FMINC:              return "X86ISD::FMINC";
12043   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12044   case X86ISD::FRCP:               return "X86ISD::FRCP";
12045   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12046   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12047   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12048   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12049   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12050   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12051   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12052   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12053   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12054   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12055   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12056   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12057   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12058   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12059   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12060   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12061   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12062   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12063   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12064   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12065   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12066   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12067   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12068   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12069   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12070   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12071   case X86ISD::VSHL:               return "X86ISD::VSHL";
12072   case X86ISD::VSRL:               return "X86ISD::VSRL";
12073   case X86ISD::VSRA:               return "X86ISD::VSRA";
12074   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12075   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12076   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12077   case X86ISD::CMPP:               return "X86ISD::CMPP";
12078   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12079   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12080   case X86ISD::ADD:                return "X86ISD::ADD";
12081   case X86ISD::SUB:                return "X86ISD::SUB";
12082   case X86ISD::ADC:                return "X86ISD::ADC";
12083   case X86ISD::SBB:                return "X86ISD::SBB";
12084   case X86ISD::SMUL:               return "X86ISD::SMUL";
12085   case X86ISD::UMUL:               return "X86ISD::UMUL";
12086   case X86ISD::INC:                return "X86ISD::INC";
12087   case X86ISD::DEC:                return "X86ISD::DEC";
12088   case X86ISD::OR:                 return "X86ISD::OR";
12089   case X86ISD::XOR:                return "X86ISD::XOR";
12090   case X86ISD::AND:                return "X86ISD::AND";
12091   case X86ISD::BLSI:               return "X86ISD::BLSI";
12092   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12093   case X86ISD::BLSR:               return "X86ISD::BLSR";
12094   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12095   case X86ISD::PTEST:              return "X86ISD::PTEST";
12096   case X86ISD::TESTP:              return "X86ISD::TESTP";
12097   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12098   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12099   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12100   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12101   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12102   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12103   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12104   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12105   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12106   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12107   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12108   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12109   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12110   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12111   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12112   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12113   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12114   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12115   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12116   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12117   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12118   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12119   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12120   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12121   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12122   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12123   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12124   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12125   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12126   case X86ISD::SAHF:               return "X86ISD::SAHF";
12127   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12128   case X86ISD::FMADD:              return "X86ISD::FMADD";
12129   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12130   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12131   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12132   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12133   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12134   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12135   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12136   }
12137 }
12138
12139 // isLegalAddressingMode - Return true if the addressing mode represented
12140 // by AM is legal for this target, for a load/store of the specified type.
12141 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12142                                               Type *Ty) const {
12143   // X86 supports extremely general addressing modes.
12144   CodeModel::Model M = getTargetMachine().getCodeModel();
12145   Reloc::Model R = getTargetMachine().getRelocationModel();
12146
12147   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12148   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12149     return false;
12150
12151   if (AM.BaseGV) {
12152     unsigned GVFlags =
12153       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12154
12155     // If a reference to this global requires an extra load, we can't fold it.
12156     if (isGlobalStubReference(GVFlags))
12157       return false;
12158
12159     // If BaseGV requires a register for the PIC base, we cannot also have a
12160     // BaseReg specified.
12161     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12162       return false;
12163
12164     // If lower 4G is not available, then we must use rip-relative addressing.
12165     if ((M != CodeModel::Small || R != Reloc::Static) &&
12166         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12167       return false;
12168   }
12169
12170   switch (AM.Scale) {
12171   case 0:
12172   case 1:
12173   case 2:
12174   case 4:
12175   case 8:
12176     // These scales always work.
12177     break;
12178   case 3:
12179   case 5:
12180   case 9:
12181     // These scales are formed with basereg+scalereg.  Only accept if there is
12182     // no basereg yet.
12183     if (AM.HasBaseReg)
12184       return false;
12185     break;
12186   default:  // Other stuff never works.
12187     return false;
12188   }
12189
12190   return true;
12191 }
12192
12193
12194 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12195   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12196     return false;
12197   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12198   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12199   if (NumBits1 <= NumBits2)
12200     return false;
12201   return true;
12202 }
12203
12204 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12205   return Imm == (int32_t)Imm;
12206 }
12207
12208 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12209   // Can also use sub to handle negated immediates.
12210   return Imm == (int32_t)Imm;
12211 }
12212
12213 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12214   if (!VT1.isInteger() || !VT2.isInteger())
12215     return false;
12216   unsigned NumBits1 = VT1.getSizeInBits();
12217   unsigned NumBits2 = VT2.getSizeInBits();
12218   if (NumBits1 <= NumBits2)
12219     return false;
12220   return true;
12221 }
12222
12223 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12224   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12225   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12226 }
12227
12228 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12229   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12230   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12231 }
12232
12233 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12234   EVT VT1 = Val.getValueType();
12235   if (isZExtFree(VT1, VT2))
12236     return true;
12237
12238   if (Val.getOpcode() != ISD::LOAD)
12239     return false;
12240
12241   if (!VT1.isSimple() || !VT1.isInteger() ||
12242       !VT2.isSimple() || !VT2.isInteger())
12243     return false;
12244
12245   switch (VT1.getSimpleVT().SimpleTy) {
12246   default: break;
12247   case MVT::i8:
12248   case MVT::i16:
12249   case MVT::i32:
12250     // X86 has 8, 16, and 32-bit zero-extending loads.
12251     return true;
12252   }
12253
12254   return false;
12255 }
12256
12257 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12258   // i16 instructions are longer (0x66 prefix) and potentially slower.
12259   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12260 }
12261
12262 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12263 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12264 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12265 /// are assumed to be legal.
12266 bool
12267 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12268                                       EVT VT) const {
12269   // Very little shuffling can be done for 64-bit vectors right now.
12270   if (VT.getSizeInBits() == 64)
12271     return false;
12272
12273   // FIXME: pshufb, blends, shifts.
12274   return (VT.getVectorNumElements() == 2 ||
12275           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12276           isMOVLMask(M, VT) ||
12277           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12278           isPSHUFDMask(M, VT) ||
12279           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12280           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12281           isPALIGNRMask(M, VT, Subtarget) ||
12282           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12283           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12284           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12285           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12286 }
12287
12288 bool
12289 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12290                                           EVT VT) const {
12291   unsigned NumElts = VT.getVectorNumElements();
12292   // FIXME: This collection of masks seems suspect.
12293   if (NumElts == 2)
12294     return true;
12295   if (NumElts == 4 && VT.is128BitVector()) {
12296     return (isMOVLMask(Mask, VT)  ||
12297             isCommutedMOVLMask(Mask, VT, true) ||
12298             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12299             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12300   }
12301   return false;
12302 }
12303
12304 //===----------------------------------------------------------------------===//
12305 //                           X86 Scheduler Hooks
12306 //===----------------------------------------------------------------------===//
12307
12308 /// Utility function to emit xbegin specifying the start of an RTM region.
12309 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12310                                      const TargetInstrInfo *TII) {
12311   DebugLoc DL = MI->getDebugLoc();
12312
12313   const BasicBlock *BB = MBB->getBasicBlock();
12314   MachineFunction::iterator I = MBB;
12315   ++I;
12316
12317   // For the v = xbegin(), we generate
12318   //
12319   // thisMBB:
12320   //  xbegin sinkMBB
12321   //
12322   // mainMBB:
12323   //  eax = -1
12324   //
12325   // sinkMBB:
12326   //  v = eax
12327
12328   MachineBasicBlock *thisMBB = MBB;
12329   MachineFunction *MF = MBB->getParent();
12330   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12331   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12332   MF->insert(I, mainMBB);
12333   MF->insert(I, sinkMBB);
12334
12335   // Transfer the remainder of BB and its successor edges to sinkMBB.
12336   sinkMBB->splice(sinkMBB->begin(), MBB,
12337                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12338   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12339
12340   // thisMBB:
12341   //  xbegin sinkMBB
12342   //  # fallthrough to mainMBB
12343   //  # abortion to sinkMBB
12344   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12345   thisMBB->addSuccessor(mainMBB);
12346   thisMBB->addSuccessor(sinkMBB);
12347
12348   // mainMBB:
12349   //  EAX = -1
12350   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12351   mainMBB->addSuccessor(sinkMBB);
12352
12353   // sinkMBB:
12354   // EAX is live into the sinkMBB
12355   sinkMBB->addLiveIn(X86::EAX);
12356   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12357           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12358     .addReg(X86::EAX);
12359
12360   MI->eraseFromParent();
12361   return sinkMBB;
12362 }
12363
12364 // Get CMPXCHG opcode for the specified data type.
12365 static unsigned getCmpXChgOpcode(EVT VT) {
12366   switch (VT.getSimpleVT().SimpleTy) {
12367   case MVT::i8:  return X86::LCMPXCHG8;
12368   case MVT::i16: return X86::LCMPXCHG16;
12369   case MVT::i32: return X86::LCMPXCHG32;
12370   case MVT::i64: return X86::LCMPXCHG64;
12371   default:
12372     break;
12373   }
12374   llvm_unreachable("Invalid operand size!");
12375 }
12376
12377 // Get LOAD opcode for the specified data type.
12378 static unsigned getLoadOpcode(EVT VT) {
12379   switch (VT.getSimpleVT().SimpleTy) {
12380   case MVT::i8:  return X86::MOV8rm;
12381   case MVT::i16: return X86::MOV16rm;
12382   case MVT::i32: return X86::MOV32rm;
12383   case MVT::i64: return X86::MOV64rm;
12384   default:
12385     break;
12386   }
12387   llvm_unreachable("Invalid operand size!");
12388 }
12389
12390 // Get opcode of the non-atomic one from the specified atomic instruction.
12391 static unsigned getNonAtomicOpcode(unsigned Opc) {
12392   switch (Opc) {
12393   case X86::ATOMAND8:  return X86::AND8rr;
12394   case X86::ATOMAND16: return X86::AND16rr;
12395   case X86::ATOMAND32: return X86::AND32rr;
12396   case X86::ATOMAND64: return X86::AND64rr;
12397   case X86::ATOMOR8:   return X86::OR8rr;
12398   case X86::ATOMOR16:  return X86::OR16rr;
12399   case X86::ATOMOR32:  return X86::OR32rr;
12400   case X86::ATOMOR64:  return X86::OR64rr;
12401   case X86::ATOMXOR8:  return X86::XOR8rr;
12402   case X86::ATOMXOR16: return X86::XOR16rr;
12403   case X86::ATOMXOR32: return X86::XOR32rr;
12404   case X86::ATOMXOR64: return X86::XOR64rr;
12405   }
12406   llvm_unreachable("Unhandled atomic-load-op opcode!");
12407 }
12408
12409 // Get opcode of the non-atomic one from the specified atomic instruction with
12410 // extra opcode.
12411 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12412                                                unsigned &ExtraOpc) {
12413   switch (Opc) {
12414   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12415   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12416   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12417   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12418   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12419   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12420   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12421   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12422   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12423   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12424   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12425   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12426   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12427   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12428   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12429   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12430   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12431   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12432   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12433   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12434   }
12435   llvm_unreachable("Unhandled atomic-load-op opcode!");
12436 }
12437
12438 // Get opcode of the non-atomic one from the specified atomic instruction for
12439 // 64-bit data type on 32-bit target.
12440 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12441   switch (Opc) {
12442   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12443   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12444   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12445   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12446   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12447   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12448   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12449   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12450   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12451   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12452   }
12453   llvm_unreachable("Unhandled atomic-load-op opcode!");
12454 }
12455
12456 // Get opcode of the non-atomic one from the specified atomic instruction for
12457 // 64-bit data type on 32-bit target with extra opcode.
12458 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12459                                                    unsigned &HiOpc,
12460                                                    unsigned &ExtraOpc) {
12461   switch (Opc) {
12462   case X86::ATOMNAND6432:
12463     ExtraOpc = X86::NOT32r;
12464     HiOpc = X86::AND32rr;
12465     return X86::AND32rr;
12466   }
12467   llvm_unreachable("Unhandled atomic-load-op opcode!");
12468 }
12469
12470 // Get pseudo CMOV opcode from the specified data type.
12471 static unsigned getPseudoCMOVOpc(EVT VT) {
12472   switch (VT.getSimpleVT().SimpleTy) {
12473   case MVT::i8:  return X86::CMOV_GR8;
12474   case MVT::i16: return X86::CMOV_GR16;
12475   case MVT::i32: return X86::CMOV_GR32;
12476   default:
12477     break;
12478   }
12479   llvm_unreachable("Unknown CMOV opcode!");
12480 }
12481
12482 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12483 // They will be translated into a spin-loop or compare-exchange loop from
12484 //
12485 //    ...
12486 //    dst = atomic-fetch-op MI.addr, MI.val
12487 //    ...
12488 //
12489 // to
12490 //
12491 //    ...
12492 //    EAX = LOAD MI.addr
12493 // loop:
12494 //    t1 = OP MI.val, EAX
12495 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12496 //    JNE loop
12497 // sink:
12498 //    dst = EAX
12499 //    ...
12500 MachineBasicBlock *
12501 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12502                                        MachineBasicBlock *MBB) const {
12503   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12504   DebugLoc DL = MI->getDebugLoc();
12505
12506   MachineFunction *MF = MBB->getParent();
12507   MachineRegisterInfo &MRI = MF->getRegInfo();
12508
12509   const BasicBlock *BB = MBB->getBasicBlock();
12510   MachineFunction::iterator I = MBB;
12511   ++I;
12512
12513   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12514          "Unexpected number of operands");
12515
12516   assert(MI->hasOneMemOperand() &&
12517          "Expected atomic-load-op to have one memoperand");
12518
12519   // Memory Reference
12520   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12521   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12522
12523   unsigned DstReg, SrcReg;
12524   unsigned MemOpndSlot;
12525
12526   unsigned CurOp = 0;
12527
12528   DstReg = MI->getOperand(CurOp++).getReg();
12529   MemOpndSlot = CurOp;
12530   CurOp += X86::AddrNumOperands;
12531   SrcReg = MI->getOperand(CurOp++).getReg();
12532
12533   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12534   MVT::SimpleValueType VT = *RC->vt_begin();
12535   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12536
12537   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12538   unsigned LOADOpc = getLoadOpcode(VT);
12539
12540   // For the atomic load-arith operator, we generate
12541   //
12542   //  thisMBB:
12543   //    EAX = LOAD [MI.addr]
12544   //  mainMBB:
12545   //    t1 = OP MI.val, EAX
12546   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12547   //    JNE mainMBB
12548   //  sinkMBB:
12549
12550   MachineBasicBlock *thisMBB = MBB;
12551   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12552   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12553   MF->insert(I, mainMBB);
12554   MF->insert(I, sinkMBB);
12555
12556   MachineInstrBuilder MIB;
12557
12558   // Transfer the remainder of BB and its successor edges to sinkMBB.
12559   sinkMBB->splice(sinkMBB->begin(), MBB,
12560                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12561   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12562
12563   // thisMBB:
12564   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12565   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12566     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12567   MIB.setMemRefs(MMOBegin, MMOEnd);
12568
12569   thisMBB->addSuccessor(mainMBB);
12570
12571   // mainMBB:
12572   MachineBasicBlock *origMainMBB = mainMBB;
12573   mainMBB->addLiveIn(AccPhyReg);
12574
12575   // Copy AccPhyReg as it is used more than once.
12576   unsigned AccReg = MRI.createVirtualRegister(RC);
12577   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12578     .addReg(AccPhyReg);
12579
12580   unsigned t1 = MRI.createVirtualRegister(RC);
12581   unsigned Opc = MI->getOpcode();
12582   switch (Opc) {
12583   default:
12584     llvm_unreachable("Unhandled atomic-load-op opcode!");
12585   case X86::ATOMAND8:
12586   case X86::ATOMAND16:
12587   case X86::ATOMAND32:
12588   case X86::ATOMAND64:
12589   case X86::ATOMOR8:
12590   case X86::ATOMOR16:
12591   case X86::ATOMOR32:
12592   case X86::ATOMOR64:
12593   case X86::ATOMXOR8:
12594   case X86::ATOMXOR16:
12595   case X86::ATOMXOR32:
12596   case X86::ATOMXOR64: {
12597     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12598     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12599       .addReg(AccReg);
12600     break;
12601   }
12602   case X86::ATOMNAND8:
12603   case X86::ATOMNAND16:
12604   case X86::ATOMNAND32:
12605   case X86::ATOMNAND64: {
12606     unsigned t2 = MRI.createVirtualRegister(RC);
12607     unsigned NOTOpc;
12608     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12609     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12610       .addReg(AccReg);
12611     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12612     break;
12613   }
12614   case X86::ATOMMAX8:
12615   case X86::ATOMMAX16:
12616   case X86::ATOMMAX32:
12617   case X86::ATOMMAX64:
12618   case X86::ATOMMIN8:
12619   case X86::ATOMMIN16:
12620   case X86::ATOMMIN32:
12621   case X86::ATOMMIN64:
12622   case X86::ATOMUMAX8:
12623   case X86::ATOMUMAX16:
12624   case X86::ATOMUMAX32:
12625   case X86::ATOMUMAX64:
12626   case X86::ATOMUMIN8:
12627   case X86::ATOMUMIN16:
12628   case X86::ATOMUMIN32:
12629   case X86::ATOMUMIN64: {
12630     unsigned CMPOpc;
12631     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12632
12633     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12634       .addReg(SrcReg)
12635       .addReg(AccReg);
12636
12637     if (Subtarget->hasCMov()) {
12638       if (VT != MVT::i8) {
12639         // Native support
12640         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12641           .addReg(SrcReg)
12642           .addReg(AccReg);
12643       } else {
12644         // Promote i8 to i32 to use CMOV32
12645         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12646         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12647         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12648         unsigned t2 = MRI.createVirtualRegister(RC32);
12649
12650         unsigned Undef = MRI.createVirtualRegister(RC32);
12651         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12652
12653         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12654           .addReg(Undef)
12655           .addReg(SrcReg)
12656           .addImm(X86::sub_8bit);
12657         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12658           .addReg(Undef)
12659           .addReg(AccReg)
12660           .addImm(X86::sub_8bit);
12661
12662         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12663           .addReg(SrcReg32)
12664           .addReg(AccReg32);
12665
12666         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12667           .addReg(t2, 0, X86::sub_8bit);
12668       }
12669     } else {
12670       // Use pseudo select and lower them.
12671       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12672              "Invalid atomic-load-op transformation!");
12673       unsigned SelOpc = getPseudoCMOVOpc(VT);
12674       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12675       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12676       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12677               .addReg(SrcReg).addReg(AccReg)
12678               .addImm(CC);
12679       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12680     }
12681     break;
12682   }
12683   }
12684
12685   // Copy AccPhyReg back from virtual register.
12686   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12687     .addReg(AccReg);
12688
12689   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12690   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12691     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12692   MIB.addReg(t1);
12693   MIB.setMemRefs(MMOBegin, MMOEnd);
12694
12695   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12696
12697   mainMBB->addSuccessor(origMainMBB);
12698   mainMBB->addSuccessor(sinkMBB);
12699
12700   // sinkMBB:
12701   sinkMBB->addLiveIn(AccPhyReg);
12702
12703   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12704           TII->get(TargetOpcode::COPY), DstReg)
12705     .addReg(AccPhyReg);
12706
12707   MI->eraseFromParent();
12708   return sinkMBB;
12709 }
12710
12711 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12712 // instructions. They will be translated into a spin-loop or compare-exchange
12713 // loop from
12714 //
12715 //    ...
12716 //    dst = atomic-fetch-op MI.addr, MI.val
12717 //    ...
12718 //
12719 // to
12720 //
12721 //    ...
12722 //    EAX = LOAD [MI.addr + 0]
12723 //    EDX = LOAD [MI.addr + 4]
12724 // loop:
12725 //    EBX = OP MI.val.lo, EAX
12726 //    ECX = OP MI.val.hi, EDX
12727 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12728 //    JNE loop
12729 // sink:
12730 //    dst = EDX:EAX
12731 //    ...
12732 MachineBasicBlock *
12733 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12734                                            MachineBasicBlock *MBB) const {
12735   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12736   DebugLoc DL = MI->getDebugLoc();
12737
12738   MachineFunction *MF = MBB->getParent();
12739   MachineRegisterInfo &MRI = MF->getRegInfo();
12740
12741   const BasicBlock *BB = MBB->getBasicBlock();
12742   MachineFunction::iterator I = MBB;
12743   ++I;
12744
12745   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12746          "Unexpected number of operands");
12747
12748   assert(MI->hasOneMemOperand() &&
12749          "Expected atomic-load-op32 to have one memoperand");
12750
12751   // Memory Reference
12752   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12753   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12754
12755   unsigned DstLoReg, DstHiReg;
12756   unsigned SrcLoReg, SrcHiReg;
12757   unsigned MemOpndSlot;
12758
12759   unsigned CurOp = 0;
12760
12761   DstLoReg = MI->getOperand(CurOp++).getReg();
12762   DstHiReg = MI->getOperand(CurOp++).getReg();
12763   MemOpndSlot = CurOp;
12764   CurOp += X86::AddrNumOperands;
12765   SrcLoReg = MI->getOperand(CurOp++).getReg();
12766   SrcHiReg = MI->getOperand(CurOp++).getReg();
12767
12768   const TargetRegisterClass *RC = &X86::GR32RegClass;
12769   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12770
12771   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12772   unsigned LOADOpc = X86::MOV32rm;
12773
12774   // For the atomic load-arith operator, we generate
12775   //
12776   //  thisMBB:
12777   //    EAX = LOAD [MI.addr + 0]
12778   //    EDX = LOAD [MI.addr + 4]
12779   //  mainMBB:
12780   //    EBX = OP MI.vallo, EAX
12781   //    ECX = OP MI.valhi, EDX
12782   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12783   //    JNE mainMBB
12784   //  sinkMBB:
12785
12786   MachineBasicBlock *thisMBB = MBB;
12787   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12788   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12789   MF->insert(I, mainMBB);
12790   MF->insert(I, sinkMBB);
12791
12792   MachineInstrBuilder MIB;
12793
12794   // Transfer the remainder of BB and its successor edges to sinkMBB.
12795   sinkMBB->splice(sinkMBB->begin(), MBB,
12796                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12797   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12798
12799   // thisMBB:
12800   // Lo
12801   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12802   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12803     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12804   MIB.setMemRefs(MMOBegin, MMOEnd);
12805   // Hi
12806   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12807   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12808     if (i == X86::AddrDisp)
12809       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12810     else
12811       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12812   }
12813   MIB.setMemRefs(MMOBegin, MMOEnd);
12814
12815   thisMBB->addSuccessor(mainMBB);
12816
12817   // mainMBB:
12818   MachineBasicBlock *origMainMBB = mainMBB;
12819   mainMBB->addLiveIn(X86::EAX);
12820   mainMBB->addLiveIn(X86::EDX);
12821
12822   // Copy EDX:EAX as they are used more than once.
12823   unsigned LoReg = MRI.createVirtualRegister(RC);
12824   unsigned HiReg = MRI.createVirtualRegister(RC);
12825   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12826   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12827
12828   unsigned t1L = MRI.createVirtualRegister(RC);
12829   unsigned t1H = MRI.createVirtualRegister(RC);
12830
12831   unsigned Opc = MI->getOpcode();
12832   switch (Opc) {
12833   default:
12834     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12835   case X86::ATOMAND6432:
12836   case X86::ATOMOR6432:
12837   case X86::ATOMXOR6432:
12838   case X86::ATOMADD6432:
12839   case X86::ATOMSUB6432: {
12840     unsigned HiOpc;
12841     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12842     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
12843     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
12844     break;
12845   }
12846   case X86::ATOMNAND6432: {
12847     unsigned HiOpc, NOTOpc;
12848     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12849     unsigned t2L = MRI.createVirtualRegister(RC);
12850     unsigned t2H = MRI.createVirtualRegister(RC);
12851     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12852     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12853     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12854     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12855     break;
12856   }
12857   case X86::ATOMMAX6432:
12858   case X86::ATOMMIN6432:
12859   case X86::ATOMUMAX6432:
12860   case X86::ATOMUMIN6432: {
12861     unsigned HiOpc;
12862     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12863     unsigned cL = MRI.createVirtualRegister(RC8);
12864     unsigned cH = MRI.createVirtualRegister(RC8);
12865     unsigned cL32 = MRI.createVirtualRegister(RC);
12866     unsigned cH32 = MRI.createVirtualRegister(RC);
12867     unsigned cc = MRI.createVirtualRegister(RC);
12868     // cl := cmp src_lo, lo
12869     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12870       .addReg(SrcLoReg).addReg(LoReg);
12871     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12872     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12873     // ch := cmp src_hi, hi
12874     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12875       .addReg(SrcHiReg).addReg(HiReg);
12876     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12877     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12878     // cc := if (src_hi == hi) ? cl : ch;
12879     if (Subtarget->hasCMov()) {
12880       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12881         .addReg(cH32).addReg(cL32);
12882     } else {
12883       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12884               .addReg(cH32).addReg(cL32)
12885               .addImm(X86::COND_E);
12886       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12887     }
12888     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12889     if (Subtarget->hasCMov()) {
12890       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12891         .addReg(SrcLoReg).addReg(LoReg);
12892       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12893         .addReg(SrcHiReg).addReg(HiReg);
12894     } else {
12895       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12896               .addReg(SrcLoReg).addReg(LoReg)
12897               .addImm(X86::COND_NE);
12898       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12899       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12900               .addReg(SrcHiReg).addReg(HiReg)
12901               .addImm(X86::COND_NE);
12902       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12903     }
12904     break;
12905   }
12906   case X86::ATOMSWAP6432: {
12907     unsigned HiOpc;
12908     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12909     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12910     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12911     break;
12912   }
12913   }
12914
12915   // Copy EDX:EAX back from HiReg:LoReg
12916   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12917   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12918   // Copy ECX:EBX from t1H:t1L
12919   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12920   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12921
12922   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12923   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12924     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12925   MIB.setMemRefs(MMOBegin, MMOEnd);
12926
12927   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12928
12929   mainMBB->addSuccessor(origMainMBB);
12930   mainMBB->addSuccessor(sinkMBB);
12931
12932   // sinkMBB:
12933   sinkMBB->addLiveIn(X86::EAX);
12934   sinkMBB->addLiveIn(X86::EDX);
12935
12936   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12937           TII->get(TargetOpcode::COPY), DstLoReg)
12938     .addReg(X86::EAX);
12939   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12940           TII->get(TargetOpcode::COPY), DstHiReg)
12941     .addReg(X86::EDX);
12942
12943   MI->eraseFromParent();
12944   return sinkMBB;
12945 }
12946
12947 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12948 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12949 // in the .td file.
12950 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
12951                                        const TargetInstrInfo *TII) {
12952   unsigned Opc;
12953   switch (MI->getOpcode()) {
12954   default: llvm_unreachable("illegal opcode!");
12955   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
12956   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
12957   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
12958   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
12959   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
12960   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
12961   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
12962   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
12963   }
12964
12965   DebugLoc dl = MI->getDebugLoc();
12966   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12967
12968   unsigned NumArgs = MI->getNumOperands();
12969   for (unsigned i = 1; i < NumArgs; ++i) {
12970     MachineOperand &Op = MI->getOperand(i);
12971     if (!(Op.isReg() && Op.isImplicit()))
12972       MIB.addOperand(Op);
12973   }
12974   if (MI->hasOneMemOperand())
12975     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12976
12977   BuildMI(*BB, MI, dl,
12978     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12979     .addReg(X86::XMM0);
12980
12981   MI->eraseFromParent();
12982   return BB;
12983 }
12984
12985 // FIXME: Custom handling because TableGen doesn't support multiple implicit
12986 // defs in an instruction pattern
12987 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
12988                                        const TargetInstrInfo *TII) {
12989   unsigned Opc;
12990   switch (MI->getOpcode()) {
12991   default: llvm_unreachable("illegal opcode!");
12992   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
12993   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
12994   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
12995   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
12996   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
12997   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
12998   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
12999   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13000   }
13001
13002   DebugLoc dl = MI->getDebugLoc();
13003   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13004
13005   unsigned NumArgs = MI->getNumOperands(); // remove the results
13006   for (unsigned i = 1; i < NumArgs; ++i) {
13007     MachineOperand &Op = MI->getOperand(i);
13008     if (!(Op.isReg() && Op.isImplicit()))
13009       MIB.addOperand(Op);
13010   }
13011   if (MI->hasOneMemOperand())
13012     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13013
13014   BuildMI(*BB, MI, dl,
13015     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13016     .addReg(X86::ECX);
13017
13018   MI->eraseFromParent();
13019   return BB;
13020 }
13021
13022 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13023                                        const TargetInstrInfo *TII,
13024                                        const X86Subtarget* Subtarget) {
13025   DebugLoc dl = MI->getDebugLoc();
13026
13027   // Address into RAX/EAX, other two args into ECX, EDX.
13028   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13029   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13030   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13031   for (int i = 0; i < X86::AddrNumOperands; ++i)
13032     MIB.addOperand(MI->getOperand(i));
13033
13034   unsigned ValOps = X86::AddrNumOperands;
13035   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13036     .addReg(MI->getOperand(ValOps).getReg());
13037   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13038     .addReg(MI->getOperand(ValOps+1).getReg());
13039
13040   // The instruction doesn't actually take any operands though.
13041   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13042
13043   MI->eraseFromParent(); // The pseudo is gone now.
13044   return BB;
13045 }
13046
13047 MachineBasicBlock *
13048 X86TargetLowering::EmitVAARG64WithCustomInserter(
13049                    MachineInstr *MI,
13050                    MachineBasicBlock *MBB) const {
13051   // Emit va_arg instruction on X86-64.
13052
13053   // Operands to this pseudo-instruction:
13054   // 0  ) Output        : destination address (reg)
13055   // 1-5) Input         : va_list address (addr, i64mem)
13056   // 6  ) ArgSize       : Size (in bytes) of vararg type
13057   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13058   // 8  ) Align         : Alignment of type
13059   // 9  ) EFLAGS (implicit-def)
13060
13061   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13062   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13063
13064   unsigned DestReg = MI->getOperand(0).getReg();
13065   MachineOperand &Base = MI->getOperand(1);
13066   MachineOperand &Scale = MI->getOperand(2);
13067   MachineOperand &Index = MI->getOperand(3);
13068   MachineOperand &Disp = MI->getOperand(4);
13069   MachineOperand &Segment = MI->getOperand(5);
13070   unsigned ArgSize = MI->getOperand(6).getImm();
13071   unsigned ArgMode = MI->getOperand(7).getImm();
13072   unsigned Align = MI->getOperand(8).getImm();
13073
13074   // Memory Reference
13075   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13076   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13077   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13078
13079   // Machine Information
13080   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13081   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13082   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13083   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13084   DebugLoc DL = MI->getDebugLoc();
13085
13086   // struct va_list {
13087   //   i32   gp_offset
13088   //   i32   fp_offset
13089   //   i64   overflow_area (address)
13090   //   i64   reg_save_area (address)
13091   // }
13092   // sizeof(va_list) = 24
13093   // alignment(va_list) = 8
13094
13095   unsigned TotalNumIntRegs = 6;
13096   unsigned TotalNumXMMRegs = 8;
13097   bool UseGPOffset = (ArgMode == 1);
13098   bool UseFPOffset = (ArgMode == 2);
13099   unsigned MaxOffset = TotalNumIntRegs * 8 +
13100                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13101
13102   /* Align ArgSize to a multiple of 8 */
13103   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13104   bool NeedsAlign = (Align > 8);
13105
13106   MachineBasicBlock *thisMBB = MBB;
13107   MachineBasicBlock *overflowMBB;
13108   MachineBasicBlock *offsetMBB;
13109   MachineBasicBlock *endMBB;
13110
13111   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13112   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13113   unsigned OffsetReg = 0;
13114
13115   if (!UseGPOffset && !UseFPOffset) {
13116     // If we only pull from the overflow region, we don't create a branch.
13117     // We don't need to alter control flow.
13118     OffsetDestReg = 0; // unused
13119     OverflowDestReg = DestReg;
13120
13121     offsetMBB = NULL;
13122     overflowMBB = thisMBB;
13123     endMBB = thisMBB;
13124   } else {
13125     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13126     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13127     // If not, pull from overflow_area. (branch to overflowMBB)
13128     //
13129     //       thisMBB
13130     //         |     .
13131     //         |        .
13132     //     offsetMBB   overflowMBB
13133     //         |        .
13134     //         |     .
13135     //        endMBB
13136
13137     // Registers for the PHI in endMBB
13138     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13139     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13140
13141     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13142     MachineFunction *MF = MBB->getParent();
13143     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13144     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13145     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13146
13147     MachineFunction::iterator MBBIter = MBB;
13148     ++MBBIter;
13149
13150     // Insert the new basic blocks
13151     MF->insert(MBBIter, offsetMBB);
13152     MF->insert(MBBIter, overflowMBB);
13153     MF->insert(MBBIter, endMBB);
13154
13155     // Transfer the remainder of MBB and its successor edges to endMBB.
13156     endMBB->splice(endMBB->begin(), thisMBB,
13157                     llvm::next(MachineBasicBlock::iterator(MI)),
13158                     thisMBB->end());
13159     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13160
13161     // Make offsetMBB and overflowMBB successors of thisMBB
13162     thisMBB->addSuccessor(offsetMBB);
13163     thisMBB->addSuccessor(overflowMBB);
13164
13165     // endMBB is a successor of both offsetMBB and overflowMBB
13166     offsetMBB->addSuccessor(endMBB);
13167     overflowMBB->addSuccessor(endMBB);
13168
13169     // Load the offset value into a register
13170     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13171     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13172       .addOperand(Base)
13173       .addOperand(Scale)
13174       .addOperand(Index)
13175       .addDisp(Disp, UseFPOffset ? 4 : 0)
13176       .addOperand(Segment)
13177       .setMemRefs(MMOBegin, MMOEnd);
13178
13179     // Check if there is enough room left to pull this argument.
13180     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13181       .addReg(OffsetReg)
13182       .addImm(MaxOffset + 8 - ArgSizeA8);
13183
13184     // Branch to "overflowMBB" if offset >= max
13185     // Fall through to "offsetMBB" otherwise
13186     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13187       .addMBB(overflowMBB);
13188   }
13189
13190   // In offsetMBB, emit code to use the reg_save_area.
13191   if (offsetMBB) {
13192     assert(OffsetReg != 0);
13193
13194     // Read the reg_save_area address.
13195     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13196     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13197       .addOperand(Base)
13198       .addOperand(Scale)
13199       .addOperand(Index)
13200       .addDisp(Disp, 16)
13201       .addOperand(Segment)
13202       .setMemRefs(MMOBegin, MMOEnd);
13203
13204     // Zero-extend the offset
13205     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13206       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13207         .addImm(0)
13208         .addReg(OffsetReg)
13209         .addImm(X86::sub_32bit);
13210
13211     // Add the offset to the reg_save_area to get the final address.
13212     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13213       .addReg(OffsetReg64)
13214       .addReg(RegSaveReg);
13215
13216     // Compute the offset for the next argument
13217     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13218     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13219       .addReg(OffsetReg)
13220       .addImm(UseFPOffset ? 16 : 8);
13221
13222     // Store it back into the va_list.
13223     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13224       .addOperand(Base)
13225       .addOperand(Scale)
13226       .addOperand(Index)
13227       .addDisp(Disp, UseFPOffset ? 4 : 0)
13228       .addOperand(Segment)
13229       .addReg(NextOffsetReg)
13230       .setMemRefs(MMOBegin, MMOEnd);
13231
13232     // Jump to endMBB
13233     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13234       .addMBB(endMBB);
13235   }
13236
13237   //
13238   // Emit code to use overflow area
13239   //
13240
13241   // Load the overflow_area address into a register.
13242   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13243   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13244     .addOperand(Base)
13245     .addOperand(Scale)
13246     .addOperand(Index)
13247     .addDisp(Disp, 8)
13248     .addOperand(Segment)
13249     .setMemRefs(MMOBegin, MMOEnd);
13250
13251   // If we need to align it, do so. Otherwise, just copy the address
13252   // to OverflowDestReg.
13253   if (NeedsAlign) {
13254     // Align the overflow address
13255     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13256     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13257
13258     // aligned_addr = (addr + (align-1)) & ~(align-1)
13259     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13260       .addReg(OverflowAddrReg)
13261       .addImm(Align-1);
13262
13263     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13264       .addReg(TmpReg)
13265       .addImm(~(uint64_t)(Align-1));
13266   } else {
13267     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13268       .addReg(OverflowAddrReg);
13269   }
13270
13271   // Compute the next overflow address after this argument.
13272   // (the overflow address should be kept 8-byte aligned)
13273   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13274   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13275     .addReg(OverflowDestReg)
13276     .addImm(ArgSizeA8);
13277
13278   // Store the new overflow address.
13279   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13280     .addOperand(Base)
13281     .addOperand(Scale)
13282     .addOperand(Index)
13283     .addDisp(Disp, 8)
13284     .addOperand(Segment)
13285     .addReg(NextAddrReg)
13286     .setMemRefs(MMOBegin, MMOEnd);
13287
13288   // If we branched, emit the PHI to the front of endMBB.
13289   if (offsetMBB) {
13290     BuildMI(*endMBB, endMBB->begin(), DL,
13291             TII->get(X86::PHI), DestReg)
13292       .addReg(OffsetDestReg).addMBB(offsetMBB)
13293       .addReg(OverflowDestReg).addMBB(overflowMBB);
13294   }
13295
13296   // Erase the pseudo instruction
13297   MI->eraseFromParent();
13298
13299   return endMBB;
13300 }
13301
13302 MachineBasicBlock *
13303 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13304                                                  MachineInstr *MI,
13305                                                  MachineBasicBlock *MBB) const {
13306   // Emit code to save XMM registers to the stack. The ABI says that the
13307   // number of registers to save is given in %al, so it's theoretically
13308   // possible to do an indirect jump trick to avoid saving all of them,
13309   // however this code takes a simpler approach and just executes all
13310   // of the stores if %al is non-zero. It's less code, and it's probably
13311   // easier on the hardware branch predictor, and stores aren't all that
13312   // expensive anyway.
13313
13314   // Create the new basic blocks. One block contains all the XMM stores,
13315   // and one block is the final destination regardless of whether any
13316   // stores were performed.
13317   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13318   MachineFunction *F = MBB->getParent();
13319   MachineFunction::iterator MBBIter = MBB;
13320   ++MBBIter;
13321   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13322   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13323   F->insert(MBBIter, XMMSaveMBB);
13324   F->insert(MBBIter, EndMBB);
13325
13326   // Transfer the remainder of MBB and its successor edges to EndMBB.
13327   EndMBB->splice(EndMBB->begin(), MBB,
13328                  llvm::next(MachineBasicBlock::iterator(MI)),
13329                  MBB->end());
13330   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13331
13332   // The original block will now fall through to the XMM save block.
13333   MBB->addSuccessor(XMMSaveMBB);
13334   // The XMMSaveMBB will fall through to the end block.
13335   XMMSaveMBB->addSuccessor(EndMBB);
13336
13337   // Now add the instructions.
13338   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13339   DebugLoc DL = MI->getDebugLoc();
13340
13341   unsigned CountReg = MI->getOperand(0).getReg();
13342   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13343   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13344
13345   if (!Subtarget->isTargetWin64()) {
13346     // If %al is 0, branch around the XMM save block.
13347     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13348     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13349     MBB->addSuccessor(EndMBB);
13350   }
13351
13352   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13353   // In the XMM save block, save all the XMM argument registers.
13354   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13355     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13356     MachineMemOperand *MMO =
13357       F->getMachineMemOperand(
13358           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13359         MachineMemOperand::MOStore,
13360         /*Size=*/16, /*Align=*/16);
13361     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13362       .addFrameIndex(RegSaveFrameIndex)
13363       .addImm(/*Scale=*/1)
13364       .addReg(/*IndexReg=*/0)
13365       .addImm(/*Disp=*/Offset)
13366       .addReg(/*Segment=*/0)
13367       .addReg(MI->getOperand(i).getReg())
13368       .addMemOperand(MMO);
13369   }
13370
13371   MI->eraseFromParent();   // The pseudo instruction is gone now.
13372
13373   return EndMBB;
13374 }
13375
13376 // The EFLAGS operand of SelectItr might be missing a kill marker
13377 // because there were multiple uses of EFLAGS, and ISel didn't know
13378 // which to mark. Figure out whether SelectItr should have had a
13379 // kill marker, and set it if it should. Returns the correct kill
13380 // marker value.
13381 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13382                                      MachineBasicBlock* BB,
13383                                      const TargetRegisterInfo* TRI) {
13384   // Scan forward through BB for a use/def of EFLAGS.
13385   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13386   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13387     const MachineInstr& mi = *miI;
13388     if (mi.readsRegister(X86::EFLAGS))
13389       return false;
13390     if (mi.definesRegister(X86::EFLAGS))
13391       break; // Should have kill-flag - update below.
13392   }
13393
13394   // If we hit the end of the block, check whether EFLAGS is live into a
13395   // successor.
13396   if (miI == BB->end()) {
13397     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13398                                           sEnd = BB->succ_end();
13399          sItr != sEnd; ++sItr) {
13400       MachineBasicBlock* succ = *sItr;
13401       if (succ->isLiveIn(X86::EFLAGS))
13402         return false;
13403     }
13404   }
13405
13406   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13407   // out. SelectMI should have a kill flag on EFLAGS.
13408   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13409   return true;
13410 }
13411
13412 MachineBasicBlock *
13413 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13414                                      MachineBasicBlock *BB) const {
13415   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13416   DebugLoc DL = MI->getDebugLoc();
13417
13418   // To "insert" a SELECT_CC instruction, we actually have to insert the
13419   // diamond control-flow pattern.  The incoming instruction knows the
13420   // destination vreg to set, the condition code register to branch on, the
13421   // true/false values to select between, and a branch opcode to use.
13422   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13423   MachineFunction::iterator It = BB;
13424   ++It;
13425
13426   //  thisMBB:
13427   //  ...
13428   //   TrueVal = ...
13429   //   cmpTY ccX, r1, r2
13430   //   bCC copy1MBB
13431   //   fallthrough --> copy0MBB
13432   MachineBasicBlock *thisMBB = BB;
13433   MachineFunction *F = BB->getParent();
13434   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13435   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13436   F->insert(It, copy0MBB);
13437   F->insert(It, sinkMBB);
13438
13439   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13440   // live into the sink and copy blocks.
13441   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13442   if (!MI->killsRegister(X86::EFLAGS) &&
13443       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13444     copy0MBB->addLiveIn(X86::EFLAGS);
13445     sinkMBB->addLiveIn(X86::EFLAGS);
13446   }
13447
13448   // Transfer the remainder of BB and its successor edges to sinkMBB.
13449   sinkMBB->splice(sinkMBB->begin(), BB,
13450                   llvm::next(MachineBasicBlock::iterator(MI)),
13451                   BB->end());
13452   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13453
13454   // Add the true and fallthrough blocks as its successors.
13455   BB->addSuccessor(copy0MBB);
13456   BB->addSuccessor(sinkMBB);
13457
13458   // Create the conditional branch instruction.
13459   unsigned Opc =
13460     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13461   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13462
13463   //  copy0MBB:
13464   //   %FalseValue = ...
13465   //   # fallthrough to sinkMBB
13466   copy0MBB->addSuccessor(sinkMBB);
13467
13468   //  sinkMBB:
13469   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13470   //  ...
13471   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13472           TII->get(X86::PHI), MI->getOperand(0).getReg())
13473     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13474     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13475
13476   MI->eraseFromParent();   // The pseudo instruction is gone now.
13477   return sinkMBB;
13478 }
13479
13480 MachineBasicBlock *
13481 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13482                                         bool Is64Bit) const {
13483   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13484   DebugLoc DL = MI->getDebugLoc();
13485   MachineFunction *MF = BB->getParent();
13486   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13487
13488   assert(getTargetMachine().Options.EnableSegmentedStacks);
13489
13490   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13491   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13492
13493   // BB:
13494   //  ... [Till the alloca]
13495   // If stacklet is not large enough, jump to mallocMBB
13496   //
13497   // bumpMBB:
13498   //  Allocate by subtracting from RSP
13499   //  Jump to continueMBB
13500   //
13501   // mallocMBB:
13502   //  Allocate by call to runtime
13503   //
13504   // continueMBB:
13505   //  ...
13506   //  [rest of original BB]
13507   //
13508
13509   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13510   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13511   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13512
13513   MachineRegisterInfo &MRI = MF->getRegInfo();
13514   const TargetRegisterClass *AddrRegClass =
13515     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13516
13517   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13518     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13519     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13520     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13521     sizeVReg = MI->getOperand(1).getReg(),
13522     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13523
13524   MachineFunction::iterator MBBIter = BB;
13525   ++MBBIter;
13526
13527   MF->insert(MBBIter, bumpMBB);
13528   MF->insert(MBBIter, mallocMBB);
13529   MF->insert(MBBIter, continueMBB);
13530
13531   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13532                       (MachineBasicBlock::iterator(MI)), BB->end());
13533   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13534
13535   // Add code to the main basic block to check if the stack limit has been hit,
13536   // and if so, jump to mallocMBB otherwise to bumpMBB.
13537   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13538   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13539     .addReg(tmpSPVReg).addReg(sizeVReg);
13540   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13541     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13542     .addReg(SPLimitVReg);
13543   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13544
13545   // bumpMBB simply decreases the stack pointer, since we know the current
13546   // stacklet has enough space.
13547   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13548     .addReg(SPLimitVReg);
13549   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13550     .addReg(SPLimitVReg);
13551   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13552
13553   // Calls into a routine in libgcc to allocate more space from the heap.
13554   const uint32_t *RegMask =
13555     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13556   if (Is64Bit) {
13557     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13558       .addReg(sizeVReg);
13559     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13560       .addExternalSymbol("__morestack_allocate_stack_space")
13561       .addRegMask(RegMask)
13562       .addReg(X86::RDI, RegState::Implicit)
13563       .addReg(X86::RAX, RegState::ImplicitDefine);
13564   } else {
13565     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13566       .addImm(12);
13567     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13568     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13569       .addExternalSymbol("__morestack_allocate_stack_space")
13570       .addRegMask(RegMask)
13571       .addReg(X86::EAX, RegState::ImplicitDefine);
13572   }
13573
13574   if (!Is64Bit)
13575     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13576       .addImm(16);
13577
13578   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13579     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13580   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13581
13582   // Set up the CFG correctly.
13583   BB->addSuccessor(bumpMBB);
13584   BB->addSuccessor(mallocMBB);
13585   mallocMBB->addSuccessor(continueMBB);
13586   bumpMBB->addSuccessor(continueMBB);
13587
13588   // Take care of the PHI nodes.
13589   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13590           MI->getOperand(0).getReg())
13591     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13592     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13593
13594   // Delete the original pseudo instruction.
13595   MI->eraseFromParent();
13596
13597   // And we're done.
13598   return continueMBB;
13599 }
13600
13601 MachineBasicBlock *
13602 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13603                                           MachineBasicBlock *BB) const {
13604   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13605   DebugLoc DL = MI->getDebugLoc();
13606
13607   assert(!Subtarget->isTargetEnvMacho());
13608
13609   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13610   // non-trivial part is impdef of ESP.
13611
13612   if (Subtarget->isTargetWin64()) {
13613     if (Subtarget->isTargetCygMing()) {
13614       // ___chkstk(Mingw64):
13615       // Clobbers R10, R11, RAX and EFLAGS.
13616       // Updates RSP.
13617       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13618         .addExternalSymbol("___chkstk")
13619         .addReg(X86::RAX, RegState::Implicit)
13620         .addReg(X86::RSP, RegState::Implicit)
13621         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13622         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13623         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13624     } else {
13625       // __chkstk(MSVCRT): does not update stack pointer.
13626       // Clobbers R10, R11 and EFLAGS.
13627       // FIXME: RAX(allocated size) might be reused and not killed.
13628       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13629         .addExternalSymbol("__chkstk")
13630         .addReg(X86::RAX, RegState::Implicit)
13631         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13632       // RAX has the offset to subtracted from RSP.
13633       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13634         .addReg(X86::RSP)
13635         .addReg(X86::RAX);
13636     }
13637   } else {
13638     const char *StackProbeSymbol =
13639       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13640
13641     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13642       .addExternalSymbol(StackProbeSymbol)
13643       .addReg(X86::EAX, RegState::Implicit)
13644       .addReg(X86::ESP, RegState::Implicit)
13645       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13646       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13647       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13648   }
13649
13650   MI->eraseFromParent();   // The pseudo instruction is gone now.
13651   return BB;
13652 }
13653
13654 MachineBasicBlock *
13655 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13656                                       MachineBasicBlock *BB) const {
13657   // This is pretty easy.  We're taking the value that we received from
13658   // our load from the relocation, sticking it in either RDI (x86-64)
13659   // or EAX and doing an indirect call.  The return value will then
13660   // be in the normal return register.
13661   const X86InstrInfo *TII
13662     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13663   DebugLoc DL = MI->getDebugLoc();
13664   MachineFunction *F = BB->getParent();
13665
13666   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13667   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13668
13669   // Get a register mask for the lowered call.
13670   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13671   // proper register mask.
13672   const uint32_t *RegMask =
13673     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13674   if (Subtarget->is64Bit()) {
13675     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13676                                       TII->get(X86::MOV64rm), X86::RDI)
13677     .addReg(X86::RIP)
13678     .addImm(0).addReg(0)
13679     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13680                       MI->getOperand(3).getTargetFlags())
13681     .addReg(0);
13682     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13683     addDirectMem(MIB, X86::RDI);
13684     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13685   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13686     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13687                                       TII->get(X86::MOV32rm), X86::EAX)
13688     .addReg(0)
13689     .addImm(0).addReg(0)
13690     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13691                       MI->getOperand(3).getTargetFlags())
13692     .addReg(0);
13693     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13694     addDirectMem(MIB, X86::EAX);
13695     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13696   } else {
13697     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13698                                       TII->get(X86::MOV32rm), X86::EAX)
13699     .addReg(TII->getGlobalBaseReg(F))
13700     .addImm(0).addReg(0)
13701     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13702                       MI->getOperand(3).getTargetFlags())
13703     .addReg(0);
13704     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13705     addDirectMem(MIB, X86::EAX);
13706     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13707   }
13708
13709   MI->eraseFromParent(); // The pseudo instruction is gone now.
13710   return BB;
13711 }
13712
13713 MachineBasicBlock *
13714 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13715                                     MachineBasicBlock *MBB) const {
13716   DebugLoc DL = MI->getDebugLoc();
13717   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13718
13719   MachineFunction *MF = MBB->getParent();
13720   MachineRegisterInfo &MRI = MF->getRegInfo();
13721
13722   const BasicBlock *BB = MBB->getBasicBlock();
13723   MachineFunction::iterator I = MBB;
13724   ++I;
13725
13726   // Memory Reference
13727   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13728   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13729
13730   unsigned DstReg;
13731   unsigned MemOpndSlot = 0;
13732
13733   unsigned CurOp = 0;
13734
13735   DstReg = MI->getOperand(CurOp++).getReg();
13736   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13737   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13738   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13739   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13740
13741   MemOpndSlot = CurOp;
13742
13743   MVT PVT = getPointerTy();
13744   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13745          "Invalid Pointer Size!");
13746
13747   // For v = setjmp(buf), we generate
13748   //
13749   // thisMBB:
13750   //  buf[LabelOffset] = restoreMBB
13751   //  SjLjSetup restoreMBB
13752   //
13753   // mainMBB:
13754   //  v_main = 0
13755   //
13756   // sinkMBB:
13757   //  v = phi(main, restore)
13758   //
13759   // restoreMBB:
13760   //  v_restore = 1
13761
13762   MachineBasicBlock *thisMBB = MBB;
13763   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13764   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13765   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13766   MF->insert(I, mainMBB);
13767   MF->insert(I, sinkMBB);
13768   MF->push_back(restoreMBB);
13769
13770   MachineInstrBuilder MIB;
13771
13772   // Transfer the remainder of BB and its successor edges to sinkMBB.
13773   sinkMBB->splice(sinkMBB->begin(), MBB,
13774                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13775   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13776
13777   // thisMBB:
13778   unsigned PtrStoreOpc = 0;
13779   unsigned LabelReg = 0;
13780   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13781   Reloc::Model RM = getTargetMachine().getRelocationModel();
13782   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13783                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13784
13785   // Prepare IP either in reg or imm.
13786   if (!UseImmLabel) {
13787     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13788     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13789     LabelReg = MRI.createVirtualRegister(PtrRC);
13790     if (Subtarget->is64Bit()) {
13791       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13792               .addReg(X86::RIP)
13793               .addImm(0)
13794               .addReg(0)
13795               .addMBB(restoreMBB)
13796               .addReg(0);
13797     } else {
13798       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13799       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13800               .addReg(XII->getGlobalBaseReg(MF))
13801               .addImm(0)
13802               .addReg(0)
13803               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13804               .addReg(0);
13805     }
13806   } else
13807     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13808   // Store IP
13809   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13810   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13811     if (i == X86::AddrDisp)
13812       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13813     else
13814       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13815   }
13816   if (!UseImmLabel)
13817     MIB.addReg(LabelReg);
13818   else
13819     MIB.addMBB(restoreMBB);
13820   MIB.setMemRefs(MMOBegin, MMOEnd);
13821   // Setup
13822   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13823           .addMBB(restoreMBB);
13824   MIB.addRegMask(RegInfo->getNoPreservedMask());
13825   thisMBB->addSuccessor(mainMBB);
13826   thisMBB->addSuccessor(restoreMBB);
13827
13828   // mainMBB:
13829   //  EAX = 0
13830   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13831   mainMBB->addSuccessor(sinkMBB);
13832
13833   // sinkMBB:
13834   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13835           TII->get(X86::PHI), DstReg)
13836     .addReg(mainDstReg).addMBB(mainMBB)
13837     .addReg(restoreDstReg).addMBB(restoreMBB);
13838
13839   // restoreMBB:
13840   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13841   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13842   restoreMBB->addSuccessor(sinkMBB);
13843
13844   MI->eraseFromParent();
13845   return sinkMBB;
13846 }
13847
13848 MachineBasicBlock *
13849 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13850                                      MachineBasicBlock *MBB) const {
13851   DebugLoc DL = MI->getDebugLoc();
13852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13853
13854   MachineFunction *MF = MBB->getParent();
13855   MachineRegisterInfo &MRI = MF->getRegInfo();
13856
13857   // Memory Reference
13858   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13859   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13860
13861   MVT PVT = getPointerTy();
13862   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13863          "Invalid Pointer Size!");
13864
13865   const TargetRegisterClass *RC =
13866     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13867   unsigned Tmp = MRI.createVirtualRegister(RC);
13868   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13869   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13870   unsigned SP = RegInfo->getStackRegister();
13871
13872   MachineInstrBuilder MIB;
13873
13874   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13875   const int64_t SPOffset = 2 * PVT.getStoreSize();
13876
13877   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13878   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13879
13880   // Reload FP
13881   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13882   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13883     MIB.addOperand(MI->getOperand(i));
13884   MIB.setMemRefs(MMOBegin, MMOEnd);
13885   // Reload IP
13886   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13887   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13888     if (i == X86::AddrDisp)
13889       MIB.addDisp(MI->getOperand(i), LabelOffset);
13890     else
13891       MIB.addOperand(MI->getOperand(i));
13892   }
13893   MIB.setMemRefs(MMOBegin, MMOEnd);
13894   // Reload SP
13895   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13896   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13897     if (i == X86::AddrDisp)
13898       MIB.addDisp(MI->getOperand(i), SPOffset);
13899     else
13900       MIB.addOperand(MI->getOperand(i));
13901   }
13902   MIB.setMemRefs(MMOBegin, MMOEnd);
13903   // Jump
13904   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13905
13906   MI->eraseFromParent();
13907   return MBB;
13908 }
13909
13910 MachineBasicBlock *
13911 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13912                                                MachineBasicBlock *BB) const {
13913   switch (MI->getOpcode()) {
13914   default: llvm_unreachable("Unexpected instr type to insert");
13915   case X86::TAILJMPd64:
13916   case X86::TAILJMPr64:
13917   case X86::TAILJMPm64:
13918     llvm_unreachable("TAILJMP64 would not be touched here.");
13919   case X86::TCRETURNdi64:
13920   case X86::TCRETURNri64:
13921   case X86::TCRETURNmi64:
13922     return BB;
13923   case X86::WIN_ALLOCA:
13924     return EmitLoweredWinAlloca(MI, BB);
13925   case X86::SEG_ALLOCA_32:
13926     return EmitLoweredSegAlloca(MI, BB, false);
13927   case X86::SEG_ALLOCA_64:
13928     return EmitLoweredSegAlloca(MI, BB, true);
13929   case X86::TLSCall_32:
13930   case X86::TLSCall_64:
13931     return EmitLoweredTLSCall(MI, BB);
13932   case X86::CMOV_GR8:
13933   case X86::CMOV_FR32:
13934   case X86::CMOV_FR64:
13935   case X86::CMOV_V4F32:
13936   case X86::CMOV_V2F64:
13937   case X86::CMOV_V2I64:
13938   case X86::CMOV_V8F32:
13939   case X86::CMOV_V4F64:
13940   case X86::CMOV_V4I64:
13941   case X86::CMOV_GR16:
13942   case X86::CMOV_GR32:
13943   case X86::CMOV_RFP32:
13944   case X86::CMOV_RFP64:
13945   case X86::CMOV_RFP80:
13946     return EmitLoweredSelect(MI, BB);
13947
13948   case X86::FP32_TO_INT16_IN_MEM:
13949   case X86::FP32_TO_INT32_IN_MEM:
13950   case X86::FP32_TO_INT64_IN_MEM:
13951   case X86::FP64_TO_INT16_IN_MEM:
13952   case X86::FP64_TO_INT32_IN_MEM:
13953   case X86::FP64_TO_INT64_IN_MEM:
13954   case X86::FP80_TO_INT16_IN_MEM:
13955   case X86::FP80_TO_INT32_IN_MEM:
13956   case X86::FP80_TO_INT64_IN_MEM: {
13957     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13958     DebugLoc DL = MI->getDebugLoc();
13959
13960     // Change the floating point control register to use "round towards zero"
13961     // mode when truncating to an integer value.
13962     MachineFunction *F = BB->getParent();
13963     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13964     addFrameReference(BuildMI(*BB, MI, DL,
13965                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13966
13967     // Load the old value of the high byte of the control word...
13968     unsigned OldCW =
13969       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13970     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13971                       CWFrameIdx);
13972
13973     // Set the high part to be round to zero...
13974     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13975       .addImm(0xC7F);
13976
13977     // Reload the modified control word now...
13978     addFrameReference(BuildMI(*BB, MI, DL,
13979                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13980
13981     // Restore the memory image of control word to original value
13982     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13983       .addReg(OldCW);
13984
13985     // Get the X86 opcode to use.
13986     unsigned Opc;
13987     switch (MI->getOpcode()) {
13988     default: llvm_unreachable("illegal opcode!");
13989     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13990     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13991     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13992     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13993     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13994     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13995     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13996     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13997     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13998     }
13999
14000     X86AddressMode AM;
14001     MachineOperand &Op = MI->getOperand(0);
14002     if (Op.isReg()) {
14003       AM.BaseType = X86AddressMode::RegBase;
14004       AM.Base.Reg = Op.getReg();
14005     } else {
14006       AM.BaseType = X86AddressMode::FrameIndexBase;
14007       AM.Base.FrameIndex = Op.getIndex();
14008     }
14009     Op = MI->getOperand(1);
14010     if (Op.isImm())
14011       AM.Scale = Op.getImm();
14012     Op = MI->getOperand(2);
14013     if (Op.isImm())
14014       AM.IndexReg = Op.getImm();
14015     Op = MI->getOperand(3);
14016     if (Op.isGlobal()) {
14017       AM.GV = Op.getGlobal();
14018     } else {
14019       AM.Disp = Op.getImm();
14020     }
14021     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14022                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14023
14024     // Reload the original control word now.
14025     addFrameReference(BuildMI(*BB, MI, DL,
14026                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14027
14028     MI->eraseFromParent();   // The pseudo instruction is gone now.
14029     return BB;
14030   }
14031     // String/text processing lowering.
14032   case X86::PCMPISTRM128REG:
14033   case X86::VPCMPISTRM128REG:
14034   case X86::PCMPISTRM128MEM:
14035   case X86::VPCMPISTRM128MEM:
14036   case X86::PCMPESTRM128REG:
14037   case X86::VPCMPESTRM128REG:
14038   case X86::PCMPESTRM128MEM:
14039   case X86::VPCMPESTRM128MEM:
14040     assert(Subtarget->hasSSE42() &&
14041            "Target must have SSE4.2 or AVX features enabled");
14042     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14043
14044   // String/text processing lowering.
14045   case X86::PCMPISTRIREG:
14046   case X86::VPCMPISTRIREG:
14047   case X86::PCMPISTRIMEM:
14048   case X86::VPCMPISTRIMEM:
14049   case X86::PCMPESTRIREG:
14050   case X86::VPCMPESTRIREG:
14051   case X86::PCMPESTRIMEM:
14052   case X86::VPCMPESTRIMEM:
14053     assert(Subtarget->hasSSE42() &&
14054            "Target must have SSE4.2 or AVX features enabled");
14055     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14056
14057   // Thread synchronization.
14058   case X86::MONITOR:
14059     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14060
14061   // xbegin
14062   case X86::XBEGIN:
14063     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14064
14065   // Atomic Lowering.
14066   case X86::ATOMAND8:
14067   case X86::ATOMAND16:
14068   case X86::ATOMAND32:
14069   case X86::ATOMAND64:
14070     // Fall through
14071   case X86::ATOMOR8:
14072   case X86::ATOMOR16:
14073   case X86::ATOMOR32:
14074   case X86::ATOMOR64:
14075     // Fall through
14076   case X86::ATOMXOR16:
14077   case X86::ATOMXOR8:
14078   case X86::ATOMXOR32:
14079   case X86::ATOMXOR64:
14080     // Fall through
14081   case X86::ATOMNAND8:
14082   case X86::ATOMNAND16:
14083   case X86::ATOMNAND32:
14084   case X86::ATOMNAND64:
14085     // Fall through
14086   case X86::ATOMMAX8:
14087   case X86::ATOMMAX16:
14088   case X86::ATOMMAX32:
14089   case X86::ATOMMAX64:
14090     // Fall through
14091   case X86::ATOMMIN8:
14092   case X86::ATOMMIN16:
14093   case X86::ATOMMIN32:
14094   case X86::ATOMMIN64:
14095     // Fall through
14096   case X86::ATOMUMAX8:
14097   case X86::ATOMUMAX16:
14098   case X86::ATOMUMAX32:
14099   case X86::ATOMUMAX64:
14100     // Fall through
14101   case X86::ATOMUMIN8:
14102   case X86::ATOMUMIN16:
14103   case X86::ATOMUMIN32:
14104   case X86::ATOMUMIN64:
14105     return EmitAtomicLoadArith(MI, BB);
14106
14107   // This group does 64-bit operations on a 32-bit host.
14108   case X86::ATOMAND6432:
14109   case X86::ATOMOR6432:
14110   case X86::ATOMXOR6432:
14111   case X86::ATOMNAND6432:
14112   case X86::ATOMADD6432:
14113   case X86::ATOMSUB6432:
14114   case X86::ATOMMAX6432:
14115   case X86::ATOMMIN6432:
14116   case X86::ATOMUMAX6432:
14117   case X86::ATOMUMIN6432:
14118   case X86::ATOMSWAP6432:
14119     return EmitAtomicLoadArith6432(MI, BB);
14120
14121   case X86::VASTART_SAVE_XMM_REGS:
14122     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14123
14124   case X86::VAARG_64:
14125     return EmitVAARG64WithCustomInserter(MI, BB);
14126
14127   case X86::EH_SjLj_SetJmp32:
14128   case X86::EH_SjLj_SetJmp64:
14129     return emitEHSjLjSetJmp(MI, BB);
14130
14131   case X86::EH_SjLj_LongJmp32:
14132   case X86::EH_SjLj_LongJmp64:
14133     return emitEHSjLjLongJmp(MI, BB);
14134   }
14135 }
14136
14137 //===----------------------------------------------------------------------===//
14138 //                           X86 Optimization Hooks
14139 //===----------------------------------------------------------------------===//
14140
14141 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14142                                                        APInt &KnownZero,
14143                                                        APInt &KnownOne,
14144                                                        const SelectionDAG &DAG,
14145                                                        unsigned Depth) const {
14146   unsigned BitWidth = KnownZero.getBitWidth();
14147   unsigned Opc = Op.getOpcode();
14148   assert((Opc >= ISD::BUILTIN_OP_END ||
14149           Opc == ISD::INTRINSIC_WO_CHAIN ||
14150           Opc == ISD::INTRINSIC_W_CHAIN ||
14151           Opc == ISD::INTRINSIC_VOID) &&
14152          "Should use MaskedValueIsZero if you don't know whether Op"
14153          " is a target node!");
14154
14155   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14156   switch (Opc) {
14157   default: break;
14158   case X86ISD::ADD:
14159   case X86ISD::SUB:
14160   case X86ISD::ADC:
14161   case X86ISD::SBB:
14162   case X86ISD::SMUL:
14163   case X86ISD::UMUL:
14164   case X86ISD::INC:
14165   case X86ISD::DEC:
14166   case X86ISD::OR:
14167   case X86ISD::XOR:
14168   case X86ISD::AND:
14169     // These nodes' second result is a boolean.
14170     if (Op.getResNo() == 0)
14171       break;
14172     // Fallthrough
14173   case X86ISD::SETCC:
14174     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14175     break;
14176   case ISD::INTRINSIC_WO_CHAIN: {
14177     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14178     unsigned NumLoBits = 0;
14179     switch (IntId) {
14180     default: break;
14181     case Intrinsic::x86_sse_movmsk_ps:
14182     case Intrinsic::x86_avx_movmsk_ps_256:
14183     case Intrinsic::x86_sse2_movmsk_pd:
14184     case Intrinsic::x86_avx_movmsk_pd_256:
14185     case Intrinsic::x86_mmx_pmovmskb:
14186     case Intrinsic::x86_sse2_pmovmskb_128:
14187     case Intrinsic::x86_avx2_pmovmskb: {
14188       // High bits of movmskp{s|d}, pmovmskb are known zero.
14189       switch (IntId) {
14190         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14191         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14192         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14193         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14194         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14195         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14196         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14197         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14198       }
14199       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14200       break;
14201     }
14202     }
14203     break;
14204   }
14205   }
14206 }
14207
14208 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14209                                                          unsigned Depth) const {
14210   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14211   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14212     return Op.getValueType().getScalarType().getSizeInBits();
14213
14214   // Fallback case.
14215   return 1;
14216 }
14217
14218 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14219 /// node is a GlobalAddress + offset.
14220 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14221                                        const GlobalValue* &GA,
14222                                        int64_t &Offset) const {
14223   if (N->getOpcode() == X86ISD::Wrapper) {
14224     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14225       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14226       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14227       return true;
14228     }
14229   }
14230   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14231 }
14232
14233 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14234 /// same as extracting the high 128-bit part of 256-bit vector and then
14235 /// inserting the result into the low part of a new 256-bit vector
14236 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14237   EVT VT = SVOp->getValueType(0);
14238   unsigned NumElems = VT.getVectorNumElements();
14239
14240   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14241   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14242     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14243         SVOp->getMaskElt(j) >= 0)
14244       return false;
14245
14246   return true;
14247 }
14248
14249 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14250 /// same as extracting the low 128-bit part of 256-bit vector and then
14251 /// inserting the result into the high part of a new 256-bit vector
14252 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14253   EVT VT = SVOp->getValueType(0);
14254   unsigned NumElems = VT.getVectorNumElements();
14255
14256   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14257   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14258     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14259         SVOp->getMaskElt(j) >= 0)
14260       return false;
14261
14262   return true;
14263 }
14264
14265 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14266 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14267                                         TargetLowering::DAGCombinerInfo &DCI,
14268                                         const X86Subtarget* Subtarget) {
14269   DebugLoc dl = N->getDebugLoc();
14270   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14271   SDValue V1 = SVOp->getOperand(0);
14272   SDValue V2 = SVOp->getOperand(1);
14273   EVT VT = SVOp->getValueType(0);
14274   unsigned NumElems = VT.getVectorNumElements();
14275
14276   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14277       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14278     //
14279     //                   0,0,0,...
14280     //                      |
14281     //    V      UNDEF    BUILD_VECTOR    UNDEF
14282     //     \      /           \           /
14283     //  CONCAT_VECTOR         CONCAT_VECTOR
14284     //         \                  /
14285     //          \                /
14286     //          RESULT: V + zero extended
14287     //
14288     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14289         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14290         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14291       return SDValue();
14292
14293     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14294       return SDValue();
14295
14296     // To match the shuffle mask, the first half of the mask should
14297     // be exactly the first vector, and all the rest a splat with the
14298     // first element of the second one.
14299     for (unsigned i = 0; i != NumElems/2; ++i)
14300       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14301           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14302         return SDValue();
14303
14304     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14305     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14306       if (Ld->hasNUsesOfValue(1, 0)) {
14307         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14308         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14309         SDValue ResNode =
14310           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14311                                   Ld->getMemoryVT(),
14312                                   Ld->getPointerInfo(),
14313                                   Ld->getAlignment(),
14314                                   false/*isVolatile*/, true/*ReadMem*/,
14315                                   false/*WriteMem*/);
14316
14317         // Make sure the newly-created LOAD is in the same position as Ld in
14318         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14319         // and update uses of Ld's output chain to use the TokenFactor.
14320         if (Ld->hasAnyUseOfValue(1)) {
14321           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14322                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14323           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14324           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14325                                  SDValue(ResNode.getNode(), 1));
14326         }
14327
14328         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14329       }
14330     }
14331
14332     // Emit a zeroed vector and insert the desired subvector on its
14333     // first half.
14334     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14335     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14336     return DCI.CombineTo(N, InsV);
14337   }
14338
14339   //===--------------------------------------------------------------------===//
14340   // Combine some shuffles into subvector extracts and inserts:
14341   //
14342
14343   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14344   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14345     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14346     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14347     return DCI.CombineTo(N, InsV);
14348   }
14349
14350   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14351   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14352     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14353     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14354     return DCI.CombineTo(N, InsV);
14355   }
14356
14357   return SDValue();
14358 }
14359
14360 /// PerformShuffleCombine - Performs several different shuffle combines.
14361 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14362                                      TargetLowering::DAGCombinerInfo &DCI,
14363                                      const X86Subtarget *Subtarget) {
14364   DebugLoc dl = N->getDebugLoc();
14365   EVT VT = N->getValueType(0);
14366
14367   // Don't create instructions with illegal types after legalize types has run.
14368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14369   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14370     return SDValue();
14371
14372   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14373   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14374       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14375     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14376
14377   // Only handle 128 wide vector from here on.
14378   if (!VT.is128BitVector())
14379     return SDValue();
14380
14381   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14382   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14383   // consecutive, non-overlapping, and in the right order.
14384   SmallVector<SDValue, 16> Elts;
14385   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14386     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14387
14388   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14389 }
14390
14391
14392 /// PerformTruncateCombine - Converts truncate operation to
14393 /// a sequence of vector shuffle operations.
14394 /// It is possible when we truncate 256-bit vector to 128-bit vector
14395 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14396                                       TargetLowering::DAGCombinerInfo &DCI,
14397                                       const X86Subtarget *Subtarget)  {
14398   if (!DCI.isBeforeLegalizeOps())
14399     return SDValue();
14400
14401   if (!Subtarget->hasFp256())
14402     return SDValue();
14403
14404   EVT VT = N->getValueType(0);
14405   SDValue Op = N->getOperand(0);
14406   EVT OpVT = Op.getValueType();
14407   DebugLoc dl = N->getDebugLoc();
14408
14409   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14410
14411     if (Subtarget->hasInt256()) {
14412       // AVX2: v4i64 -> v4i32
14413
14414       // VPERMD
14415       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14416
14417       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14418       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14419                                 ShufMask);
14420
14421       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14422                          DAG.getIntPtrConstant(0));
14423     }
14424
14425     // AVX: v4i64 -> v4i32
14426     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14427                                DAG.getIntPtrConstant(0));
14428
14429     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14430                                DAG.getIntPtrConstant(2));
14431
14432     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14433     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14434
14435     // PSHUFD
14436     static const int ShufMask1[] = {0, 2, 0, 0};
14437
14438     SDValue Undef = DAG.getUNDEF(VT);
14439     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14440     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14441
14442     // MOVLHPS
14443     static const int ShufMask2[] = {0, 1, 4, 5};
14444
14445     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14446   }
14447
14448   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14449
14450     if (Subtarget->hasInt256()) {
14451       // AVX2: v8i32 -> v8i16
14452
14453       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14454
14455       // PSHUFB
14456       SmallVector<SDValue,32> pshufbMask;
14457       for (unsigned i = 0; i < 2; ++i) {
14458         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14459         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14460         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14461         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14462         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14463         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14464         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14465         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14466         for (unsigned j = 0; j < 8; ++j)
14467           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14468       }
14469       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14470                                &pshufbMask[0], 32);
14471       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14472
14473       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14474
14475       static const int ShufMask[] = {0,  2,  -1,  -1};
14476       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14477                                 &ShufMask[0]);
14478
14479       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14480                        DAG.getIntPtrConstant(0));
14481
14482       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14483     }
14484
14485     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14486                                DAG.getIntPtrConstant(0));
14487
14488     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14489                                DAG.getIntPtrConstant(4));
14490
14491     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14492     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14493
14494     // PSHUFB
14495     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14496                                    -1, -1, -1, -1, -1, -1, -1, -1};
14497
14498     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14499     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14500     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14501
14502     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14503     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14504
14505     // MOVLHPS
14506     static const int ShufMask2[] = {0, 1, 4, 5};
14507
14508     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14509     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14510   }
14511
14512   return SDValue();
14513 }
14514
14515 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14516 /// specific shuffle of a load can be folded into a single element load.
14517 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14518 /// shuffles have been customed lowered so we need to handle those here.
14519 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14520                                          TargetLowering::DAGCombinerInfo &DCI) {
14521   if (DCI.isBeforeLegalizeOps())
14522     return SDValue();
14523
14524   SDValue InVec = N->getOperand(0);
14525   SDValue EltNo = N->getOperand(1);
14526
14527   if (!isa<ConstantSDNode>(EltNo))
14528     return SDValue();
14529
14530   EVT VT = InVec.getValueType();
14531
14532   bool HasShuffleIntoBitcast = false;
14533   if (InVec.getOpcode() == ISD::BITCAST) {
14534     // Don't duplicate a load with other uses.
14535     if (!InVec.hasOneUse())
14536       return SDValue();
14537     EVT BCVT = InVec.getOperand(0).getValueType();
14538     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14539       return SDValue();
14540     InVec = InVec.getOperand(0);
14541     HasShuffleIntoBitcast = true;
14542   }
14543
14544   if (!isTargetShuffle(InVec.getOpcode()))
14545     return SDValue();
14546
14547   // Don't duplicate a load with other uses.
14548   if (!InVec.hasOneUse())
14549     return SDValue();
14550
14551   SmallVector<int, 16> ShuffleMask;
14552   bool UnaryShuffle;
14553   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14554                             UnaryShuffle))
14555     return SDValue();
14556
14557   // Select the input vector, guarding against out of range extract vector.
14558   unsigned NumElems = VT.getVectorNumElements();
14559   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14560   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14561   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14562                                          : InVec.getOperand(1);
14563
14564   // If inputs to shuffle are the same for both ops, then allow 2 uses
14565   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14566
14567   if (LdNode.getOpcode() == ISD::BITCAST) {
14568     // Don't duplicate a load with other uses.
14569     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14570       return SDValue();
14571
14572     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14573     LdNode = LdNode.getOperand(0);
14574   }
14575
14576   if (!ISD::isNormalLoad(LdNode.getNode()))
14577     return SDValue();
14578
14579   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14580
14581   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14582     return SDValue();
14583
14584   if (HasShuffleIntoBitcast) {
14585     // If there's a bitcast before the shuffle, check if the load type and
14586     // alignment is valid.
14587     unsigned Align = LN0->getAlignment();
14588     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14589     unsigned NewAlign = TLI.getDataLayout()->
14590       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14591
14592     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14593       return SDValue();
14594   }
14595
14596   // All checks match so transform back to vector_shuffle so that DAG combiner
14597   // can finish the job
14598   DebugLoc dl = N->getDebugLoc();
14599
14600   // Create shuffle node taking into account the case that its a unary shuffle
14601   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14602   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14603                                  InVec.getOperand(0), Shuffle,
14604                                  &ShuffleMask[0]);
14605   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14606   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14607                      EltNo);
14608 }
14609
14610 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14611 /// generation and convert it from being a bunch of shuffles and extracts
14612 /// to a simple store and scalar loads to extract the elements.
14613 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14614                                          TargetLowering::DAGCombinerInfo &DCI) {
14615   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14616   if (NewOp.getNode())
14617     return NewOp;
14618
14619   SDValue InputVector = N->getOperand(0);
14620   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14621   // from mmx to v2i32 has a single usage.
14622   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14623       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14624       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14625     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14626                        N->getValueType(0),
14627                        InputVector.getNode()->getOperand(0));
14628
14629   // Only operate on vectors of 4 elements, where the alternative shuffling
14630   // gets to be more expensive.
14631   if (InputVector.getValueType() != MVT::v4i32)
14632     return SDValue();
14633
14634   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14635   // single use which is a sign-extend or zero-extend, and all elements are
14636   // used.
14637   SmallVector<SDNode *, 4> Uses;
14638   unsigned ExtractedElements = 0;
14639   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14640        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14641     if (UI.getUse().getResNo() != InputVector.getResNo())
14642       return SDValue();
14643
14644     SDNode *Extract = *UI;
14645     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14646       return SDValue();
14647
14648     if (Extract->getValueType(0) != MVT::i32)
14649       return SDValue();
14650     if (!Extract->hasOneUse())
14651       return SDValue();
14652     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14653         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14654       return SDValue();
14655     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14656       return SDValue();
14657
14658     // Record which element was extracted.
14659     ExtractedElements |=
14660       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14661
14662     Uses.push_back(Extract);
14663   }
14664
14665   // If not all the elements were used, this may not be worthwhile.
14666   if (ExtractedElements != 15)
14667     return SDValue();
14668
14669   // Ok, we've now decided to do the transformation.
14670   DebugLoc dl = InputVector.getDebugLoc();
14671
14672   // Store the value to a temporary stack slot.
14673   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14674   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14675                             MachinePointerInfo(), false, false, 0);
14676
14677   // Replace each use (extract) with a load of the appropriate element.
14678   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14679        UE = Uses.end(); UI != UE; ++UI) {
14680     SDNode *Extract = *UI;
14681
14682     // cOMpute the element's address.
14683     SDValue Idx = Extract->getOperand(1);
14684     unsigned EltSize =
14685         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14686     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14687     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14688     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14689
14690     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14691                                      StackPtr, OffsetVal);
14692
14693     // Load the scalar.
14694     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14695                                      ScalarAddr, MachinePointerInfo(),
14696                                      false, false, false, 0);
14697
14698     // Replace the exact with the load.
14699     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14700   }
14701
14702   // The replacement was made in place; don't return anything.
14703   return SDValue();
14704 }
14705
14706 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14707 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14708                                    SDValue RHS, SelectionDAG &DAG,
14709                                    const X86Subtarget *Subtarget) {
14710   if (!VT.isVector())
14711     return 0;
14712
14713   switch (VT.getSimpleVT().SimpleTy) {
14714   default: return 0;
14715   case MVT::v32i8:
14716   case MVT::v16i16:
14717   case MVT::v8i32:
14718     if (!Subtarget->hasAVX2())
14719       return 0;
14720   case MVT::v16i8:
14721   case MVT::v8i16:
14722   case MVT::v4i32:
14723     if (!Subtarget->hasSSE2())
14724       return 0;
14725   }
14726
14727   // SSE2 has only a small subset of the operations.
14728   bool hasUnsigned = Subtarget->hasSSE41() ||
14729                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
14730   bool hasSigned = Subtarget->hasSSE41() ||
14731                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
14732
14733   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14734
14735   // Check for x CC y ? x : y.
14736   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14737       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14738     switch (CC) {
14739     default: break;
14740     case ISD::SETULT:
14741     case ISD::SETULE:
14742       return hasUnsigned ? X86ISD::UMIN : 0;
14743     case ISD::SETUGT:
14744     case ISD::SETUGE:
14745       return hasUnsigned ? X86ISD::UMAX : 0;
14746     case ISD::SETLT:
14747     case ISD::SETLE:
14748       return hasSigned ? X86ISD::SMIN : 0;
14749     case ISD::SETGT:
14750     case ISD::SETGE:
14751       return hasSigned ? X86ISD::SMAX : 0;
14752     }
14753   // Check for x CC y ? y : x -- a min/max with reversed arms.
14754   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14755              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14756     switch (CC) {
14757     default: break;
14758     case ISD::SETULT:
14759     case ISD::SETULE:
14760       return hasUnsigned ? X86ISD::UMAX : 0;
14761     case ISD::SETUGT:
14762     case ISD::SETUGE:
14763       return hasUnsigned ? X86ISD::UMIN : 0;
14764     case ISD::SETLT:
14765     case ISD::SETLE:
14766       return hasSigned ? X86ISD::SMAX : 0;
14767     case ISD::SETGT:
14768     case ISD::SETGE:
14769       return hasSigned ? X86ISD::SMIN : 0;
14770     }
14771   }
14772
14773   return 0;
14774 }
14775
14776 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14777 /// nodes.
14778 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14779                                     TargetLowering::DAGCombinerInfo &DCI,
14780                                     const X86Subtarget *Subtarget) {
14781   DebugLoc DL = N->getDebugLoc();
14782   SDValue Cond = N->getOperand(0);
14783   // Get the LHS/RHS of the select.
14784   SDValue LHS = N->getOperand(1);
14785   SDValue RHS = N->getOperand(2);
14786   EVT VT = LHS.getValueType();
14787
14788   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14789   // instructions match the semantics of the common C idiom x<y?x:y but not
14790   // x<=y?x:y, because of how they handle negative zero (which can be
14791   // ignored in unsafe-math mode).
14792   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14793       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14794       (Subtarget->hasSSE2() ||
14795        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14796     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14797
14798     unsigned Opcode = 0;
14799     // Check for x CC y ? x : y.
14800     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14801         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14802       switch (CC) {
14803       default: break;
14804       case ISD::SETULT:
14805         // Converting this to a min would handle NaNs incorrectly, and swapping
14806         // the operands would cause it to handle comparisons between positive
14807         // and negative zero incorrectly.
14808         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14809           if (!DAG.getTarget().Options.UnsafeFPMath &&
14810               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14811             break;
14812           std::swap(LHS, RHS);
14813         }
14814         Opcode = X86ISD::FMIN;
14815         break;
14816       case ISD::SETOLE:
14817         // Converting this to a min would handle comparisons between positive
14818         // and negative zero incorrectly.
14819         if (!DAG.getTarget().Options.UnsafeFPMath &&
14820             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14821           break;
14822         Opcode = X86ISD::FMIN;
14823         break;
14824       case ISD::SETULE:
14825         // Converting this to a min would handle both negative zeros and NaNs
14826         // incorrectly, but we can swap the operands to fix both.
14827         std::swap(LHS, RHS);
14828       case ISD::SETOLT:
14829       case ISD::SETLT:
14830       case ISD::SETLE:
14831         Opcode = X86ISD::FMIN;
14832         break;
14833
14834       case ISD::SETOGE:
14835         // Converting this to a max would handle comparisons between positive
14836         // and negative zero incorrectly.
14837         if (!DAG.getTarget().Options.UnsafeFPMath &&
14838             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14839           break;
14840         Opcode = X86ISD::FMAX;
14841         break;
14842       case ISD::SETUGT:
14843         // Converting this to a max would handle NaNs incorrectly, and swapping
14844         // the operands would cause it to handle comparisons between positive
14845         // and negative zero incorrectly.
14846         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14847           if (!DAG.getTarget().Options.UnsafeFPMath &&
14848               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14849             break;
14850           std::swap(LHS, RHS);
14851         }
14852         Opcode = X86ISD::FMAX;
14853         break;
14854       case ISD::SETUGE:
14855         // Converting this to a max would handle both negative zeros and NaNs
14856         // incorrectly, but we can swap the operands to fix both.
14857         std::swap(LHS, RHS);
14858       case ISD::SETOGT:
14859       case ISD::SETGT:
14860       case ISD::SETGE:
14861         Opcode = X86ISD::FMAX;
14862         break;
14863       }
14864     // Check for x CC y ? y : x -- a min/max with reversed arms.
14865     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14866                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14867       switch (CC) {
14868       default: break;
14869       case ISD::SETOGE:
14870         // Converting this to a min would handle comparisons between positive
14871         // and negative zero incorrectly, and swapping the operands would
14872         // cause it to handle NaNs incorrectly.
14873         if (!DAG.getTarget().Options.UnsafeFPMath &&
14874             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14875           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14876             break;
14877           std::swap(LHS, RHS);
14878         }
14879         Opcode = X86ISD::FMIN;
14880         break;
14881       case ISD::SETUGT:
14882         // Converting this to a min would handle NaNs incorrectly.
14883         if (!DAG.getTarget().Options.UnsafeFPMath &&
14884             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14885           break;
14886         Opcode = X86ISD::FMIN;
14887         break;
14888       case ISD::SETUGE:
14889         // Converting this to a min would handle both negative zeros and NaNs
14890         // incorrectly, but we can swap the operands to fix both.
14891         std::swap(LHS, RHS);
14892       case ISD::SETOGT:
14893       case ISD::SETGT:
14894       case ISD::SETGE:
14895         Opcode = X86ISD::FMIN;
14896         break;
14897
14898       case ISD::SETULT:
14899         // Converting this to a max would handle NaNs incorrectly.
14900         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14901           break;
14902         Opcode = X86ISD::FMAX;
14903         break;
14904       case ISD::SETOLE:
14905         // Converting this to a max would handle comparisons between positive
14906         // and negative zero incorrectly, and swapping the operands would
14907         // cause it to handle NaNs incorrectly.
14908         if (!DAG.getTarget().Options.UnsafeFPMath &&
14909             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14910           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14911             break;
14912           std::swap(LHS, RHS);
14913         }
14914         Opcode = X86ISD::FMAX;
14915         break;
14916       case ISD::SETULE:
14917         // Converting this to a max would handle both negative zeros and NaNs
14918         // incorrectly, but we can swap the operands to fix both.
14919         std::swap(LHS, RHS);
14920       case ISD::SETOLT:
14921       case ISD::SETLT:
14922       case ISD::SETLE:
14923         Opcode = X86ISD::FMAX;
14924         break;
14925       }
14926     }
14927
14928     if (Opcode)
14929       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14930   }
14931
14932   // If this is a select between two integer constants, try to do some
14933   // optimizations.
14934   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14935     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14936       // Don't do this for crazy integer types.
14937       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14938         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14939         // so that TrueC (the true value) is larger than FalseC.
14940         bool NeedsCondInvert = false;
14941
14942         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14943             // Efficiently invertible.
14944             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14945              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14946               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14947           NeedsCondInvert = true;
14948           std::swap(TrueC, FalseC);
14949         }
14950
14951         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14952         if (FalseC->getAPIntValue() == 0 &&
14953             TrueC->getAPIntValue().isPowerOf2()) {
14954           if (NeedsCondInvert) // Invert the condition if needed.
14955             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14956                                DAG.getConstant(1, Cond.getValueType()));
14957
14958           // Zero extend the condition if needed.
14959           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14960
14961           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14962           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14963                              DAG.getConstant(ShAmt, MVT::i8));
14964         }
14965
14966         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14967         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14968           if (NeedsCondInvert) // Invert the condition if needed.
14969             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14970                                DAG.getConstant(1, Cond.getValueType()));
14971
14972           // Zero extend the condition if needed.
14973           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14974                              FalseC->getValueType(0), Cond);
14975           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14976                              SDValue(FalseC, 0));
14977         }
14978
14979         // Optimize cases that will turn into an LEA instruction.  This requires
14980         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14981         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14982           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14983           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14984
14985           bool isFastMultiplier = false;
14986           if (Diff < 10) {
14987             switch ((unsigned char)Diff) {
14988               default: break;
14989               case 1:  // result = add base, cond
14990               case 2:  // result = lea base(    , cond*2)
14991               case 3:  // result = lea base(cond, cond*2)
14992               case 4:  // result = lea base(    , cond*4)
14993               case 5:  // result = lea base(cond, cond*4)
14994               case 8:  // result = lea base(    , cond*8)
14995               case 9:  // result = lea base(cond, cond*8)
14996                 isFastMultiplier = true;
14997                 break;
14998             }
14999           }
15000
15001           if (isFastMultiplier) {
15002             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15003             if (NeedsCondInvert) // Invert the condition if needed.
15004               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15005                                  DAG.getConstant(1, Cond.getValueType()));
15006
15007             // Zero extend the condition if needed.
15008             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15009                                Cond);
15010             // Scale the condition by the difference.
15011             if (Diff != 1)
15012               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15013                                  DAG.getConstant(Diff, Cond.getValueType()));
15014
15015             // Add the base if non-zero.
15016             if (FalseC->getAPIntValue() != 0)
15017               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15018                                  SDValue(FalseC, 0));
15019             return Cond;
15020           }
15021         }
15022       }
15023   }
15024
15025   // Canonicalize max and min:
15026   // (x > y) ? x : y -> (x >= y) ? x : y
15027   // (x < y) ? x : y -> (x <= y) ? x : y
15028   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15029   // the need for an extra compare
15030   // against zero. e.g.
15031   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15032   // subl   %esi, %edi
15033   // testl  %edi, %edi
15034   // movl   $0, %eax
15035   // cmovgl %edi, %eax
15036   // =>
15037   // xorl   %eax, %eax
15038   // subl   %esi, $edi
15039   // cmovsl %eax, %edi
15040   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15041       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15042       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15043     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15044     switch (CC) {
15045     default: break;
15046     case ISD::SETLT:
15047     case ISD::SETGT: {
15048       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15049       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15050                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15051       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15052     }
15053     }
15054   }
15055
15056   // Match VSELECTs into subs with unsigned saturation.
15057   if (!DCI.isBeforeLegalize() &&
15058       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15059       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15060       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15061        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15062     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15063
15064     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15065     // left side invert the predicate to simplify logic below.
15066     SDValue Other;
15067     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15068       Other = RHS;
15069       CC = ISD::getSetCCInverse(CC, true);
15070     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15071       Other = LHS;
15072     }
15073
15074     if (Other.getNode() && Other->getNumOperands() == 2 &&
15075         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15076       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15077       SDValue CondRHS = Cond->getOperand(1);
15078
15079       // Look for a general sub with unsigned saturation first.
15080       // x >= y ? x-y : 0 --> subus x, y
15081       // x >  y ? x-y : 0 --> subus x, y
15082       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15083           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15084         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15085
15086       // If the RHS is a constant we have to reverse the const canonicalization.
15087       // x > C-1 ? x+-C : 0 --> subus x, C
15088       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15089           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15090         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15091         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15092           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15093                                      DAG.getConstant(-A, VT.getScalarType()));
15094           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15095                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15096                                          V.data(), V.size()));
15097         }
15098       }
15099
15100       // Another special case: If C was a sign bit, the sub has been
15101       // canonicalized into a xor.
15102       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15103       //        it's safe to decanonicalize the xor?
15104       // x s< 0 ? x^C : 0 --> subus x, C
15105       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15106           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15107           isSplatVector(OpRHS.getNode())) {
15108         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15109         if (A.isSignBit())
15110           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15111       }
15112     }
15113   }
15114
15115   // Try to match a min/max vector operation.
15116   if (!DCI.isBeforeLegalize() &&
15117       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15118     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15119       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15120
15121
15122   // If we know that this node is legal then we know that it is going to be
15123   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15124   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15125   // to simplify previous instructions.
15126   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15127   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15128       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15129     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15130
15131     // Don't optimize vector selects that map to mask-registers.
15132     if (BitWidth == 1)
15133       return SDValue();
15134
15135     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15136     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15137
15138     APInt KnownZero, KnownOne;
15139     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15140                                           DCI.isBeforeLegalizeOps());
15141     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15142         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15143       DCI.CommitTargetLoweringOpt(TLO);
15144   }
15145
15146   return SDValue();
15147 }
15148
15149 // Check whether a boolean test is testing a boolean value generated by
15150 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15151 // code.
15152 //
15153 // Simplify the following patterns:
15154 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15155 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15156 // to (Op EFLAGS Cond)
15157 //
15158 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15159 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15160 // to (Op EFLAGS !Cond)
15161 //
15162 // where Op could be BRCOND or CMOV.
15163 //
15164 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15165   // Quit if not CMP and SUB with its value result used.
15166   if (Cmp.getOpcode() != X86ISD::CMP &&
15167       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15168       return SDValue();
15169
15170   // Quit if not used as a boolean value.
15171   if (CC != X86::COND_E && CC != X86::COND_NE)
15172     return SDValue();
15173
15174   // Check CMP operands. One of them should be 0 or 1 and the other should be
15175   // an SetCC or extended from it.
15176   SDValue Op1 = Cmp.getOperand(0);
15177   SDValue Op2 = Cmp.getOperand(1);
15178
15179   SDValue SetCC;
15180   const ConstantSDNode* C = 0;
15181   bool needOppositeCond = (CC == X86::COND_E);
15182
15183   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15184     SetCC = Op2;
15185   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15186     SetCC = Op1;
15187   else // Quit if all operands are not constants.
15188     return SDValue();
15189
15190   if (C->getZExtValue() == 1)
15191     needOppositeCond = !needOppositeCond;
15192   else if (C->getZExtValue() != 0)
15193     // Quit if the constant is neither 0 or 1.
15194     return SDValue();
15195
15196   // Skip 'zext' node.
15197   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15198     SetCC = SetCC.getOperand(0);
15199
15200   switch (SetCC.getOpcode()) {
15201   case X86ISD::SETCC:
15202     // Set the condition code or opposite one if necessary.
15203     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15204     if (needOppositeCond)
15205       CC = X86::GetOppositeBranchCondition(CC);
15206     return SetCC.getOperand(1);
15207   case X86ISD::CMOV: {
15208     // Check whether false/true value has canonical one, i.e. 0 or 1.
15209     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15210     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15211     // Quit if true value is not a constant.
15212     if (!TVal)
15213       return SDValue();
15214     // Quit if false value is not a constant.
15215     if (!FVal) {
15216       // A special case for rdrand, where 0 is set if false cond is found.
15217       SDValue Op = SetCC.getOperand(0);
15218       if (Op.getOpcode() != X86ISD::RDRAND)
15219         return SDValue();
15220     }
15221     // Quit if false value is not the constant 0 or 1.
15222     bool FValIsFalse = true;
15223     if (FVal && FVal->getZExtValue() != 0) {
15224       if (FVal->getZExtValue() != 1)
15225         return SDValue();
15226       // If FVal is 1, opposite cond is needed.
15227       needOppositeCond = !needOppositeCond;
15228       FValIsFalse = false;
15229     }
15230     // Quit if TVal is not the constant opposite of FVal.
15231     if (FValIsFalse && TVal->getZExtValue() != 1)
15232       return SDValue();
15233     if (!FValIsFalse && TVal->getZExtValue() != 0)
15234       return SDValue();
15235     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15236     if (needOppositeCond)
15237       CC = X86::GetOppositeBranchCondition(CC);
15238     return SetCC.getOperand(3);
15239   }
15240   }
15241
15242   return SDValue();
15243 }
15244
15245 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15246 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15247                                   TargetLowering::DAGCombinerInfo &DCI,
15248                                   const X86Subtarget *Subtarget) {
15249   DebugLoc DL = N->getDebugLoc();
15250
15251   // If the flag operand isn't dead, don't touch this CMOV.
15252   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15253     return SDValue();
15254
15255   SDValue FalseOp = N->getOperand(0);
15256   SDValue TrueOp = N->getOperand(1);
15257   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15258   SDValue Cond = N->getOperand(3);
15259
15260   if (CC == X86::COND_E || CC == X86::COND_NE) {
15261     switch (Cond.getOpcode()) {
15262     default: break;
15263     case X86ISD::BSR:
15264     case X86ISD::BSF:
15265       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15266       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15267         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15268     }
15269   }
15270
15271   SDValue Flags;
15272
15273   Flags = checkBoolTestSetCCCombine(Cond, CC);
15274   if (Flags.getNode() &&
15275       // Extra check as FCMOV only supports a subset of X86 cond.
15276       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15277     SDValue Ops[] = { FalseOp, TrueOp,
15278                       DAG.getConstant(CC, MVT::i8), Flags };
15279     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15280                        Ops, array_lengthof(Ops));
15281   }
15282
15283   // If this is a select between two integer constants, try to do some
15284   // optimizations.  Note that the operands are ordered the opposite of SELECT
15285   // operands.
15286   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15287     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15288       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15289       // larger than FalseC (the false value).
15290       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15291         CC = X86::GetOppositeBranchCondition(CC);
15292         std::swap(TrueC, FalseC);
15293         std::swap(TrueOp, FalseOp);
15294       }
15295
15296       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15297       // This is efficient for any integer data type (including i8/i16) and
15298       // shift amount.
15299       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15300         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15301                            DAG.getConstant(CC, MVT::i8), Cond);
15302
15303         // Zero extend the condition if needed.
15304         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15305
15306         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15307         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15308                            DAG.getConstant(ShAmt, MVT::i8));
15309         if (N->getNumValues() == 2)  // Dead flag value?
15310           return DCI.CombineTo(N, Cond, SDValue());
15311         return Cond;
15312       }
15313
15314       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15315       // for any integer data type, including i8/i16.
15316       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15317         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15318                            DAG.getConstant(CC, MVT::i8), Cond);
15319
15320         // Zero extend the condition if needed.
15321         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15322                            FalseC->getValueType(0), Cond);
15323         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15324                            SDValue(FalseC, 0));
15325
15326         if (N->getNumValues() == 2)  // Dead flag value?
15327           return DCI.CombineTo(N, Cond, SDValue());
15328         return Cond;
15329       }
15330
15331       // Optimize cases that will turn into an LEA instruction.  This requires
15332       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15333       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15334         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15335         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15336
15337         bool isFastMultiplier = false;
15338         if (Diff < 10) {
15339           switch ((unsigned char)Diff) {
15340           default: break;
15341           case 1:  // result = add base, cond
15342           case 2:  // result = lea base(    , cond*2)
15343           case 3:  // result = lea base(cond, cond*2)
15344           case 4:  // result = lea base(    , cond*4)
15345           case 5:  // result = lea base(cond, cond*4)
15346           case 8:  // result = lea base(    , cond*8)
15347           case 9:  // result = lea base(cond, cond*8)
15348             isFastMultiplier = true;
15349             break;
15350           }
15351         }
15352
15353         if (isFastMultiplier) {
15354           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15355           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15356                              DAG.getConstant(CC, MVT::i8), Cond);
15357           // Zero extend the condition if needed.
15358           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15359                              Cond);
15360           // Scale the condition by the difference.
15361           if (Diff != 1)
15362             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15363                                DAG.getConstant(Diff, Cond.getValueType()));
15364
15365           // Add the base if non-zero.
15366           if (FalseC->getAPIntValue() != 0)
15367             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15368                                SDValue(FalseC, 0));
15369           if (N->getNumValues() == 2)  // Dead flag value?
15370             return DCI.CombineTo(N, Cond, SDValue());
15371           return Cond;
15372         }
15373       }
15374     }
15375   }
15376
15377   // Handle these cases:
15378   //   (select (x != c), e, c) -> select (x != c), e, x),
15379   //   (select (x == c), c, e) -> select (x == c), x, e)
15380   // where the c is an integer constant, and the "select" is the combination
15381   // of CMOV and CMP.
15382   //
15383   // The rationale for this change is that the conditional-move from a constant
15384   // needs two instructions, however, conditional-move from a register needs
15385   // only one instruction.
15386   //
15387   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15388   //  some instruction-combining opportunities. This opt needs to be
15389   //  postponed as late as possible.
15390   //
15391   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15392     // the DCI.xxxx conditions are provided to postpone the optimization as
15393     // late as possible.
15394
15395     ConstantSDNode *CmpAgainst = 0;
15396     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15397         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15398         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15399
15400       if (CC == X86::COND_NE &&
15401           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15402         CC = X86::GetOppositeBranchCondition(CC);
15403         std::swap(TrueOp, FalseOp);
15404       }
15405
15406       if (CC == X86::COND_E &&
15407           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15408         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15409                           DAG.getConstant(CC, MVT::i8), Cond };
15410         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15411                            array_lengthof(Ops));
15412       }
15413     }
15414   }
15415
15416   return SDValue();
15417 }
15418
15419
15420 /// PerformMulCombine - Optimize a single multiply with constant into two
15421 /// in order to implement it with two cheaper instructions, e.g.
15422 /// LEA + SHL, LEA + LEA.
15423 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15424                                  TargetLowering::DAGCombinerInfo &DCI) {
15425   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15426     return SDValue();
15427
15428   EVT VT = N->getValueType(0);
15429   if (VT != MVT::i64)
15430     return SDValue();
15431
15432   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15433   if (!C)
15434     return SDValue();
15435   uint64_t MulAmt = C->getZExtValue();
15436   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15437     return SDValue();
15438
15439   uint64_t MulAmt1 = 0;
15440   uint64_t MulAmt2 = 0;
15441   if ((MulAmt % 9) == 0) {
15442     MulAmt1 = 9;
15443     MulAmt2 = MulAmt / 9;
15444   } else if ((MulAmt % 5) == 0) {
15445     MulAmt1 = 5;
15446     MulAmt2 = MulAmt / 5;
15447   } else if ((MulAmt % 3) == 0) {
15448     MulAmt1 = 3;
15449     MulAmt2 = MulAmt / 3;
15450   }
15451   if (MulAmt2 &&
15452       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15453     DebugLoc DL = N->getDebugLoc();
15454
15455     if (isPowerOf2_64(MulAmt2) &&
15456         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15457       // If second multiplifer is pow2, issue it first. We want the multiply by
15458       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15459       // is an add.
15460       std::swap(MulAmt1, MulAmt2);
15461
15462     SDValue NewMul;
15463     if (isPowerOf2_64(MulAmt1))
15464       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15465                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15466     else
15467       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15468                            DAG.getConstant(MulAmt1, VT));
15469
15470     if (isPowerOf2_64(MulAmt2))
15471       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15472                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15473     else
15474       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15475                            DAG.getConstant(MulAmt2, VT));
15476
15477     // Do not add new nodes to DAG combiner worklist.
15478     DCI.CombineTo(N, NewMul, false);
15479   }
15480   return SDValue();
15481 }
15482
15483 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15484   SDValue N0 = N->getOperand(0);
15485   SDValue N1 = N->getOperand(1);
15486   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15487   EVT VT = N0.getValueType();
15488
15489   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15490   // since the result of setcc_c is all zero's or all ones.
15491   if (VT.isInteger() && !VT.isVector() &&
15492       N1C && N0.getOpcode() == ISD::AND &&
15493       N0.getOperand(1).getOpcode() == ISD::Constant) {
15494     SDValue N00 = N0.getOperand(0);
15495     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15496         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15497           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15498          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15499       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15500       APInt ShAmt = N1C->getAPIntValue();
15501       Mask = Mask.shl(ShAmt);
15502       if (Mask != 0)
15503         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15504                            N00, DAG.getConstant(Mask, VT));
15505     }
15506   }
15507
15508
15509   // Hardware support for vector shifts is sparse which makes us scalarize the
15510   // vector operations in many cases. Also, on sandybridge ADD is faster than
15511   // shl.
15512   // (shl V, 1) -> add V,V
15513   if (isSplatVector(N1.getNode())) {
15514     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15515     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15516     // We shift all of the values by one. In many cases we do not have
15517     // hardware support for this operation. This is better expressed as an ADD
15518     // of two values.
15519     if (N1C && (1 == N1C->getZExtValue())) {
15520       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15521     }
15522   }
15523
15524   return SDValue();
15525 }
15526
15527 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15528 ///                       when possible.
15529 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15530                                    TargetLowering::DAGCombinerInfo &DCI,
15531                                    const X86Subtarget *Subtarget) {
15532   EVT VT = N->getValueType(0);
15533   if (N->getOpcode() == ISD::SHL) {
15534     SDValue V = PerformSHLCombine(N, DAG);
15535     if (V.getNode()) return V;
15536   }
15537
15538   // On X86 with SSE2 support, we can transform this to a vector shift if
15539   // all elements are shifted by the same amount.  We can't do this in legalize
15540   // because the a constant vector is typically transformed to a constant pool
15541   // so we have no knowledge of the shift amount.
15542   if (!Subtarget->hasSSE2())
15543     return SDValue();
15544
15545   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15546       (!Subtarget->hasInt256() ||
15547        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15548     return SDValue();
15549
15550   SDValue ShAmtOp = N->getOperand(1);
15551   EVT EltVT = VT.getVectorElementType();
15552   DebugLoc DL = N->getDebugLoc();
15553   SDValue BaseShAmt = SDValue();
15554   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15555     unsigned NumElts = VT.getVectorNumElements();
15556     unsigned i = 0;
15557     for (; i != NumElts; ++i) {
15558       SDValue Arg = ShAmtOp.getOperand(i);
15559       if (Arg.getOpcode() == ISD::UNDEF) continue;
15560       BaseShAmt = Arg;
15561       break;
15562     }
15563     // Handle the case where the build_vector is all undef
15564     // FIXME: Should DAG allow this?
15565     if (i == NumElts)
15566       return SDValue();
15567
15568     for (; i != NumElts; ++i) {
15569       SDValue Arg = ShAmtOp.getOperand(i);
15570       if (Arg.getOpcode() == ISD::UNDEF) continue;
15571       if (Arg != BaseShAmt) {
15572         return SDValue();
15573       }
15574     }
15575   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15576              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15577     SDValue InVec = ShAmtOp.getOperand(0);
15578     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15579       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15580       unsigned i = 0;
15581       for (; i != NumElts; ++i) {
15582         SDValue Arg = InVec.getOperand(i);
15583         if (Arg.getOpcode() == ISD::UNDEF) continue;
15584         BaseShAmt = Arg;
15585         break;
15586       }
15587     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15588        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15589          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15590          if (C->getZExtValue() == SplatIdx)
15591            BaseShAmt = InVec.getOperand(1);
15592        }
15593     }
15594     if (BaseShAmt.getNode() == 0) {
15595       // Don't create instructions with illegal types after legalize
15596       // types has run.
15597       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15598           !DCI.isBeforeLegalize())
15599         return SDValue();
15600
15601       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15602                               DAG.getIntPtrConstant(0));
15603     }
15604   } else
15605     return SDValue();
15606
15607   // The shift amount is an i32.
15608   if (EltVT.bitsGT(MVT::i32))
15609     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15610   else if (EltVT.bitsLT(MVT::i32))
15611     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15612
15613   // The shift amount is identical so we can do a vector shift.
15614   SDValue  ValOp = N->getOperand(0);
15615   switch (N->getOpcode()) {
15616   default:
15617     llvm_unreachable("Unknown shift opcode!");
15618   case ISD::SHL:
15619     switch (VT.getSimpleVT().SimpleTy) {
15620     default: return SDValue();
15621     case MVT::v2i64:
15622     case MVT::v4i32:
15623     case MVT::v8i16:
15624     case MVT::v4i64:
15625     case MVT::v8i32:
15626     case MVT::v16i16:
15627       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15628     }
15629   case ISD::SRA:
15630     switch (VT.getSimpleVT().SimpleTy) {
15631     default: return SDValue();
15632     case MVT::v4i32:
15633     case MVT::v8i16:
15634     case MVT::v8i32:
15635     case MVT::v16i16:
15636       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15637     }
15638   case ISD::SRL:
15639     switch (VT.getSimpleVT().SimpleTy) {
15640     default: return SDValue();
15641     case MVT::v2i64:
15642     case MVT::v4i32:
15643     case MVT::v8i16:
15644     case MVT::v4i64:
15645     case MVT::v8i32:
15646     case MVT::v16i16:
15647       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15648     }
15649   }
15650 }
15651
15652
15653 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15654 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15655 // and friends.  Likewise for OR -> CMPNEQSS.
15656 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15657                             TargetLowering::DAGCombinerInfo &DCI,
15658                             const X86Subtarget *Subtarget) {
15659   unsigned opcode;
15660
15661   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15662   // we're requiring SSE2 for both.
15663   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15664     SDValue N0 = N->getOperand(0);
15665     SDValue N1 = N->getOperand(1);
15666     SDValue CMP0 = N0->getOperand(1);
15667     SDValue CMP1 = N1->getOperand(1);
15668     DebugLoc DL = N->getDebugLoc();
15669
15670     // The SETCCs should both refer to the same CMP.
15671     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15672       return SDValue();
15673
15674     SDValue CMP00 = CMP0->getOperand(0);
15675     SDValue CMP01 = CMP0->getOperand(1);
15676     EVT     VT    = CMP00.getValueType();
15677
15678     if (VT == MVT::f32 || VT == MVT::f64) {
15679       bool ExpectingFlags = false;
15680       // Check for any users that want flags:
15681       for (SDNode::use_iterator UI = N->use_begin(),
15682              UE = N->use_end();
15683            !ExpectingFlags && UI != UE; ++UI)
15684         switch (UI->getOpcode()) {
15685         default:
15686         case ISD::BR_CC:
15687         case ISD::BRCOND:
15688         case ISD::SELECT:
15689           ExpectingFlags = true;
15690           break;
15691         case ISD::CopyToReg:
15692         case ISD::SIGN_EXTEND:
15693         case ISD::ZERO_EXTEND:
15694         case ISD::ANY_EXTEND:
15695           break;
15696         }
15697
15698       if (!ExpectingFlags) {
15699         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15700         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15701
15702         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15703           X86::CondCode tmp = cc0;
15704           cc0 = cc1;
15705           cc1 = tmp;
15706         }
15707
15708         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15709             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15710           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15711           X86ISD::NodeType NTOperator = is64BitFP ?
15712             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15713           // FIXME: need symbolic constants for these magic numbers.
15714           // See X86ATTInstPrinter.cpp:printSSECC().
15715           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15716           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15717                                               DAG.getConstant(x86cc, MVT::i8));
15718           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15719                                               OnesOrZeroesF);
15720           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15721                                       DAG.getConstant(1, MVT::i32));
15722           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15723           return OneBitOfTruth;
15724         }
15725       }
15726     }
15727   }
15728   return SDValue();
15729 }
15730
15731 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15732 /// so it can be folded inside ANDNP.
15733 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15734   EVT VT = N->getValueType(0);
15735
15736   // Match direct AllOnes for 128 and 256-bit vectors
15737   if (ISD::isBuildVectorAllOnes(N))
15738     return true;
15739
15740   // Look through a bit convert.
15741   if (N->getOpcode() == ISD::BITCAST)
15742     N = N->getOperand(0).getNode();
15743
15744   // Sometimes the operand may come from a insert_subvector building a 256-bit
15745   // allones vector
15746   if (VT.is256BitVector() &&
15747       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15748     SDValue V1 = N->getOperand(0);
15749     SDValue V2 = N->getOperand(1);
15750
15751     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15752         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15753         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15754         ISD::isBuildVectorAllOnes(V2.getNode()))
15755       return true;
15756   }
15757
15758   return false;
15759 }
15760
15761 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15762                                  TargetLowering::DAGCombinerInfo &DCI,
15763                                  const X86Subtarget *Subtarget) {
15764   if (DCI.isBeforeLegalizeOps())
15765     return SDValue();
15766
15767   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15768   if (R.getNode())
15769     return R;
15770
15771   EVT VT = N->getValueType(0);
15772
15773   // Create BLSI, and BLSR instructions
15774   // BLSI is X & (-X)
15775   // BLSR is X & (X-1)
15776   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15777     SDValue N0 = N->getOperand(0);
15778     SDValue N1 = N->getOperand(1);
15779     DebugLoc DL = N->getDebugLoc();
15780
15781     // Check LHS for neg
15782     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15783         isZero(N0.getOperand(0)))
15784       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15785
15786     // Check RHS for neg
15787     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15788         isZero(N1.getOperand(0)))
15789       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15790
15791     // Check LHS for X-1
15792     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15793         isAllOnes(N0.getOperand(1)))
15794       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15795
15796     // Check RHS for X-1
15797     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15798         isAllOnes(N1.getOperand(1)))
15799       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15800
15801     return SDValue();
15802   }
15803
15804   // Want to form ANDNP nodes:
15805   // 1) In the hopes of then easily combining them with OR and AND nodes
15806   //    to form PBLEND/PSIGN.
15807   // 2) To match ANDN packed intrinsics
15808   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15809     return SDValue();
15810
15811   SDValue N0 = N->getOperand(0);
15812   SDValue N1 = N->getOperand(1);
15813   DebugLoc DL = N->getDebugLoc();
15814
15815   // Check LHS for vnot
15816   if (N0.getOpcode() == ISD::XOR &&
15817       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15818       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15819     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15820
15821   // Check RHS for vnot
15822   if (N1.getOpcode() == ISD::XOR &&
15823       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15824       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15825     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15826
15827   return SDValue();
15828 }
15829
15830 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15831                                 TargetLowering::DAGCombinerInfo &DCI,
15832                                 const X86Subtarget *Subtarget) {
15833   if (DCI.isBeforeLegalizeOps())
15834     return SDValue();
15835
15836   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15837   if (R.getNode())
15838     return R;
15839
15840   EVT VT = N->getValueType(0);
15841
15842   SDValue N0 = N->getOperand(0);
15843   SDValue N1 = N->getOperand(1);
15844
15845   // look for psign/blend
15846   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15847     if (!Subtarget->hasSSSE3() ||
15848         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
15849       return SDValue();
15850
15851     // Canonicalize pandn to RHS
15852     if (N0.getOpcode() == X86ISD::ANDNP)
15853       std::swap(N0, N1);
15854     // or (and (m, y), (pandn m, x))
15855     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15856       SDValue Mask = N1.getOperand(0);
15857       SDValue X    = N1.getOperand(1);
15858       SDValue Y;
15859       if (N0.getOperand(0) == Mask)
15860         Y = N0.getOperand(1);
15861       if (N0.getOperand(1) == Mask)
15862         Y = N0.getOperand(0);
15863
15864       // Check to see if the mask appeared in both the AND and ANDNP and
15865       if (!Y.getNode())
15866         return SDValue();
15867
15868       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15869       // Look through mask bitcast.
15870       if (Mask.getOpcode() == ISD::BITCAST)
15871         Mask = Mask.getOperand(0);
15872       if (X.getOpcode() == ISD::BITCAST)
15873         X = X.getOperand(0);
15874       if (Y.getOpcode() == ISD::BITCAST)
15875         Y = Y.getOperand(0);
15876
15877       EVT MaskVT = Mask.getValueType();
15878
15879       // Validate that the Mask operand is a vector sra node.
15880       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15881       // there is no psrai.b
15882       if (Mask.getOpcode() != X86ISD::VSRAI)
15883         return SDValue();
15884
15885       // Check that the SRA is all signbits.
15886       SDValue SraC = Mask.getOperand(1);
15887       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15888       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15889       if ((SraAmt + 1) != EltBits)
15890         return SDValue();
15891
15892       DebugLoc DL = N->getDebugLoc();
15893
15894       // We are going to replace the AND, OR, NAND with either BLEND
15895       // or PSIGN, which only look at the MSB. The VSRAI instruction
15896       // does not affect the highest bit, so we can get rid of it.
15897       Mask = Mask.getOperand(0);
15898
15899       // Now we know we at least have a plendvb with the mask val.  See if
15900       // we can form a psignb/w/d.
15901       // psign = x.type == y.type == mask.type && y = sub(0, x);
15902       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15903           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15904           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15905         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15906                "Unsupported VT for PSIGN");
15907         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
15908         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15909       }
15910       // PBLENDVB only available on SSE 4.1
15911       if (!Subtarget->hasSSE41())
15912         return SDValue();
15913
15914       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15915
15916       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15917       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15918       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15919       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15920       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15921     }
15922   }
15923
15924   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15925     return SDValue();
15926
15927   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15928   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15929     std::swap(N0, N1);
15930   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15931     return SDValue();
15932   if (!N0.hasOneUse() || !N1.hasOneUse())
15933     return SDValue();
15934
15935   SDValue ShAmt0 = N0.getOperand(1);
15936   if (ShAmt0.getValueType() != MVT::i8)
15937     return SDValue();
15938   SDValue ShAmt1 = N1.getOperand(1);
15939   if (ShAmt1.getValueType() != MVT::i8)
15940     return SDValue();
15941   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15942     ShAmt0 = ShAmt0.getOperand(0);
15943   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15944     ShAmt1 = ShAmt1.getOperand(0);
15945
15946   DebugLoc DL = N->getDebugLoc();
15947   unsigned Opc = X86ISD::SHLD;
15948   SDValue Op0 = N0.getOperand(0);
15949   SDValue Op1 = N1.getOperand(0);
15950   if (ShAmt0.getOpcode() == ISD::SUB) {
15951     Opc = X86ISD::SHRD;
15952     std::swap(Op0, Op1);
15953     std::swap(ShAmt0, ShAmt1);
15954   }
15955
15956   unsigned Bits = VT.getSizeInBits();
15957   if (ShAmt1.getOpcode() == ISD::SUB) {
15958     SDValue Sum = ShAmt1.getOperand(0);
15959     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15960       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15961       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15962         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15963       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15964         return DAG.getNode(Opc, DL, VT,
15965                            Op0, Op1,
15966                            DAG.getNode(ISD::TRUNCATE, DL,
15967                                        MVT::i8, ShAmt0));
15968     }
15969   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15970     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15971     if (ShAmt0C &&
15972         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15973       return DAG.getNode(Opc, DL, VT,
15974                          N0.getOperand(0), N1.getOperand(0),
15975                          DAG.getNode(ISD::TRUNCATE, DL,
15976                                        MVT::i8, ShAmt0));
15977   }
15978
15979   return SDValue();
15980 }
15981
15982 // Generate NEG and CMOV for integer abs.
15983 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15984   EVT VT = N->getValueType(0);
15985
15986   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15987   // 8-bit integer abs to NEG and CMOV.
15988   if (VT.isInteger() && VT.getSizeInBits() == 8)
15989     return SDValue();
15990
15991   SDValue N0 = N->getOperand(0);
15992   SDValue N1 = N->getOperand(1);
15993   DebugLoc DL = N->getDebugLoc();
15994
15995   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15996   // and change it to SUB and CMOV.
15997   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15998       N0.getOpcode() == ISD::ADD &&
15999       N0.getOperand(1) == N1 &&
16000       N1.getOpcode() == ISD::SRA &&
16001       N1.getOperand(0) == N0.getOperand(0))
16002     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16003       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16004         // Generate SUB & CMOV.
16005         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16006                                   DAG.getConstant(0, VT), N0.getOperand(0));
16007
16008         SDValue Ops[] = { N0.getOperand(0), Neg,
16009                           DAG.getConstant(X86::COND_GE, MVT::i8),
16010                           SDValue(Neg.getNode(), 1) };
16011         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16012                            Ops, array_lengthof(Ops));
16013       }
16014   return SDValue();
16015 }
16016
16017 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16018 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16019                                  TargetLowering::DAGCombinerInfo &DCI,
16020                                  const X86Subtarget *Subtarget) {
16021   if (DCI.isBeforeLegalizeOps())
16022     return SDValue();
16023
16024   if (Subtarget->hasCMov()) {
16025     SDValue RV = performIntegerAbsCombine(N, DAG);
16026     if (RV.getNode())
16027       return RV;
16028   }
16029
16030   // Try forming BMI if it is available.
16031   if (!Subtarget->hasBMI())
16032     return SDValue();
16033
16034   EVT VT = N->getValueType(0);
16035
16036   if (VT != MVT::i32 && VT != MVT::i64)
16037     return SDValue();
16038
16039   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16040
16041   // Create BLSMSK instructions by finding X ^ (X-1)
16042   SDValue N0 = N->getOperand(0);
16043   SDValue N1 = N->getOperand(1);
16044   DebugLoc DL = N->getDebugLoc();
16045
16046   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16047       isAllOnes(N0.getOperand(1)))
16048     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16049
16050   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16051       isAllOnes(N1.getOperand(1)))
16052     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16053
16054   return SDValue();
16055 }
16056
16057 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16058 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16059                                   TargetLowering::DAGCombinerInfo &DCI,
16060                                   const X86Subtarget *Subtarget) {
16061   LoadSDNode *Ld = cast<LoadSDNode>(N);
16062   EVT RegVT = Ld->getValueType(0);
16063   EVT MemVT = Ld->getMemoryVT();
16064   DebugLoc dl = Ld->getDebugLoc();
16065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16066
16067   ISD::LoadExtType Ext = Ld->getExtensionType();
16068
16069   // If this is a vector EXT Load then attempt to optimize it using a
16070   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16071   // expansion is still better than scalar code.
16072   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16073   // emit a shuffle and a arithmetic shift.
16074   // TODO: It is possible to support ZExt by zeroing the undef values
16075   // during the shuffle phase or after the shuffle.
16076   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16077       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16078     assert(MemVT != RegVT && "Cannot extend to the same type");
16079     assert(MemVT.isVector() && "Must load a vector from memory");
16080
16081     unsigned NumElems = RegVT.getVectorNumElements();
16082     unsigned RegSz = RegVT.getSizeInBits();
16083     unsigned MemSz = MemVT.getSizeInBits();
16084     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16085
16086     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16087       return SDValue();
16088
16089     // All sizes must be a power of two.
16090     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16091       return SDValue();
16092
16093     // Attempt to load the original value using scalar loads.
16094     // Find the largest scalar type that divides the total loaded size.
16095     MVT SclrLoadTy = MVT::i8;
16096     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16097          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16098       MVT Tp = (MVT::SimpleValueType)tp;
16099       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16100         SclrLoadTy = Tp;
16101       }
16102     }
16103
16104     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16105     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16106         (64 <= MemSz))
16107       SclrLoadTy = MVT::f64;
16108
16109     // Calculate the number of scalar loads that we need to perform
16110     // in order to load our vector from memory.
16111     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16112     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16113       return SDValue();
16114
16115     unsigned loadRegZize = RegSz;
16116     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16117       loadRegZize /= 2;
16118
16119     // Represent our vector as a sequence of elements which are the
16120     // largest scalar that we can load.
16121     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16122       loadRegZize/SclrLoadTy.getSizeInBits());
16123
16124     // Represent the data using the same element type that is stored in
16125     // memory. In practice, we ''widen'' MemVT.
16126     EVT WideVecVT = 
16127           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16128                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16129
16130     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16131       "Invalid vector type");
16132
16133     // We can't shuffle using an illegal type.
16134     if (!TLI.isTypeLegal(WideVecVT))
16135       return SDValue();
16136
16137     SmallVector<SDValue, 8> Chains;
16138     SDValue Ptr = Ld->getBasePtr();
16139     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16140                                         TLI.getPointerTy());
16141     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16142
16143     for (unsigned i = 0; i < NumLoads; ++i) {
16144       // Perform a single load.
16145       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16146                                        Ptr, Ld->getPointerInfo(),
16147                                        Ld->isVolatile(), Ld->isNonTemporal(),
16148                                        Ld->isInvariant(), Ld->getAlignment());
16149       Chains.push_back(ScalarLoad.getValue(1));
16150       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16151       // another round of DAGCombining.
16152       if (i == 0)
16153         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16154       else
16155         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16156                           ScalarLoad, DAG.getIntPtrConstant(i));
16157
16158       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16159     }
16160
16161     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16162                                Chains.size());
16163
16164     // Bitcast the loaded value to a vector of the original element type, in
16165     // the size of the target vector type.
16166     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16167     unsigned SizeRatio = RegSz/MemSz;
16168
16169     if (Ext == ISD::SEXTLOAD) {
16170       // If we have SSE4.1 we can directly emit a VSEXT node.
16171       if (Subtarget->hasSSE41()) {
16172         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16173         return DCI.CombineTo(N, Sext, TF, true);
16174       }
16175
16176       // Otherwise we'll shuffle the small elements in the high bits of the
16177       // larger type and perform an arithmetic shift. If the shift is not legal
16178       // it's better to scalarize.
16179       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16180         return SDValue();
16181
16182       // Redistribute the loaded elements into the different locations.
16183       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16184       for (unsigned i = 0; i != NumElems; ++i)
16185         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16186
16187       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16188                                            DAG.getUNDEF(WideVecVT),
16189                                            &ShuffleVec[0]);
16190
16191       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16192
16193       // Build the arithmetic shift.
16194       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16195                      MemVT.getVectorElementType().getSizeInBits();
16196       SmallVector<SDValue, 8> C(NumElems,
16197                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16198       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16199       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16200
16201       return DCI.CombineTo(N, Shuff, TF, true);
16202     }
16203
16204     // Redistribute the loaded elements into the different locations.
16205     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16206     for (unsigned i = 0; i != NumElems; ++i)
16207       ShuffleVec[i*SizeRatio] = i;
16208
16209     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16210                                          DAG.getUNDEF(WideVecVT),
16211                                          &ShuffleVec[0]);
16212
16213     // Bitcast to the requested type.
16214     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16215     // Replace the original load with the new sequence
16216     // and return the new chain.
16217     return DCI.CombineTo(N, Shuff, TF, true);
16218   }
16219
16220   return SDValue();
16221 }
16222
16223 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16224 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16225                                    const X86Subtarget *Subtarget) {
16226   StoreSDNode *St = cast<StoreSDNode>(N);
16227   EVT VT = St->getValue().getValueType();
16228   EVT StVT = St->getMemoryVT();
16229   DebugLoc dl = St->getDebugLoc();
16230   SDValue StoredVal = St->getOperand(1);
16231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16232
16233   // If we are saving a concatenation of two XMM registers, perform two stores.
16234   // On Sandy Bridge, 256-bit memory operations are executed by two
16235   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16236   // memory  operation.
16237   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16238       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16239       StoredVal.getNumOperands() == 2) {
16240     SDValue Value0 = StoredVal.getOperand(0);
16241     SDValue Value1 = StoredVal.getOperand(1);
16242
16243     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16244     SDValue Ptr0 = St->getBasePtr();
16245     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16246
16247     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16248                                 St->getPointerInfo(), St->isVolatile(),
16249                                 St->isNonTemporal(), St->getAlignment());
16250     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16251                                 St->getPointerInfo(), St->isVolatile(),
16252                                 St->isNonTemporal(), St->getAlignment());
16253     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16254   }
16255
16256   // Optimize trunc store (of multiple scalars) to shuffle and store.
16257   // First, pack all of the elements in one place. Next, store to memory
16258   // in fewer chunks.
16259   if (St->isTruncatingStore() && VT.isVector()) {
16260     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16261     unsigned NumElems = VT.getVectorNumElements();
16262     assert(StVT != VT && "Cannot truncate to the same type");
16263     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16264     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16265
16266     // From, To sizes and ElemCount must be pow of two
16267     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16268     // We are going to use the original vector elt for storing.
16269     // Accumulated smaller vector elements must be a multiple of the store size.
16270     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16271
16272     unsigned SizeRatio  = FromSz / ToSz;
16273
16274     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16275
16276     // Create a type on which we perform the shuffle
16277     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16278             StVT.getScalarType(), NumElems*SizeRatio);
16279
16280     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16281
16282     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16283     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16284     for (unsigned i = 0; i != NumElems; ++i)
16285       ShuffleVec[i] = i * SizeRatio;
16286
16287     // Can't shuffle using an illegal type.
16288     if (!TLI.isTypeLegal(WideVecVT))
16289       return SDValue();
16290
16291     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16292                                          DAG.getUNDEF(WideVecVT),
16293                                          &ShuffleVec[0]);
16294     // At this point all of the data is stored at the bottom of the
16295     // register. We now need to save it to mem.
16296
16297     // Find the largest store unit
16298     MVT StoreType = MVT::i8;
16299     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16300          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16301       MVT Tp = (MVT::SimpleValueType)tp;
16302       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16303         StoreType = Tp;
16304     }
16305
16306     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16307     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16308         (64 <= NumElems * ToSz))
16309       StoreType = MVT::f64;
16310
16311     // Bitcast the original vector into a vector of store-size units
16312     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16313             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16314     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16315     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16316     SmallVector<SDValue, 8> Chains;
16317     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16318                                         TLI.getPointerTy());
16319     SDValue Ptr = St->getBasePtr();
16320
16321     // Perform one or more big stores into memory.
16322     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16323       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16324                                    StoreType, ShuffWide,
16325                                    DAG.getIntPtrConstant(i));
16326       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16327                                 St->getPointerInfo(), St->isVolatile(),
16328                                 St->isNonTemporal(), St->getAlignment());
16329       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16330       Chains.push_back(Ch);
16331     }
16332
16333     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16334                                Chains.size());
16335   }
16336
16337
16338   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16339   // the FP state in cases where an emms may be missing.
16340   // A preferable solution to the general problem is to figure out the right
16341   // places to insert EMMS.  This qualifies as a quick hack.
16342
16343   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16344   if (VT.getSizeInBits() != 64)
16345     return SDValue();
16346
16347   const Function *F = DAG.getMachineFunction().getFunction();
16348   bool NoImplicitFloatOps = F->getFnAttributes().
16349     hasAttribute(Attribute::NoImplicitFloat);
16350   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16351                      && Subtarget->hasSSE2();
16352   if ((VT.isVector() ||
16353        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16354       isa<LoadSDNode>(St->getValue()) &&
16355       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16356       St->getChain().hasOneUse() && !St->isVolatile()) {
16357     SDNode* LdVal = St->getValue().getNode();
16358     LoadSDNode *Ld = 0;
16359     int TokenFactorIndex = -1;
16360     SmallVector<SDValue, 8> Ops;
16361     SDNode* ChainVal = St->getChain().getNode();
16362     // Must be a store of a load.  We currently handle two cases:  the load
16363     // is a direct child, and it's under an intervening TokenFactor.  It is
16364     // possible to dig deeper under nested TokenFactors.
16365     if (ChainVal == LdVal)
16366       Ld = cast<LoadSDNode>(St->getChain());
16367     else if (St->getValue().hasOneUse() &&
16368              ChainVal->getOpcode() == ISD::TokenFactor) {
16369       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16370         if (ChainVal->getOperand(i).getNode() == LdVal) {
16371           TokenFactorIndex = i;
16372           Ld = cast<LoadSDNode>(St->getValue());
16373         } else
16374           Ops.push_back(ChainVal->getOperand(i));
16375       }
16376     }
16377
16378     if (!Ld || !ISD::isNormalLoad(Ld))
16379       return SDValue();
16380
16381     // If this is not the MMX case, i.e. we are just turning i64 load/store
16382     // into f64 load/store, avoid the transformation if there are multiple
16383     // uses of the loaded value.
16384     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16385       return SDValue();
16386
16387     DebugLoc LdDL = Ld->getDebugLoc();
16388     DebugLoc StDL = N->getDebugLoc();
16389     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16390     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16391     // pair instead.
16392     if (Subtarget->is64Bit() || F64IsLegal) {
16393       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16394       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16395                                   Ld->getPointerInfo(), Ld->isVolatile(),
16396                                   Ld->isNonTemporal(), Ld->isInvariant(),
16397                                   Ld->getAlignment());
16398       SDValue NewChain = NewLd.getValue(1);
16399       if (TokenFactorIndex != -1) {
16400         Ops.push_back(NewChain);
16401         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16402                                Ops.size());
16403       }
16404       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16405                           St->getPointerInfo(),
16406                           St->isVolatile(), St->isNonTemporal(),
16407                           St->getAlignment());
16408     }
16409
16410     // Otherwise, lower to two pairs of 32-bit loads / stores.
16411     SDValue LoAddr = Ld->getBasePtr();
16412     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16413                                  DAG.getConstant(4, MVT::i32));
16414
16415     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16416                                Ld->getPointerInfo(),
16417                                Ld->isVolatile(), Ld->isNonTemporal(),
16418                                Ld->isInvariant(), Ld->getAlignment());
16419     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16420                                Ld->getPointerInfo().getWithOffset(4),
16421                                Ld->isVolatile(), Ld->isNonTemporal(),
16422                                Ld->isInvariant(),
16423                                MinAlign(Ld->getAlignment(), 4));
16424
16425     SDValue NewChain = LoLd.getValue(1);
16426     if (TokenFactorIndex != -1) {
16427       Ops.push_back(LoLd);
16428       Ops.push_back(HiLd);
16429       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16430                              Ops.size());
16431     }
16432
16433     LoAddr = St->getBasePtr();
16434     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16435                          DAG.getConstant(4, MVT::i32));
16436
16437     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16438                                 St->getPointerInfo(),
16439                                 St->isVolatile(), St->isNonTemporal(),
16440                                 St->getAlignment());
16441     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16442                                 St->getPointerInfo().getWithOffset(4),
16443                                 St->isVolatile(),
16444                                 St->isNonTemporal(),
16445                                 MinAlign(St->getAlignment(), 4));
16446     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16447   }
16448   return SDValue();
16449 }
16450
16451 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16452 /// and return the operands for the horizontal operation in LHS and RHS.  A
16453 /// horizontal operation performs the binary operation on successive elements
16454 /// of its first operand, then on successive elements of its second operand,
16455 /// returning the resulting values in a vector.  For example, if
16456 ///   A = < float a0, float a1, float a2, float a3 >
16457 /// and
16458 ///   B = < float b0, float b1, float b2, float b3 >
16459 /// then the result of doing a horizontal operation on A and B is
16460 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16461 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16462 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16463 /// set to A, RHS to B, and the routine returns 'true'.
16464 /// Note that the binary operation should have the property that if one of the
16465 /// operands is UNDEF then the result is UNDEF.
16466 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16467   // Look for the following pattern: if
16468   //   A = < float a0, float a1, float a2, float a3 >
16469   //   B = < float b0, float b1, float b2, float b3 >
16470   // and
16471   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16472   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16473   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16474   // which is A horizontal-op B.
16475
16476   // At least one of the operands should be a vector shuffle.
16477   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16478       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16479     return false;
16480
16481   EVT VT = LHS.getValueType();
16482
16483   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16484          "Unsupported vector type for horizontal add/sub");
16485
16486   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16487   // operate independently on 128-bit lanes.
16488   unsigned NumElts = VT.getVectorNumElements();
16489   unsigned NumLanes = VT.getSizeInBits()/128;
16490   unsigned NumLaneElts = NumElts / NumLanes;
16491   assert((NumLaneElts % 2 == 0) &&
16492          "Vector type should have an even number of elements in each lane");
16493   unsigned HalfLaneElts = NumLaneElts/2;
16494
16495   // View LHS in the form
16496   //   LHS = VECTOR_SHUFFLE A, B, LMask
16497   // If LHS is not a shuffle then pretend it is the shuffle
16498   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16499   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16500   // type VT.
16501   SDValue A, B;
16502   SmallVector<int, 16> LMask(NumElts);
16503   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16504     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16505       A = LHS.getOperand(0);
16506     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16507       B = LHS.getOperand(1);
16508     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16509     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16510   } else {
16511     if (LHS.getOpcode() != ISD::UNDEF)
16512       A = LHS;
16513     for (unsigned i = 0; i != NumElts; ++i)
16514       LMask[i] = i;
16515   }
16516
16517   // Likewise, view RHS in the form
16518   //   RHS = VECTOR_SHUFFLE C, D, RMask
16519   SDValue C, D;
16520   SmallVector<int, 16> RMask(NumElts);
16521   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16522     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16523       C = RHS.getOperand(0);
16524     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16525       D = RHS.getOperand(1);
16526     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16527     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16528   } else {
16529     if (RHS.getOpcode() != ISD::UNDEF)
16530       C = RHS;
16531     for (unsigned i = 0; i != NumElts; ++i)
16532       RMask[i] = i;
16533   }
16534
16535   // Check that the shuffles are both shuffling the same vectors.
16536   if (!(A == C && B == D) && !(A == D && B == C))
16537     return false;
16538
16539   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16540   if (!A.getNode() && !B.getNode())
16541     return false;
16542
16543   // If A and B occur in reverse order in RHS, then "swap" them (which means
16544   // rewriting the mask).
16545   if (A != C)
16546     CommuteVectorShuffleMask(RMask, NumElts);
16547
16548   // At this point LHS and RHS are equivalent to
16549   //   LHS = VECTOR_SHUFFLE A, B, LMask
16550   //   RHS = VECTOR_SHUFFLE A, B, RMask
16551   // Check that the masks correspond to performing a horizontal operation.
16552   for (unsigned i = 0; i != NumElts; ++i) {
16553     int LIdx = LMask[i], RIdx = RMask[i];
16554
16555     // Ignore any UNDEF components.
16556     if (LIdx < 0 || RIdx < 0 ||
16557         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16558         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16559       continue;
16560
16561     // Check that successive elements are being operated on.  If not, this is
16562     // not a horizontal operation.
16563     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16564     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16565     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16566     if (!(LIdx == Index && RIdx == Index + 1) &&
16567         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16568       return false;
16569   }
16570
16571   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16572   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16573   return true;
16574 }
16575
16576 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16577 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16578                                   const X86Subtarget *Subtarget) {
16579   EVT VT = N->getValueType(0);
16580   SDValue LHS = N->getOperand(0);
16581   SDValue RHS = N->getOperand(1);
16582
16583   // Try to synthesize horizontal adds from adds of shuffles.
16584   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16585        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16586       isHorizontalBinOp(LHS, RHS, true))
16587     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16588   return SDValue();
16589 }
16590
16591 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16592 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16593                                   const X86Subtarget *Subtarget) {
16594   EVT VT = N->getValueType(0);
16595   SDValue LHS = N->getOperand(0);
16596   SDValue RHS = N->getOperand(1);
16597
16598   // Try to synthesize horizontal subs from subs of shuffles.
16599   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16600        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16601       isHorizontalBinOp(LHS, RHS, false))
16602     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16603   return SDValue();
16604 }
16605
16606 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16607 /// X86ISD::FXOR nodes.
16608 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16609   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16610   // F[X]OR(0.0, x) -> x
16611   // F[X]OR(x, 0.0) -> x
16612   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16613     if (C->getValueAPF().isPosZero())
16614       return N->getOperand(1);
16615   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16616     if (C->getValueAPF().isPosZero())
16617       return N->getOperand(0);
16618   return SDValue();
16619 }
16620
16621 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16622 /// X86ISD::FMAX nodes.
16623 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16624   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16625
16626   // Only perform optimizations if UnsafeMath is used.
16627   if (!DAG.getTarget().Options.UnsafeFPMath)
16628     return SDValue();
16629
16630   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16631   // into FMINC and FMAXC, which are Commutative operations.
16632   unsigned NewOp = 0;
16633   switch (N->getOpcode()) {
16634     default: llvm_unreachable("unknown opcode");
16635     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16636     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16637   }
16638
16639   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16640                      N->getOperand(0), N->getOperand(1));
16641 }
16642
16643
16644 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16645 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16646   // FAND(0.0, x) -> 0.0
16647   // FAND(x, 0.0) -> 0.0
16648   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16649     if (C->getValueAPF().isPosZero())
16650       return N->getOperand(0);
16651   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16652     if (C->getValueAPF().isPosZero())
16653       return N->getOperand(1);
16654   return SDValue();
16655 }
16656
16657 static SDValue PerformBTCombine(SDNode *N,
16658                                 SelectionDAG &DAG,
16659                                 TargetLowering::DAGCombinerInfo &DCI) {
16660   // BT ignores high bits in the bit index operand.
16661   SDValue Op1 = N->getOperand(1);
16662   if (Op1.hasOneUse()) {
16663     unsigned BitWidth = Op1.getValueSizeInBits();
16664     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16665     APInt KnownZero, KnownOne;
16666     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16667                                           !DCI.isBeforeLegalizeOps());
16668     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16669     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16670         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16671       DCI.CommitTargetLoweringOpt(TLO);
16672   }
16673   return SDValue();
16674 }
16675
16676 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16677   SDValue Op = N->getOperand(0);
16678   if (Op.getOpcode() == ISD::BITCAST)
16679     Op = Op.getOperand(0);
16680   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16681   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16682       VT.getVectorElementType().getSizeInBits() ==
16683       OpVT.getVectorElementType().getSizeInBits()) {
16684     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16685   }
16686   return SDValue();
16687 }
16688
16689 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16690                                   TargetLowering::DAGCombinerInfo &DCI,
16691                                   const X86Subtarget *Subtarget) {
16692   if (!DCI.isBeforeLegalizeOps())
16693     return SDValue();
16694
16695   if (!Subtarget->hasFp256())
16696     return SDValue();
16697
16698   EVT VT = N->getValueType(0);
16699   SDValue Op = N->getOperand(0);
16700   EVT OpVT = Op.getValueType();
16701   DebugLoc dl = N->getDebugLoc();
16702
16703   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16704       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16705
16706     if (Subtarget->hasInt256())
16707       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16708
16709     // Optimize vectors in AVX mode
16710     // Sign extend  v8i16 to v8i32 and
16711     //              v4i32 to v4i64
16712     //
16713     // Divide input vector into two parts
16714     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16715     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16716     // concat the vectors to original VT
16717
16718     unsigned NumElems = OpVT.getVectorNumElements();
16719     SDValue Undef = DAG.getUNDEF(OpVT);
16720
16721     SmallVector<int,8> ShufMask1(NumElems, -1);
16722     for (unsigned i = 0; i != NumElems/2; ++i)
16723       ShufMask1[i] = i;
16724
16725     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16726
16727     SmallVector<int,8> ShufMask2(NumElems, -1);
16728     for (unsigned i = 0; i != NumElems/2; ++i)
16729       ShufMask2[i] = i + NumElems/2;
16730
16731     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16732
16733     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16734                                   VT.getVectorNumElements()/2);
16735
16736     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16737     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16738
16739     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16740   }
16741   return SDValue();
16742 }
16743
16744 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16745                                  const X86Subtarget* Subtarget) {
16746   DebugLoc dl = N->getDebugLoc();
16747   EVT VT = N->getValueType(0);
16748
16749   // Let legalize expand this if it isn't a legal type yet.
16750   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16751     return SDValue();
16752
16753   EVT ScalarVT = VT.getScalarType();
16754   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16755       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16756     return SDValue();
16757
16758   SDValue A = N->getOperand(0);
16759   SDValue B = N->getOperand(1);
16760   SDValue C = N->getOperand(2);
16761
16762   bool NegA = (A.getOpcode() == ISD::FNEG);
16763   bool NegB = (B.getOpcode() == ISD::FNEG);
16764   bool NegC = (C.getOpcode() == ISD::FNEG);
16765
16766   // Negative multiplication when NegA xor NegB
16767   bool NegMul = (NegA != NegB);
16768   if (NegA)
16769     A = A.getOperand(0);
16770   if (NegB)
16771     B = B.getOperand(0);
16772   if (NegC)
16773     C = C.getOperand(0);
16774
16775   unsigned Opcode;
16776   if (!NegMul)
16777     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16778   else
16779     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16780
16781   return DAG.getNode(Opcode, dl, VT, A, B, C);
16782 }
16783
16784 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16785                                   TargetLowering::DAGCombinerInfo &DCI,
16786                                   const X86Subtarget *Subtarget) {
16787   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16788   //           (and (i32 x86isd::setcc_carry), 1)
16789   // This eliminates the zext. This transformation is necessary because
16790   // ISD::SETCC is always legalized to i8.
16791   DebugLoc dl = N->getDebugLoc();
16792   SDValue N0 = N->getOperand(0);
16793   EVT VT = N->getValueType(0);
16794   EVT OpVT = N0.getValueType();
16795
16796   if (N0.getOpcode() == ISD::AND &&
16797       N0.hasOneUse() &&
16798       N0.getOperand(0).hasOneUse()) {
16799     SDValue N00 = N0.getOperand(0);
16800     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16801       return SDValue();
16802     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16803     if (!C || C->getZExtValue() != 1)
16804       return SDValue();
16805     return DAG.getNode(ISD::AND, dl, VT,
16806                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16807                                    N00.getOperand(0), N00.getOperand(1)),
16808                        DAG.getConstant(1, VT));
16809   }
16810
16811   // Optimize vectors in AVX mode:
16812   //
16813   //   v8i16 -> v8i32
16814   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16815   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16816   //   Concat upper and lower parts.
16817   //
16818   //   v4i32 -> v4i64
16819   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16820   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16821   //   Concat upper and lower parts.
16822   //
16823   if (!DCI.isBeforeLegalizeOps())
16824     return SDValue();
16825
16826   if (!Subtarget->hasFp256())
16827     return SDValue();
16828
16829   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16830       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16831
16832     if (Subtarget->hasInt256())
16833       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16834
16835     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16836     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16837     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16838
16839     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16840                                VT.getVectorNumElements()/2);
16841
16842     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16843     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16844
16845     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16846   }
16847
16848   return SDValue();
16849 }
16850
16851 // Optimize x == -y --> x+y == 0
16852 //          x != -y --> x+y != 0
16853 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16854   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16855   SDValue LHS = N->getOperand(0);
16856   SDValue RHS = N->getOperand(1);
16857
16858   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16860       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16861         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16862                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16863         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16864                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16865       }
16866   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16868       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16869         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16870                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16871         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16872                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16873       }
16874   return SDValue();
16875 }
16876
16877 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
16878 // as "sbb reg,reg", since it can be extended without zext and produces 
16879 // an all-ones bit which is more useful than 0/1 in some cases.
16880 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16881   return DAG.getNode(ISD::AND, DL, MVT::i8,
16882                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16883                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16884                      DAG.getConstant(1, MVT::i8));
16885 }
16886
16887 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16888 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16889                                    TargetLowering::DAGCombinerInfo &DCI,
16890                                    const X86Subtarget *Subtarget) {
16891   DebugLoc DL = N->getDebugLoc();
16892   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16893   SDValue EFLAGS = N->getOperand(1);
16894
16895   if (CC == X86::COND_A) {
16896     // Try to convert COND_A into COND_B in an attempt to facilitate 
16897     // materializing "setb reg".
16898     //
16899     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16900     // cannot take an immediate as its first operand.
16901     //
16902     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
16903         EFLAGS.getValueType().isInteger() &&
16904         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
16905       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
16906                                    EFLAGS.getNode()->getVTList(),
16907                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
16908       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
16909       return MaterializeSETB(DL, NewEFLAGS, DAG);
16910     }
16911   }
16912
16913   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16914   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16915   // cases.
16916   if (CC == X86::COND_B)
16917     return MaterializeSETB(DL, EFLAGS, DAG);
16918
16919   SDValue Flags;
16920
16921   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16922   if (Flags.getNode()) {
16923     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16924     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16925   }
16926
16927   return SDValue();
16928 }
16929
16930 // Optimize branch condition evaluation.
16931 //
16932 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16933                                     TargetLowering::DAGCombinerInfo &DCI,
16934                                     const X86Subtarget *Subtarget) {
16935   DebugLoc DL = N->getDebugLoc();
16936   SDValue Chain = N->getOperand(0);
16937   SDValue Dest = N->getOperand(1);
16938   SDValue EFLAGS = N->getOperand(3);
16939   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16940
16941   SDValue Flags;
16942
16943   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16944   if (Flags.getNode()) {
16945     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16946     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16947                        Flags);
16948   }
16949
16950   return SDValue();
16951 }
16952
16953 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16954                                         const X86TargetLowering *XTLI) {
16955   SDValue Op0 = N->getOperand(0);
16956   EVT InVT = Op0->getValueType(0);
16957
16958   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16959   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16960     DebugLoc dl = N->getDebugLoc();
16961     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16962     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16963     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16964   }
16965
16966   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16967   // a 32-bit target where SSE doesn't support i64->FP operations.
16968   if (Op0.getOpcode() == ISD::LOAD) {
16969     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16970     EVT VT = Ld->getValueType(0);
16971     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16972         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16973         !XTLI->getSubtarget()->is64Bit() &&
16974         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16975       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16976                                           Ld->getChain(), Op0, DAG);
16977       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16978       return FILDChain;
16979     }
16980   }
16981   return SDValue();
16982 }
16983
16984 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16985 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16986                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16987   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16988   // the result is either zero or one (depending on the input carry bit).
16989   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16990   if (X86::isZeroNode(N->getOperand(0)) &&
16991       X86::isZeroNode(N->getOperand(1)) &&
16992       // We don't have a good way to replace an EFLAGS use, so only do this when
16993       // dead right now.
16994       SDValue(N, 1).use_empty()) {
16995     DebugLoc DL = N->getDebugLoc();
16996     EVT VT = N->getValueType(0);
16997     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16998     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16999                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17000                                            DAG.getConstant(X86::COND_B,MVT::i8),
17001                                            N->getOperand(2)),
17002                                DAG.getConstant(1, VT));
17003     return DCI.CombineTo(N, Res1, CarryOut);
17004   }
17005
17006   return SDValue();
17007 }
17008
17009 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17010 //      (add Y, (setne X, 0)) -> sbb -1, Y
17011 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17012 //      (sub (setne X, 0), Y) -> adc -1, Y
17013 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17014   DebugLoc DL = N->getDebugLoc();
17015
17016   // Look through ZExts.
17017   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17018   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17019     return SDValue();
17020
17021   SDValue SetCC = Ext.getOperand(0);
17022   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17023     return SDValue();
17024
17025   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17026   if (CC != X86::COND_E && CC != X86::COND_NE)
17027     return SDValue();
17028
17029   SDValue Cmp = SetCC.getOperand(1);
17030   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17031       !X86::isZeroNode(Cmp.getOperand(1)) ||
17032       !Cmp.getOperand(0).getValueType().isInteger())
17033     return SDValue();
17034
17035   SDValue CmpOp0 = Cmp.getOperand(0);
17036   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17037                                DAG.getConstant(1, CmpOp0.getValueType()));
17038
17039   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17040   if (CC == X86::COND_NE)
17041     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17042                        DL, OtherVal.getValueType(), OtherVal,
17043                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17044   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17045                      DL, OtherVal.getValueType(), OtherVal,
17046                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17047 }
17048
17049 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17050 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17051                                  const X86Subtarget *Subtarget) {
17052   EVT VT = N->getValueType(0);
17053   SDValue Op0 = N->getOperand(0);
17054   SDValue Op1 = N->getOperand(1);
17055
17056   // Try to synthesize horizontal adds from adds of shuffles.
17057   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17058        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17059       isHorizontalBinOp(Op0, Op1, true))
17060     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17061
17062   return OptimizeConditionalInDecrement(N, DAG);
17063 }
17064
17065 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17066                                  const X86Subtarget *Subtarget) {
17067   SDValue Op0 = N->getOperand(0);
17068   SDValue Op1 = N->getOperand(1);
17069
17070   // X86 can't encode an immediate LHS of a sub. See if we can push the
17071   // negation into a preceding instruction.
17072   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17073     // If the RHS of the sub is a XOR with one use and a constant, invert the
17074     // immediate. Then add one to the LHS of the sub so we can turn
17075     // X-Y -> X+~Y+1, saving one register.
17076     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17077         isa<ConstantSDNode>(Op1.getOperand(1))) {
17078       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17079       EVT VT = Op0.getValueType();
17080       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17081                                    Op1.getOperand(0),
17082                                    DAG.getConstant(~XorC, VT));
17083       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17084                          DAG.getConstant(C->getAPIntValue()+1, VT));
17085     }
17086   }
17087
17088   // Try to synthesize horizontal adds from adds of shuffles.
17089   EVT VT = N->getValueType(0);
17090   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17091        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17092       isHorizontalBinOp(Op0, Op1, true))
17093     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17094
17095   return OptimizeConditionalInDecrement(N, DAG);
17096 }
17097
17098 /// performVZEXTCombine - Performs build vector combines
17099 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17100                                         TargetLowering::DAGCombinerInfo &DCI,
17101                                         const X86Subtarget *Subtarget) {
17102   // (vzext (bitcast (vzext (x)) -> (vzext x)
17103   SDValue In = N->getOperand(0);
17104   while (In.getOpcode() == ISD::BITCAST)
17105     In = In.getOperand(0);
17106
17107   if (In.getOpcode() != X86ISD::VZEXT)
17108     return SDValue();
17109
17110   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17111 }
17112
17113 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17114                                              DAGCombinerInfo &DCI) const {
17115   SelectionDAG &DAG = DCI.DAG;
17116   switch (N->getOpcode()) {
17117   default: break;
17118   case ISD::EXTRACT_VECTOR_ELT:
17119     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17120   case ISD::VSELECT:
17121   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17122   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17123   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17124   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17125   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17126   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17127   case ISD::SHL:
17128   case ISD::SRA:
17129   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17130   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17131   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17132   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17133   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17134   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17135   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17136   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17137   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17138   case X86ISD::FXOR:
17139   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17140   case X86ISD::FMIN:
17141   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17142   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17143   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17144   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17145   case ISD::ANY_EXTEND:
17146   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17147   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17148   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17149   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17150   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17151   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17152   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17153   case X86ISD::SHUFP:       // Handle all target specific shuffles
17154   case X86ISD::PALIGN:
17155   case X86ISD::UNPCKH:
17156   case X86ISD::UNPCKL:
17157   case X86ISD::MOVHLPS:
17158   case X86ISD::MOVLHPS:
17159   case X86ISD::PSHUFD:
17160   case X86ISD::PSHUFHW:
17161   case X86ISD::PSHUFLW:
17162   case X86ISD::MOVSS:
17163   case X86ISD::MOVSD:
17164   case X86ISD::VPERMILP:
17165   case X86ISD::VPERM2X128:
17166   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17167   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17168   }
17169
17170   return SDValue();
17171 }
17172
17173 /// isTypeDesirableForOp - Return true if the target has native support for
17174 /// the specified value type and it is 'desirable' to use the type for the
17175 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17176 /// instruction encodings are longer and some i16 instructions are slow.
17177 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17178   if (!isTypeLegal(VT))
17179     return false;
17180   if (VT != MVT::i16)
17181     return true;
17182
17183   switch (Opc) {
17184   default:
17185     return true;
17186   case ISD::LOAD:
17187   case ISD::SIGN_EXTEND:
17188   case ISD::ZERO_EXTEND:
17189   case ISD::ANY_EXTEND:
17190   case ISD::SHL:
17191   case ISD::SRL:
17192   case ISD::SUB:
17193   case ISD::ADD:
17194   case ISD::MUL:
17195   case ISD::AND:
17196   case ISD::OR:
17197   case ISD::XOR:
17198     return false;
17199   }
17200 }
17201
17202 /// IsDesirableToPromoteOp - This method query the target whether it is
17203 /// beneficial for dag combiner to promote the specified node. If true, it
17204 /// should return the desired promotion type by reference.
17205 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17206   EVT VT = Op.getValueType();
17207   if (VT != MVT::i16)
17208     return false;
17209
17210   bool Promote = false;
17211   bool Commute = false;
17212   switch (Op.getOpcode()) {
17213   default: break;
17214   case ISD::LOAD: {
17215     LoadSDNode *LD = cast<LoadSDNode>(Op);
17216     // If the non-extending load has a single use and it's not live out, then it
17217     // might be folded.
17218     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17219                                                      Op.hasOneUse()*/) {
17220       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17221              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17222         // The only case where we'd want to promote LOAD (rather then it being
17223         // promoted as an operand is when it's only use is liveout.
17224         if (UI->getOpcode() != ISD::CopyToReg)
17225           return false;
17226       }
17227     }
17228     Promote = true;
17229     break;
17230   }
17231   case ISD::SIGN_EXTEND:
17232   case ISD::ZERO_EXTEND:
17233   case ISD::ANY_EXTEND:
17234     Promote = true;
17235     break;
17236   case ISD::SHL:
17237   case ISD::SRL: {
17238     SDValue N0 = Op.getOperand(0);
17239     // Look out for (store (shl (load), x)).
17240     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17241       return false;
17242     Promote = true;
17243     break;
17244   }
17245   case ISD::ADD:
17246   case ISD::MUL:
17247   case ISD::AND:
17248   case ISD::OR:
17249   case ISD::XOR:
17250     Commute = true;
17251     // fallthrough
17252   case ISD::SUB: {
17253     SDValue N0 = Op.getOperand(0);
17254     SDValue N1 = Op.getOperand(1);
17255     if (!Commute && MayFoldLoad(N1))
17256       return false;
17257     // Avoid disabling potential load folding opportunities.
17258     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17259       return false;
17260     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17261       return false;
17262     Promote = true;
17263   }
17264   }
17265
17266   PVT = MVT::i32;
17267   return Promote;
17268 }
17269
17270 //===----------------------------------------------------------------------===//
17271 //                           X86 Inline Assembly Support
17272 //===----------------------------------------------------------------------===//
17273
17274 namespace {
17275   // Helper to match a string separated by whitespace.
17276   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17277     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17278
17279     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17280       StringRef piece(*args[i]);
17281       if (!s.startswith(piece)) // Check if the piece matches.
17282         return false;
17283
17284       s = s.substr(piece.size());
17285       StringRef::size_type pos = s.find_first_not_of(" \t");
17286       if (pos == 0) // We matched a prefix.
17287         return false;
17288
17289       s = s.substr(pos);
17290     }
17291
17292     return s.empty();
17293   }
17294   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17295 }
17296
17297 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17298   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17299
17300   std::string AsmStr = IA->getAsmString();
17301
17302   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17303   if (!Ty || Ty->getBitWidth() % 16 != 0)
17304     return false;
17305
17306   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17307   SmallVector<StringRef, 4> AsmPieces;
17308   SplitString(AsmStr, AsmPieces, ";\n");
17309
17310   switch (AsmPieces.size()) {
17311   default: return false;
17312   case 1:
17313     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17314     // we will turn this bswap into something that will be lowered to logical
17315     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17316     // lower so don't worry about this.
17317     // bswap $0
17318     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17319         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17320         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17321         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17322         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17323         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17324       // No need to check constraints, nothing other than the equivalent of
17325       // "=r,0" would be valid here.
17326       return IntrinsicLowering::LowerToByteSwap(CI);
17327     }
17328
17329     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17330     if (CI->getType()->isIntegerTy(16) &&
17331         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17332         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17333          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17334       AsmPieces.clear();
17335       const std::string &ConstraintsStr = IA->getConstraintString();
17336       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17337       std::sort(AsmPieces.begin(), AsmPieces.end());
17338       if (AsmPieces.size() == 4 &&
17339           AsmPieces[0] == "~{cc}" &&
17340           AsmPieces[1] == "~{dirflag}" &&
17341           AsmPieces[2] == "~{flags}" &&
17342           AsmPieces[3] == "~{fpsr}")
17343       return IntrinsicLowering::LowerToByteSwap(CI);
17344     }
17345     break;
17346   case 3:
17347     if (CI->getType()->isIntegerTy(32) &&
17348         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17349         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17350         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17351         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17352       AsmPieces.clear();
17353       const std::string &ConstraintsStr = IA->getConstraintString();
17354       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17355       std::sort(AsmPieces.begin(), AsmPieces.end());
17356       if (AsmPieces.size() == 4 &&
17357           AsmPieces[0] == "~{cc}" &&
17358           AsmPieces[1] == "~{dirflag}" &&
17359           AsmPieces[2] == "~{flags}" &&
17360           AsmPieces[3] == "~{fpsr}")
17361         return IntrinsicLowering::LowerToByteSwap(CI);
17362     }
17363
17364     if (CI->getType()->isIntegerTy(64)) {
17365       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17366       if (Constraints.size() >= 2 &&
17367           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17368           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17369         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17370         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17371             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17372             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17373           return IntrinsicLowering::LowerToByteSwap(CI);
17374       }
17375     }
17376     break;
17377   }
17378   return false;
17379 }
17380
17381
17382
17383 /// getConstraintType - Given a constraint letter, return the type of
17384 /// constraint it is for this target.
17385 X86TargetLowering::ConstraintType
17386 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17387   if (Constraint.size() == 1) {
17388     switch (Constraint[0]) {
17389     case 'R':
17390     case 'q':
17391     case 'Q':
17392     case 'f':
17393     case 't':
17394     case 'u':
17395     case 'y':
17396     case 'x':
17397     case 'Y':
17398     case 'l':
17399       return C_RegisterClass;
17400     case 'a':
17401     case 'b':
17402     case 'c':
17403     case 'd':
17404     case 'S':
17405     case 'D':
17406     case 'A':
17407       return C_Register;
17408     case 'I':
17409     case 'J':
17410     case 'K':
17411     case 'L':
17412     case 'M':
17413     case 'N':
17414     case 'G':
17415     case 'C':
17416     case 'e':
17417     case 'Z':
17418       return C_Other;
17419     default:
17420       break;
17421     }
17422   }
17423   return TargetLowering::getConstraintType(Constraint);
17424 }
17425
17426 /// Examine constraint type and operand type and determine a weight value.
17427 /// This object must already have been set up with the operand type
17428 /// and the current alternative constraint selected.
17429 TargetLowering::ConstraintWeight
17430   X86TargetLowering::getSingleConstraintMatchWeight(
17431     AsmOperandInfo &info, const char *constraint) const {
17432   ConstraintWeight weight = CW_Invalid;
17433   Value *CallOperandVal = info.CallOperandVal;
17434     // If we don't have a value, we can't do a match,
17435     // but allow it at the lowest weight.
17436   if (CallOperandVal == NULL)
17437     return CW_Default;
17438   Type *type = CallOperandVal->getType();
17439   // Look at the constraint type.
17440   switch (*constraint) {
17441   default:
17442     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17443   case 'R':
17444   case 'q':
17445   case 'Q':
17446   case 'a':
17447   case 'b':
17448   case 'c':
17449   case 'd':
17450   case 'S':
17451   case 'D':
17452   case 'A':
17453     if (CallOperandVal->getType()->isIntegerTy())
17454       weight = CW_SpecificReg;
17455     break;
17456   case 'f':
17457   case 't':
17458   case 'u':
17459       if (type->isFloatingPointTy())
17460         weight = CW_SpecificReg;
17461       break;
17462   case 'y':
17463       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17464         weight = CW_SpecificReg;
17465       break;
17466   case 'x':
17467   case 'Y':
17468     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17469         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17470       weight = CW_Register;
17471     break;
17472   case 'I':
17473     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17474       if (C->getZExtValue() <= 31)
17475         weight = CW_Constant;
17476     }
17477     break;
17478   case 'J':
17479     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17480       if (C->getZExtValue() <= 63)
17481         weight = CW_Constant;
17482     }
17483     break;
17484   case 'K':
17485     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17486       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17487         weight = CW_Constant;
17488     }
17489     break;
17490   case 'L':
17491     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17492       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17493         weight = CW_Constant;
17494     }
17495     break;
17496   case 'M':
17497     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17498       if (C->getZExtValue() <= 3)
17499         weight = CW_Constant;
17500     }
17501     break;
17502   case 'N':
17503     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17504       if (C->getZExtValue() <= 0xff)
17505         weight = CW_Constant;
17506     }
17507     break;
17508   case 'G':
17509   case 'C':
17510     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17511       weight = CW_Constant;
17512     }
17513     break;
17514   case 'e':
17515     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17516       if ((C->getSExtValue() >= -0x80000000LL) &&
17517           (C->getSExtValue() <= 0x7fffffffLL))
17518         weight = CW_Constant;
17519     }
17520     break;
17521   case 'Z':
17522     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17523       if (C->getZExtValue() <= 0xffffffff)
17524         weight = CW_Constant;
17525     }
17526     break;
17527   }
17528   return weight;
17529 }
17530
17531 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17532 /// with another that has more specific requirements based on the type of the
17533 /// corresponding operand.
17534 const char *X86TargetLowering::
17535 LowerXConstraint(EVT ConstraintVT) const {
17536   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17537   // 'f' like normal targets.
17538   if (ConstraintVT.isFloatingPoint()) {
17539     if (Subtarget->hasSSE2())
17540       return "Y";
17541     if (Subtarget->hasSSE1())
17542       return "x";
17543   }
17544
17545   return TargetLowering::LowerXConstraint(ConstraintVT);
17546 }
17547
17548 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17549 /// vector.  If it is invalid, don't add anything to Ops.
17550 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17551                                                      std::string &Constraint,
17552                                                      std::vector<SDValue>&Ops,
17553                                                      SelectionDAG &DAG) const {
17554   SDValue Result(0, 0);
17555
17556   // Only support length 1 constraints for now.
17557   if (Constraint.length() > 1) return;
17558
17559   char ConstraintLetter = Constraint[0];
17560   switch (ConstraintLetter) {
17561   default: break;
17562   case 'I':
17563     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17564       if (C->getZExtValue() <= 31) {
17565         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17566         break;
17567       }
17568     }
17569     return;
17570   case 'J':
17571     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17572       if (C->getZExtValue() <= 63) {
17573         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17574         break;
17575       }
17576     }
17577     return;
17578   case 'K':
17579     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17580       if (isInt<8>(C->getSExtValue())) {
17581         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17582         break;
17583       }
17584     }
17585     return;
17586   case 'N':
17587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17588       if (C->getZExtValue() <= 255) {
17589         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17590         break;
17591       }
17592     }
17593     return;
17594   case 'e': {
17595     // 32-bit signed value
17596     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17597       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17598                                            C->getSExtValue())) {
17599         // Widen to 64 bits here to get it sign extended.
17600         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17601         break;
17602       }
17603     // FIXME gcc accepts some relocatable values here too, but only in certain
17604     // memory models; it's complicated.
17605     }
17606     return;
17607   }
17608   case 'Z': {
17609     // 32-bit unsigned value
17610     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17611       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17612                                            C->getZExtValue())) {
17613         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17614         break;
17615       }
17616     }
17617     // FIXME gcc accepts some relocatable values here too, but only in certain
17618     // memory models; it's complicated.
17619     return;
17620   }
17621   case 'i': {
17622     // Literal immediates are always ok.
17623     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17624       // Widen to 64 bits here to get it sign extended.
17625       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17626       break;
17627     }
17628
17629     // In any sort of PIC mode addresses need to be computed at runtime by
17630     // adding in a register or some sort of table lookup.  These can't
17631     // be used as immediates.
17632     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17633       return;
17634
17635     // If we are in non-pic codegen mode, we allow the address of a global (with
17636     // an optional displacement) to be used with 'i'.
17637     GlobalAddressSDNode *GA = 0;
17638     int64_t Offset = 0;
17639
17640     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17641     while (1) {
17642       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17643         Offset += GA->getOffset();
17644         break;
17645       } else if (Op.getOpcode() == ISD::ADD) {
17646         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17647           Offset += C->getZExtValue();
17648           Op = Op.getOperand(0);
17649           continue;
17650         }
17651       } else if (Op.getOpcode() == ISD::SUB) {
17652         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17653           Offset += -C->getZExtValue();
17654           Op = Op.getOperand(0);
17655           continue;
17656         }
17657       }
17658
17659       // Otherwise, this isn't something we can handle, reject it.
17660       return;
17661     }
17662
17663     const GlobalValue *GV = GA->getGlobal();
17664     // If we require an extra load to get this address, as in PIC mode, we
17665     // can't accept it.
17666     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17667                                                         getTargetMachine())))
17668       return;
17669
17670     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17671                                         GA->getValueType(0), Offset);
17672     break;
17673   }
17674   }
17675
17676   if (Result.getNode()) {
17677     Ops.push_back(Result);
17678     return;
17679   }
17680   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17681 }
17682
17683 std::pair<unsigned, const TargetRegisterClass*>
17684 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17685                                                 EVT VT) const {
17686   // First, see if this is a constraint that directly corresponds to an LLVM
17687   // register class.
17688   if (Constraint.size() == 1) {
17689     // GCC Constraint Letters
17690     switch (Constraint[0]) {
17691     default: break;
17692       // TODO: Slight differences here in allocation order and leaving
17693       // RIP in the class. Do they matter any more here than they do
17694       // in the normal allocation?
17695     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17696       if (Subtarget->is64Bit()) {
17697         if (VT == MVT::i32 || VT == MVT::f32)
17698           return std::make_pair(0U, &X86::GR32RegClass);
17699         if (VT == MVT::i16)
17700           return std::make_pair(0U, &X86::GR16RegClass);
17701         if (VT == MVT::i8 || VT == MVT::i1)
17702           return std::make_pair(0U, &X86::GR8RegClass);
17703         if (VT == MVT::i64 || VT == MVT::f64)
17704           return std::make_pair(0U, &X86::GR64RegClass);
17705         break;
17706       }
17707       // 32-bit fallthrough
17708     case 'Q':   // Q_REGS
17709       if (VT == MVT::i32 || VT == MVT::f32)
17710         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17711       if (VT == MVT::i16)
17712         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17713       if (VT == MVT::i8 || VT == MVT::i1)
17714         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17715       if (VT == MVT::i64)
17716         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17717       break;
17718     case 'r':   // GENERAL_REGS
17719     case 'l':   // INDEX_REGS
17720       if (VT == MVT::i8 || VT == MVT::i1)
17721         return std::make_pair(0U, &X86::GR8RegClass);
17722       if (VT == MVT::i16)
17723         return std::make_pair(0U, &X86::GR16RegClass);
17724       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17725         return std::make_pair(0U, &X86::GR32RegClass);
17726       return std::make_pair(0U, &X86::GR64RegClass);
17727     case 'R':   // LEGACY_REGS
17728       if (VT == MVT::i8 || VT == MVT::i1)
17729         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17730       if (VT == MVT::i16)
17731         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17732       if (VT == MVT::i32 || !Subtarget->is64Bit())
17733         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17734       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17735     case 'f':  // FP Stack registers.
17736       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17737       // value to the correct fpstack register class.
17738       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17739         return std::make_pair(0U, &X86::RFP32RegClass);
17740       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17741         return std::make_pair(0U, &X86::RFP64RegClass);
17742       return std::make_pair(0U, &X86::RFP80RegClass);
17743     case 'y':   // MMX_REGS if MMX allowed.
17744       if (!Subtarget->hasMMX()) break;
17745       return std::make_pair(0U, &X86::VR64RegClass);
17746     case 'Y':   // SSE_REGS if SSE2 allowed
17747       if (!Subtarget->hasSSE2()) break;
17748       // FALL THROUGH.
17749     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17750       if (!Subtarget->hasSSE1()) break;
17751
17752       switch (VT.getSimpleVT().SimpleTy) {
17753       default: break;
17754       // Scalar SSE types.
17755       case MVT::f32:
17756       case MVT::i32:
17757         return std::make_pair(0U, &X86::FR32RegClass);
17758       case MVT::f64:
17759       case MVT::i64:
17760         return std::make_pair(0U, &X86::FR64RegClass);
17761       // Vector types.
17762       case MVT::v16i8:
17763       case MVT::v8i16:
17764       case MVT::v4i32:
17765       case MVT::v2i64:
17766       case MVT::v4f32:
17767       case MVT::v2f64:
17768         return std::make_pair(0U, &X86::VR128RegClass);
17769       // AVX types.
17770       case MVT::v32i8:
17771       case MVT::v16i16:
17772       case MVT::v8i32:
17773       case MVT::v4i64:
17774       case MVT::v8f32:
17775       case MVT::v4f64:
17776         return std::make_pair(0U, &X86::VR256RegClass);
17777       }
17778       break;
17779     }
17780   }
17781
17782   // Use the default implementation in TargetLowering to convert the register
17783   // constraint into a member of a register class.
17784   std::pair<unsigned, const TargetRegisterClass*> Res;
17785   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17786
17787   // Not found as a standard register?
17788   if (Res.second == 0) {
17789     // Map st(0) -> st(7) -> ST0
17790     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17791         tolower(Constraint[1]) == 's' &&
17792         tolower(Constraint[2]) == 't' &&
17793         Constraint[3] == '(' &&
17794         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17795         Constraint[5] == ')' &&
17796         Constraint[6] == '}') {
17797
17798       Res.first = X86::ST0+Constraint[4]-'0';
17799       Res.second = &X86::RFP80RegClass;
17800       return Res;
17801     }
17802
17803     // GCC allows "st(0)" to be called just plain "st".
17804     if (StringRef("{st}").equals_lower(Constraint)) {
17805       Res.first = X86::ST0;
17806       Res.second = &X86::RFP80RegClass;
17807       return Res;
17808     }
17809
17810     // flags -> EFLAGS
17811     if (StringRef("{flags}").equals_lower(Constraint)) {
17812       Res.first = X86::EFLAGS;
17813       Res.second = &X86::CCRRegClass;
17814       return Res;
17815     }
17816
17817     // 'A' means EAX + EDX.
17818     if (Constraint == "A") {
17819       Res.first = X86::EAX;
17820       Res.second = &X86::GR32_ADRegClass;
17821       return Res;
17822     }
17823     return Res;
17824   }
17825
17826   // Otherwise, check to see if this is a register class of the wrong value
17827   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17828   // turn into {ax},{dx}.
17829   if (Res.second->hasType(VT))
17830     return Res;   // Correct type already, nothing to do.
17831
17832   // All of the single-register GCC register classes map their values onto
17833   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17834   // really want an 8-bit or 32-bit register, map to the appropriate register
17835   // class and return the appropriate register.
17836   if (Res.second == &X86::GR16RegClass) {
17837     if (VT == MVT::i8) {
17838       unsigned DestReg = 0;
17839       switch (Res.first) {
17840       default: break;
17841       case X86::AX: DestReg = X86::AL; break;
17842       case X86::DX: DestReg = X86::DL; break;
17843       case X86::CX: DestReg = X86::CL; break;
17844       case X86::BX: DestReg = X86::BL; break;
17845       }
17846       if (DestReg) {
17847         Res.first = DestReg;
17848         Res.second = &X86::GR8RegClass;
17849       }
17850     } else if (VT == MVT::i32) {
17851       unsigned DestReg = 0;
17852       switch (Res.first) {
17853       default: break;
17854       case X86::AX: DestReg = X86::EAX; break;
17855       case X86::DX: DestReg = X86::EDX; break;
17856       case X86::CX: DestReg = X86::ECX; break;
17857       case X86::BX: DestReg = X86::EBX; break;
17858       case X86::SI: DestReg = X86::ESI; break;
17859       case X86::DI: DestReg = X86::EDI; break;
17860       case X86::BP: DestReg = X86::EBP; break;
17861       case X86::SP: DestReg = X86::ESP; break;
17862       }
17863       if (DestReg) {
17864         Res.first = DestReg;
17865         Res.second = &X86::GR32RegClass;
17866       }
17867     } else if (VT == MVT::i64) {
17868       unsigned DestReg = 0;
17869       switch (Res.first) {
17870       default: break;
17871       case X86::AX: DestReg = X86::RAX; break;
17872       case X86::DX: DestReg = X86::RDX; break;
17873       case X86::CX: DestReg = X86::RCX; break;
17874       case X86::BX: DestReg = X86::RBX; break;
17875       case X86::SI: DestReg = X86::RSI; break;
17876       case X86::DI: DestReg = X86::RDI; break;
17877       case X86::BP: DestReg = X86::RBP; break;
17878       case X86::SP: DestReg = X86::RSP; break;
17879       }
17880       if (DestReg) {
17881         Res.first = DestReg;
17882         Res.second = &X86::GR64RegClass;
17883       }
17884     }
17885   } else if (Res.second == &X86::FR32RegClass ||
17886              Res.second == &X86::FR64RegClass ||
17887              Res.second == &X86::VR128RegClass) {
17888     // Handle references to XMM physical registers that got mapped into the
17889     // wrong class.  This can happen with constraints like {xmm0} where the
17890     // target independent register mapper will just pick the first match it can
17891     // find, ignoring the required type.
17892
17893     if (VT == MVT::f32 || VT == MVT::i32)
17894       Res.second = &X86::FR32RegClass;
17895     else if (VT == MVT::f64 || VT == MVT::i64)
17896       Res.second = &X86::FR64RegClass;
17897     else if (X86::VR128RegClass.hasType(VT))
17898       Res.second = &X86::VR128RegClass;
17899     else if (X86::VR256RegClass.hasType(VT))
17900       Res.second = &X86::VR256RegClass;
17901   }
17902
17903   return Res;
17904 }
17905
17906 //===----------------------------------------------------------------------===//
17907 //
17908 // X86 cost model.
17909 //
17910 //===----------------------------------------------------------------------===//
17911
17912 struct X86CostTblEntry {
17913   int ISD;
17914   MVT Type;
17915   unsigned Cost;
17916 };
17917
17918 static int
17919 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
17920   for (unsigned int i = 0; i < len; ++i)
17921     if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
17922       return i;
17923
17924   // Could not find an entry.
17925   return -1;
17926 }
17927
17928 struct X86TypeConversionCostTblEntry {
17929   int ISD;
17930   MVT Dst;
17931   MVT Src;
17932   unsigned Cost;
17933 };
17934
17935 static int
17936 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
17937                    int ISD, MVT Dst, MVT Src) {
17938   for (unsigned int i = 0; i < len; ++i)
17939     if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
17940       return i;
17941
17942   // Could not find an entry.
17943   return -1;
17944 }
17945
17946 ScalarTargetTransformInfo::PopcntHwSupport
17947 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
17948   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
17949   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17950
17951   // TODO: Currently the __builtin_popcount() implementation using SSE3
17952   //   instructions is inefficient. Once the problem is fixed, we should
17953   //   call ST.hasSSE3() instead of ST.hasSSE4().
17954   return ST.hasSSE41() ? Fast : None;
17955 }
17956
17957 unsigned
17958 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
17959                                                      Type *Ty) const {
17960   // Legalize the type.
17961   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
17962
17963   int ISD = InstructionOpcodeToISD(Opcode);
17964   assert(ISD && "Invalid opcode");
17965
17966   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17967
17968   static const X86CostTblEntry AVX1CostTable[] = {
17969     // We don't have to scalarize unsupported ops. We can issue two half-sized
17970     // operations and we only need to extract the upper YMM half.
17971     // Two ops + 1 extract + 1 insert = 4.
17972     { ISD::MUL,     MVT::v8i32,    4 },
17973     { ISD::SUB,     MVT::v8i32,    4 },
17974     { ISD::ADD,     MVT::v8i32,    4 },
17975     { ISD::MUL,     MVT::v4i64,    4 },
17976     { ISD::SUB,     MVT::v4i64,    4 },
17977     { ISD::ADD,     MVT::v4i64,    4 },
17978     };
17979
17980   // Look for AVX1 lowering tricks.
17981   if (ST.hasAVX()) {
17982     int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
17983                           LT.second);
17984     if (Idx != -1)
17985       return LT.first * AVX1CostTable[Idx].Cost;
17986   }
17987   // Fallback to the default implementation.
17988   return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
17989 }
17990
17991 unsigned
17992 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
17993                                               unsigned Alignment,
17994                                               unsigned AddressSpace) const {
17995   // Legalize the type.
17996   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
17997   assert(Opcode == Instruction::Load || Opcode == Instruction::Store &&
17998          "Invalid Opcode");
17999
18000   const X86Subtarget &ST =
18001   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18002
18003   // Each load/store unit costs 1.
18004   unsigned Cost = LT.first * 1;
18005
18006   // On Sandybridge 256bit load/stores are double pumped
18007   // (but not on Haswell).
18008   if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
18009     Cost*=2;
18010
18011   return Cost;
18012 }
18013
18014 unsigned
18015 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
18016                                                  unsigned Index) const {
18017   assert(Val->isVectorTy() && "This must be a vector type");
18018
18019   if (Index != -1U) {
18020     // Legalize the type.
18021     std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
18022
18023     // This type is legalized to a scalar type.
18024     if (!LT.second.isVector())
18025       return 0;
18026
18027     // The type may be split. Normalize the index to the new type.
18028     unsigned Width = LT.second.getVectorNumElements();
18029     Index = Index % Width;
18030
18031     // Floating point scalars are already located in index #0.
18032     if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18033       return 0;
18034   }
18035
18036   return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18037 }
18038
18039 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18040                                                           Type *ValTy,
18041                                                           Type *CondTy) const {
18042   // Legalize the type.
18043   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18044
18045   MVT MTy = LT.second;
18046
18047   int ISD = InstructionOpcodeToISD(Opcode);
18048   assert(ISD && "Invalid opcode");
18049
18050   const X86Subtarget &ST =
18051   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18052
18053   static const X86CostTblEntry SSE42CostTbl[] = {
18054     { ISD::SETCC,   MVT::v2f64,   1 },
18055     { ISD::SETCC,   MVT::v4f32,   1 },
18056     { ISD::SETCC,   MVT::v2i64,   1 },
18057     { ISD::SETCC,   MVT::v4i32,   1 },
18058     { ISD::SETCC,   MVT::v8i16,   1 },
18059     { ISD::SETCC,   MVT::v16i8,   1 },
18060   };
18061
18062   static const X86CostTblEntry AVX1CostTbl[] = {
18063     { ISD::SETCC,   MVT::v4f64,   1 },
18064     { ISD::SETCC,   MVT::v8f32,   1 },
18065     // AVX1 does not support 8-wide integer compare.
18066     { ISD::SETCC,   MVT::v4i64,   4 },
18067     { ISD::SETCC,   MVT::v8i32,   4 },
18068     { ISD::SETCC,   MVT::v16i16,  4 },
18069     { ISD::SETCC,   MVT::v32i8,   4 },
18070   };
18071
18072   static const X86CostTblEntry AVX2CostTbl[] = {
18073     { ISD::SETCC,   MVT::v4i64,   1 },
18074     { ISD::SETCC,   MVT::v8i32,   1 },
18075     { ISD::SETCC,   MVT::v16i16,  1 },
18076     { ISD::SETCC,   MVT::v32i8,   1 },
18077   };
18078
18079   if (ST.hasAVX2()) {
18080     int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18081     if (Idx != -1)
18082       return LT.first * AVX2CostTbl[Idx].Cost;
18083   }
18084
18085   if (ST.hasAVX()) {
18086     int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18087     if (Idx != -1)
18088       return LT.first * AVX1CostTbl[Idx].Cost;
18089   }
18090
18091   if (ST.hasSSE42()) {
18092     int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18093     if (Idx != -1)
18094       return LT.first * SSE42CostTbl[Idx].Cost;
18095   }
18096
18097   return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18098 }
18099
18100 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18101                                                         Type *Dst,
18102                                                         Type *Src) const {
18103   int ISD = InstructionOpcodeToISD(Opcode);
18104   assert(ISD && "Invalid opcode");
18105
18106   EVT SrcTy = TLI->getValueType(Src);
18107   EVT DstTy = TLI->getValueType(Dst);
18108
18109   if (!SrcTy.isSimple() || !DstTy.isSimple())
18110     return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18111
18112   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18113
18114   static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18115     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18116     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18117     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18118     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18119     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 1 },
18120     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32, 1 },
18121     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18122     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18123     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18124     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18125     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 1 },
18126     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
18127     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1,  6 },
18128     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1,  9 },
18129     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64, 3 },
18130   };
18131
18132   if (ST.hasAVX()) {
18133     int Idx = FindInConvertTable(AVXConversionTbl,
18134                                  array_lengthof(AVXConversionTbl),
18135                                  ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18136     if (Idx != -1)
18137       return AVXConversionTbl[Idx].Cost;
18138   }
18139
18140   return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18141 }
18142