VCVTSS2SD requires a strict alignment. Thanks Elena.
[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   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1243   // handle type legalization for these operations here.
1244   //
1245   // FIXME: We really should do custom legalization for addition and
1246   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1247   // than generic legalization for 64-bit multiplication-with-overflow, though.
1248   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1249     // Add/Sub/Mul with overflow operations are custom lowered.
1250     MVT VT = IntVTs[i];
1251     setOperationAction(ISD::SADDO, VT, Custom);
1252     setOperationAction(ISD::UADDO, VT, Custom);
1253     setOperationAction(ISD::SSUBO, VT, Custom);
1254     setOperationAction(ISD::USUBO, VT, Custom);
1255     setOperationAction(ISD::SMULO, VT, Custom);
1256     setOperationAction(ISD::UMULO, VT, Custom);
1257   }
1258
1259   // There are no 8-bit 3-address imul/mul instructions
1260   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1261   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1262
1263   if (!Subtarget->is64Bit()) {
1264     // These libcalls are not available in 32-bit.
1265     setLibcallName(RTLIB::SHL_I128, 0);
1266     setLibcallName(RTLIB::SRL_I128, 0);
1267     setLibcallName(RTLIB::SRA_I128, 0);
1268   }
1269
1270   // We have target-specific dag combine patterns for the following nodes:
1271   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1272   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1273   setTargetDAGCombine(ISD::VSELECT);
1274   setTargetDAGCombine(ISD::SELECT);
1275   setTargetDAGCombine(ISD::SHL);
1276   setTargetDAGCombine(ISD::SRA);
1277   setTargetDAGCombine(ISD::SRL);
1278   setTargetDAGCombine(ISD::OR);
1279   setTargetDAGCombine(ISD::AND);
1280   setTargetDAGCombine(ISD::ADD);
1281   setTargetDAGCombine(ISD::FADD);
1282   setTargetDAGCombine(ISD::FSUB);
1283   setTargetDAGCombine(ISD::FMA);
1284   setTargetDAGCombine(ISD::SUB);
1285   setTargetDAGCombine(ISD::LOAD);
1286   setTargetDAGCombine(ISD::STORE);
1287   setTargetDAGCombine(ISD::ZERO_EXTEND);
1288   setTargetDAGCombine(ISD::ANY_EXTEND);
1289   setTargetDAGCombine(ISD::SIGN_EXTEND);
1290   setTargetDAGCombine(ISD::TRUNCATE);
1291   setTargetDAGCombine(ISD::SINT_TO_FP);
1292   setTargetDAGCombine(ISD::SETCC);
1293   if (Subtarget->is64Bit())
1294     setTargetDAGCombine(ISD::MUL);
1295   setTargetDAGCombine(ISD::XOR);
1296
1297   computeRegisterProperties();
1298
1299   // On Darwin, -Os means optimize for size without hurting performance,
1300   // do not reduce the limit.
1301   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1302   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1303   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1304   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1305   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1306   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1307   setPrefLoopAlignment(4); // 2^4 bytes.
1308   benefitFromCodePlacementOpt = true;
1309
1310   // Predictable cmov don't hurt on atom because it's in-order.
1311   predictableSelectIsExpensive = !Subtarget->isAtom();
1312
1313   setPrefFunctionAlignment(4); // 2^4 bytes.
1314 }
1315
1316 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1317   if (!VT.isVector()) return MVT::i8;
1318   return VT.changeVectorElementTypeToInteger();
1319 }
1320
1321 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1322 /// the desired ByVal argument alignment.
1323 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1324   if (MaxAlign == 16)
1325     return;
1326   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1327     if (VTy->getBitWidth() == 128)
1328       MaxAlign = 16;
1329   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1330     unsigned EltAlign = 0;
1331     getMaxByValAlign(ATy->getElementType(), EltAlign);
1332     if (EltAlign > MaxAlign)
1333       MaxAlign = EltAlign;
1334   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1335     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1336       unsigned EltAlign = 0;
1337       getMaxByValAlign(STy->getElementType(i), EltAlign);
1338       if (EltAlign > MaxAlign)
1339         MaxAlign = EltAlign;
1340       if (MaxAlign == 16)
1341         break;
1342     }
1343   }
1344 }
1345
1346 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1347 /// function arguments in the caller parameter area. For X86, aggregates
1348 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1349 /// are at 4-byte boundaries.
1350 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1351   if (Subtarget->is64Bit()) {
1352     // Max of 8 and alignment of type.
1353     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1354     if (TyAlign > 8)
1355       return TyAlign;
1356     return 8;
1357   }
1358
1359   unsigned Align = 4;
1360   if (Subtarget->hasSSE1())
1361     getMaxByValAlign(Ty, Align);
1362   return Align;
1363 }
1364
1365 /// getOptimalMemOpType - Returns the target specific optimal type for load
1366 /// and store operations as a result of memset, memcpy, and memmove
1367 /// lowering. If DstAlign is zero that means it's safe to destination
1368 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1369 /// means there isn't a need to check it against alignment requirement,
1370 /// probably because the source does not need to be loaded. If 'IsMemset' is
1371 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1372 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1373 /// source is constant so it does not need to be loaded.
1374 /// It returns EVT::Other if the type should be determined using generic
1375 /// target-independent logic.
1376 EVT
1377 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1378                                        unsigned DstAlign, unsigned SrcAlign,
1379                                        bool IsMemset, bool ZeroMemset,
1380                                        bool MemcpyStrSrc,
1381                                        MachineFunction &MF) const {
1382   const Function *F = MF.getFunction();
1383   if ((!IsMemset || ZeroMemset) &&
1384       !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1385     if (Size >= 16 &&
1386         (Subtarget->isUnalignedMemAccessFast() ||
1387          ((DstAlign == 0 || DstAlign >= 16) &&
1388           (SrcAlign == 0 || SrcAlign >= 16)))) {
1389       if (Size >= 32) {
1390         if (Subtarget->hasInt256())
1391           return MVT::v8i32;
1392         if (Subtarget->hasFp256())
1393           return MVT::v8f32;
1394       }
1395       if (Subtarget->hasSSE2())
1396         return MVT::v4i32;
1397       if (Subtarget->hasSSE1())
1398         return MVT::v4f32;
1399     } else if (!MemcpyStrSrc && Size >= 8 &&
1400                !Subtarget->is64Bit() &&
1401                Subtarget->hasSSE2()) {
1402       // Do not use f64 to lower memcpy if source is string constant. It's
1403       // better to use i32 to avoid the loads.
1404       return MVT::f64;
1405     }
1406   }
1407   if (Subtarget->is64Bit() && Size >= 8)
1408     return MVT::i64;
1409   return MVT::i32;
1410 }
1411
1412 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1413   if (VT == MVT::f32)
1414     return X86ScalarSSEf32;
1415   else if (VT == MVT::f64)
1416     return X86ScalarSSEf64;
1417   return true;
1418 }
1419
1420 bool
1421 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1422   if (Fast)
1423     *Fast = Subtarget->isUnalignedMemAccessFast();
1424   return true;
1425 }
1426
1427 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1428 /// current function.  The returned value is a member of the
1429 /// MachineJumpTableInfo::JTEntryKind enum.
1430 unsigned X86TargetLowering::getJumpTableEncoding() const {
1431   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1432   // symbol.
1433   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1434       Subtarget->isPICStyleGOT())
1435     return MachineJumpTableInfo::EK_Custom32;
1436
1437   // Otherwise, use the normal jump table encoding heuristics.
1438   return TargetLowering::getJumpTableEncoding();
1439 }
1440
1441 const MCExpr *
1442 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1443                                              const MachineBasicBlock *MBB,
1444                                              unsigned uid,MCContext &Ctx) const{
1445   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1446          Subtarget->isPICStyleGOT());
1447   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1448   // entries.
1449   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1450                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1451 }
1452
1453 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1454 /// jumptable.
1455 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1456                                                     SelectionDAG &DAG) const {
1457   if (!Subtarget->is64Bit())
1458     // This doesn't have DebugLoc associated with it, but is not really the
1459     // same as a Register.
1460     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1461   return Table;
1462 }
1463
1464 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1465 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1466 /// MCExpr.
1467 const MCExpr *X86TargetLowering::
1468 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1469                              MCContext &Ctx) const {
1470   // X86-64 uses RIP relative addressing based on the jump table label.
1471   if (Subtarget->isPICStyleRIPRel())
1472     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1473
1474   // Otherwise, the reference is relative to the PIC base.
1475   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1476 }
1477
1478 // FIXME: Why this routine is here? Move to RegInfo!
1479 std::pair<const TargetRegisterClass*, uint8_t>
1480 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1481   const TargetRegisterClass *RRC = 0;
1482   uint8_t Cost = 1;
1483   switch (VT.SimpleTy) {
1484   default:
1485     return TargetLowering::findRepresentativeClass(VT);
1486   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1487     RRC = Subtarget->is64Bit() ?
1488       (const TargetRegisterClass*)&X86::GR64RegClass :
1489       (const TargetRegisterClass*)&X86::GR32RegClass;
1490     break;
1491   case MVT::x86mmx:
1492     RRC = &X86::VR64RegClass;
1493     break;
1494   case MVT::f32: case MVT::f64:
1495   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1496   case MVT::v4f32: case MVT::v2f64:
1497   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1498   case MVT::v4f64:
1499     RRC = &X86::VR128RegClass;
1500     break;
1501   }
1502   return std::make_pair(RRC, Cost);
1503 }
1504
1505 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1506                                                unsigned &Offset) const {
1507   if (!Subtarget->isTargetLinux())
1508     return false;
1509
1510   if (Subtarget->is64Bit()) {
1511     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1512     Offset = 0x28;
1513     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1514       AddressSpace = 256;
1515     else
1516       AddressSpace = 257;
1517   } else {
1518     // %gs:0x14 on i386
1519     Offset = 0x14;
1520     AddressSpace = 256;
1521   }
1522   return true;
1523 }
1524
1525 //===----------------------------------------------------------------------===//
1526 //               Return Value Calling Convention Implementation
1527 //===----------------------------------------------------------------------===//
1528
1529 #include "X86GenCallingConv.inc"
1530
1531 bool
1532 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1533                                   MachineFunction &MF, bool isVarArg,
1534                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1535                         LLVMContext &Context) const {
1536   SmallVector<CCValAssign, 16> RVLocs;
1537   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1538                  RVLocs, Context);
1539   return CCInfo.CheckReturn(Outs, RetCC_X86);
1540 }
1541
1542 SDValue
1543 X86TargetLowering::LowerReturn(SDValue Chain,
1544                                CallingConv::ID CallConv, bool isVarArg,
1545                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1546                                const SmallVectorImpl<SDValue> &OutVals,
1547                                DebugLoc dl, SelectionDAG &DAG) const {
1548   MachineFunction &MF = DAG.getMachineFunction();
1549   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1550
1551   SmallVector<CCValAssign, 16> RVLocs;
1552   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1553                  RVLocs, *DAG.getContext());
1554   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1555
1556   // Add the regs to the liveout set for the function.
1557   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1558   for (unsigned i = 0; i != RVLocs.size(); ++i)
1559     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1560       MRI.addLiveOut(RVLocs[i].getLocReg());
1561
1562   SDValue Flag;
1563
1564   SmallVector<SDValue, 6> RetOps;
1565   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1566   // Operand #1 = Bytes To Pop
1567   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1568                    MVT::i16));
1569
1570   // Copy the result values into the output registers.
1571   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1572     CCValAssign &VA = RVLocs[i];
1573     assert(VA.isRegLoc() && "Can only return in registers!");
1574     SDValue ValToCopy = OutVals[i];
1575     EVT ValVT = ValToCopy.getValueType();
1576
1577     // Promote values to the appropriate types
1578     if (VA.getLocInfo() == CCValAssign::SExt)
1579       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1580     else if (VA.getLocInfo() == CCValAssign::ZExt)
1581       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1582     else if (VA.getLocInfo() == CCValAssign::AExt)
1583       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1584     else if (VA.getLocInfo() == CCValAssign::BCvt)
1585       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1586
1587     // If this is x86-64, and we disabled SSE, we can't return FP values,
1588     // or SSE or MMX vectors.
1589     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1590          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1591           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1592       report_fatal_error("SSE register return with SSE disabled");
1593     }
1594     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1595     // llvm-gcc has never done it right and no one has noticed, so this
1596     // should be OK for now.
1597     if (ValVT == MVT::f64 &&
1598         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1599       report_fatal_error("SSE2 register return with SSE2 disabled");
1600
1601     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1602     // the RET instruction and handled by the FP Stackifier.
1603     if (VA.getLocReg() == X86::ST0 ||
1604         VA.getLocReg() == X86::ST1) {
1605       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1606       // change the value to the FP stack register class.
1607       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1608         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1609       RetOps.push_back(ValToCopy);
1610       // Don't emit a copytoreg.
1611       continue;
1612     }
1613
1614     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1615     // which is returned in RAX / RDX.
1616     if (Subtarget->is64Bit()) {
1617       if (ValVT == MVT::x86mmx) {
1618         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1619           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1620           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1621                                   ValToCopy);
1622           // If we don't have SSE2 available, convert to v4f32 so the generated
1623           // register is legal.
1624           if (!Subtarget->hasSSE2())
1625             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1626         }
1627       }
1628     }
1629
1630     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1631     Flag = Chain.getValue(1);
1632   }
1633
1634   // The x86-64 ABI for returning structs by value requires that we copy
1635   // the sret argument into %rax for the return. We saved the argument into
1636   // a virtual register in the entry block, so now we copy the value out
1637   // and into %rax.
1638   if (Subtarget->is64Bit() &&
1639       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1640     MachineFunction &MF = DAG.getMachineFunction();
1641     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1642     unsigned Reg = FuncInfo->getSRetReturnReg();
1643     assert(Reg &&
1644            "SRetReturnReg should have been set in LowerFormalArguments().");
1645     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1646
1647     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1648     Flag = Chain.getValue(1);
1649
1650     // RAX now acts like a return value.
1651     MRI.addLiveOut(X86::RAX);
1652   }
1653
1654   RetOps[0] = Chain;  // Update chain.
1655
1656   // Add the flag if we have it.
1657   if (Flag.getNode())
1658     RetOps.push_back(Flag);
1659
1660   return DAG.getNode(X86ISD::RET_FLAG, dl,
1661                      MVT::Other, &RetOps[0], RetOps.size());
1662 }
1663
1664 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1665   if (N->getNumValues() != 1)
1666     return false;
1667   if (!N->hasNUsesOfValue(1, 0))
1668     return false;
1669
1670   SDValue TCChain = Chain;
1671   SDNode *Copy = *N->use_begin();
1672   if (Copy->getOpcode() == ISD::CopyToReg) {
1673     // If the copy has a glue operand, we conservatively assume it isn't safe to
1674     // perform a tail call.
1675     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1676       return false;
1677     TCChain = Copy->getOperand(0);
1678   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1679     return false;
1680
1681   bool HasRet = false;
1682   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1683        UI != UE; ++UI) {
1684     if (UI->getOpcode() != X86ISD::RET_FLAG)
1685       return false;
1686     HasRet = true;
1687   }
1688
1689   if (!HasRet)
1690     return false;
1691
1692   Chain = TCChain;
1693   return true;
1694 }
1695
1696 MVT
1697 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1698                                             ISD::NodeType ExtendKind) const {
1699   MVT ReturnMVT;
1700   // TODO: Is this also valid on 32-bit?
1701   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1702     ReturnMVT = MVT::i8;
1703   else
1704     ReturnMVT = MVT::i32;
1705
1706   MVT MinVT = getRegisterType(ReturnMVT);
1707   return VT.bitsLT(MinVT) ? MinVT : VT;
1708 }
1709
1710 /// LowerCallResult - Lower the result values of a call into the
1711 /// appropriate copies out of appropriate physical registers.
1712 ///
1713 SDValue
1714 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1715                                    CallingConv::ID CallConv, bool isVarArg,
1716                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1717                                    DebugLoc dl, SelectionDAG &DAG,
1718                                    SmallVectorImpl<SDValue> &InVals) const {
1719
1720   // Assign locations to each value returned by this call.
1721   SmallVector<CCValAssign, 16> RVLocs;
1722   bool Is64Bit = Subtarget->is64Bit();
1723   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1724                  getTargetMachine(), RVLocs, *DAG.getContext());
1725   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1726
1727   // Copy all of the result registers out of their specified physreg.
1728   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1729     CCValAssign &VA = RVLocs[i];
1730     EVT CopyVT = VA.getValVT();
1731
1732     // If this is x86-64, and we disabled SSE, we can't return FP values
1733     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1734         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1735       report_fatal_error("SSE register return with SSE disabled");
1736     }
1737
1738     SDValue Val;
1739
1740     // If this is a call to a function that returns an fp value on the floating
1741     // point stack, we must guarantee the value is popped from the stack, so
1742     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1743     // if the return value is not used. We use the FpPOP_RETVAL instruction
1744     // instead.
1745     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1746       // If we prefer to use the value in xmm registers, copy it out as f80 and
1747       // use a truncate to move it from fp stack reg to xmm reg.
1748       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1749       SDValue Ops[] = { Chain, InFlag };
1750       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1751                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1752       Val = Chain.getValue(0);
1753
1754       // Round the f80 to the right size, which also moves it to the appropriate
1755       // xmm register.
1756       if (CopyVT != VA.getValVT())
1757         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1758                           // This truncation won't change the value.
1759                           DAG.getIntPtrConstant(1));
1760     } else {
1761       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1762                                  CopyVT, InFlag).getValue(1);
1763       Val = Chain.getValue(0);
1764     }
1765     InFlag = Chain.getValue(2);
1766     InVals.push_back(Val);
1767   }
1768
1769   return Chain;
1770 }
1771
1772 //===----------------------------------------------------------------------===//
1773 //                C & StdCall & Fast Calling Convention implementation
1774 //===----------------------------------------------------------------------===//
1775 //  StdCall calling convention seems to be standard for many Windows' API
1776 //  routines and around. It differs from C calling convention just a little:
1777 //  callee should clean up the stack, not caller. Symbols should be also
1778 //  decorated in some fancy way :) It doesn't support any vector arguments.
1779 //  For info on fast calling convention see Fast Calling Convention (tail call)
1780 //  implementation LowerX86_32FastCCCallTo.
1781
1782 /// CallIsStructReturn - Determines whether a call uses struct return
1783 /// semantics.
1784 enum StructReturnType {
1785   NotStructReturn,
1786   RegStructReturn,
1787   StackStructReturn
1788 };
1789 static StructReturnType
1790 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1791   if (Outs.empty())
1792     return NotStructReturn;
1793
1794   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1795   if (!Flags.isSRet())
1796     return NotStructReturn;
1797   if (Flags.isInReg())
1798     return RegStructReturn;
1799   return StackStructReturn;
1800 }
1801
1802 /// ArgsAreStructReturn - Determines whether a function uses struct
1803 /// return semantics.
1804 static StructReturnType
1805 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1806   if (Ins.empty())
1807     return NotStructReturn;
1808
1809   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1810   if (!Flags.isSRet())
1811     return NotStructReturn;
1812   if (Flags.isInReg())
1813     return RegStructReturn;
1814   return StackStructReturn;
1815 }
1816
1817 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1818 /// by "Src" to address "Dst" with size and alignment information specified by
1819 /// the specific parameter attribute. The copy will be passed as a byval
1820 /// function parameter.
1821 static SDValue
1822 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1823                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1824                           DebugLoc dl) {
1825   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1826
1827   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1828                        /*isVolatile*/false, /*AlwaysInline=*/true,
1829                        MachinePointerInfo(), MachinePointerInfo());
1830 }
1831
1832 /// IsTailCallConvention - Return true if the calling convention is one that
1833 /// supports tail call optimization.
1834 static bool IsTailCallConvention(CallingConv::ID CC) {
1835   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1836           CC == CallingConv::HiPE);
1837 }
1838
1839 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1840   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1841     return false;
1842
1843   CallSite CS(CI);
1844   CallingConv::ID CalleeCC = CS.getCallingConv();
1845   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1846     return false;
1847
1848   return true;
1849 }
1850
1851 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1852 /// a tailcall target by changing its ABI.
1853 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1854                                    bool GuaranteedTailCallOpt) {
1855   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1856 }
1857
1858 SDValue
1859 X86TargetLowering::LowerMemArgument(SDValue Chain,
1860                                     CallingConv::ID CallConv,
1861                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1862                                     DebugLoc dl, SelectionDAG &DAG,
1863                                     const CCValAssign &VA,
1864                                     MachineFrameInfo *MFI,
1865                                     unsigned i) const {
1866   // Create the nodes corresponding to a load from this parameter slot.
1867   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1868   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1869                               getTargetMachine().Options.GuaranteedTailCallOpt);
1870   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1871   EVT ValVT;
1872
1873   // If value is passed by pointer we have address passed instead of the value
1874   // itself.
1875   if (VA.getLocInfo() == CCValAssign::Indirect)
1876     ValVT = VA.getLocVT();
1877   else
1878     ValVT = VA.getValVT();
1879
1880   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1881   // changed with more analysis.
1882   // In case of tail call optimization mark all arguments mutable. Since they
1883   // could be overwritten by lowering of arguments in case of a tail call.
1884   if (Flags.isByVal()) {
1885     unsigned Bytes = Flags.getByValSize();
1886     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1887     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1888     return DAG.getFrameIndex(FI, getPointerTy());
1889   } else {
1890     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1891                                     VA.getLocMemOffset(), isImmutable);
1892     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1893     return DAG.getLoad(ValVT, dl, Chain, FIN,
1894                        MachinePointerInfo::getFixedStack(FI),
1895                        false, false, false, 0);
1896   }
1897 }
1898
1899 SDValue
1900 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1901                                         CallingConv::ID CallConv,
1902                                         bool isVarArg,
1903                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1904                                         DebugLoc dl,
1905                                         SelectionDAG &DAG,
1906                                         SmallVectorImpl<SDValue> &InVals)
1907                                           const {
1908   MachineFunction &MF = DAG.getMachineFunction();
1909   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1910
1911   const Function* Fn = MF.getFunction();
1912   if (Fn->hasExternalLinkage() &&
1913       Subtarget->isTargetCygMing() &&
1914       Fn->getName() == "main")
1915     FuncInfo->setForceFramePointer(true);
1916
1917   MachineFrameInfo *MFI = MF.getFrameInfo();
1918   bool Is64Bit = Subtarget->is64Bit();
1919   bool IsWindows = Subtarget->isTargetWindows();
1920   bool IsWin64 = Subtarget->isTargetWin64();
1921
1922   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1923          "Var args not supported with calling convention fastcc, ghc or hipe");
1924
1925   // Assign locations to all of the incoming arguments.
1926   SmallVector<CCValAssign, 16> ArgLocs;
1927   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1928                  ArgLocs, *DAG.getContext());
1929
1930   // Allocate shadow area for Win64
1931   if (IsWin64) {
1932     CCInfo.AllocateStack(32, 8);
1933   }
1934
1935   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1936
1937   unsigned LastVal = ~0U;
1938   SDValue ArgValue;
1939   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1940     CCValAssign &VA = ArgLocs[i];
1941     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1942     // places.
1943     assert(VA.getValNo() != LastVal &&
1944            "Don't support value assigned to multiple locs yet");
1945     (void)LastVal;
1946     LastVal = VA.getValNo();
1947
1948     if (VA.isRegLoc()) {
1949       EVT RegVT = VA.getLocVT();
1950       const TargetRegisterClass *RC;
1951       if (RegVT == MVT::i32)
1952         RC = &X86::GR32RegClass;
1953       else if (Is64Bit && RegVT == MVT::i64)
1954         RC = &X86::GR64RegClass;
1955       else if (RegVT == MVT::f32)
1956         RC = &X86::FR32RegClass;
1957       else if (RegVT == MVT::f64)
1958         RC = &X86::FR64RegClass;
1959       else if (RegVT.is256BitVector())
1960         RC = &X86::VR256RegClass;
1961       else if (RegVT.is128BitVector())
1962         RC = &X86::VR128RegClass;
1963       else if (RegVT == MVT::x86mmx)
1964         RC = &X86::VR64RegClass;
1965       else
1966         llvm_unreachable("Unknown argument type!");
1967
1968       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1969       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1970
1971       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1972       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1973       // right size.
1974       if (VA.getLocInfo() == CCValAssign::SExt)
1975         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1976                                DAG.getValueType(VA.getValVT()));
1977       else if (VA.getLocInfo() == CCValAssign::ZExt)
1978         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1979                                DAG.getValueType(VA.getValVT()));
1980       else if (VA.getLocInfo() == CCValAssign::BCvt)
1981         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1982
1983       if (VA.isExtInLoc()) {
1984         // Handle MMX values passed in XMM regs.
1985         if (RegVT.isVector()) {
1986           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1987                                  ArgValue);
1988         } else
1989           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1990       }
1991     } else {
1992       assert(VA.isMemLoc());
1993       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1994     }
1995
1996     // If value is passed via pointer - do a load.
1997     if (VA.getLocInfo() == CCValAssign::Indirect)
1998       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1999                              MachinePointerInfo(), false, false, false, 0);
2000
2001     InVals.push_back(ArgValue);
2002   }
2003
2004   // The x86-64 ABI for returning structs by value requires that we copy
2005   // the sret argument into %rax for the return. Save the argument into
2006   // a virtual register so that we can access it from the return points.
2007   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2008     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009     unsigned Reg = FuncInfo->getSRetReturnReg();
2010     if (!Reg) {
2011       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2012       FuncInfo->setSRetReturnReg(Reg);
2013     }
2014     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2015     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2016   }
2017
2018   unsigned StackSize = CCInfo.getNextStackOffset();
2019   // Align stack specially for tail calls.
2020   if (FuncIsMadeTailCallSafe(CallConv,
2021                              MF.getTarget().Options.GuaranteedTailCallOpt))
2022     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2023
2024   // If the function takes variable number of arguments, make a frame index for
2025   // the start of the first vararg value... for expansion of llvm.va_start.
2026   if (isVarArg) {
2027     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2028                     CallConv != CallingConv::X86_ThisCall)) {
2029       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2030     }
2031     if (Is64Bit) {
2032       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2033
2034       // FIXME: We should really autogenerate these arrays
2035       static const uint16_t GPR64ArgRegsWin64[] = {
2036         X86::RCX, X86::RDX, X86::R8,  X86::R9
2037       };
2038       static const uint16_t GPR64ArgRegs64Bit[] = {
2039         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2040       };
2041       static const uint16_t XMMArgRegs64Bit[] = {
2042         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2044       };
2045       const uint16_t *GPR64ArgRegs;
2046       unsigned NumXMMRegs = 0;
2047
2048       if (IsWin64) {
2049         // The XMM registers which might contain var arg parameters are shadowed
2050         // in their paired GPR.  So we only need to save the GPR to their home
2051         // slots.
2052         TotalNumIntRegs = 4;
2053         GPR64ArgRegs = GPR64ArgRegsWin64;
2054       } else {
2055         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2056         GPR64ArgRegs = GPR64ArgRegs64Bit;
2057
2058         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2059                                                 TotalNumXMMRegs);
2060       }
2061       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2062                                                        TotalNumIntRegs);
2063
2064       bool NoImplicitFloatOps = Fn->getFnAttributes().
2065         hasAttribute(Attribute::NoImplicitFloat);
2066       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2067              "SSE register cannot be used when SSE is disabled!");
2068       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2069                NoImplicitFloatOps) &&
2070              "SSE register cannot be used when SSE is disabled!");
2071       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2072           !Subtarget->hasSSE1())
2073         // Kernel mode asks for SSE to be disabled, so don't push them
2074         // on the stack.
2075         TotalNumXMMRegs = 0;
2076
2077       if (IsWin64) {
2078         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2079         // Get to the caller-allocated home save location.  Add 8 to account
2080         // for the return address.
2081         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2082         FuncInfo->setRegSaveFrameIndex(
2083           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2084         // Fixup to set vararg frame on shadow area (4 x i64).
2085         if (NumIntRegs < 4)
2086           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2087       } else {
2088         // For X86-64, if there are vararg parameters that are passed via
2089         // registers, then we must store them to their spots on the stack so
2090         // they may be loaded by deferencing the result of va_next.
2091         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2092         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2093         FuncInfo->setRegSaveFrameIndex(
2094           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2095                                false));
2096       }
2097
2098       // Store the integer parameter registers.
2099       SmallVector<SDValue, 8> MemOps;
2100       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2101                                         getPointerTy());
2102       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2103       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2104         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2105                                   DAG.getIntPtrConstant(Offset));
2106         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2107                                      &X86::GR64RegClass);
2108         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2109         SDValue Store =
2110           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2111                        MachinePointerInfo::getFixedStack(
2112                          FuncInfo->getRegSaveFrameIndex(), Offset),
2113                        false, false, 0);
2114         MemOps.push_back(Store);
2115         Offset += 8;
2116       }
2117
2118       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2119         // Now store the XMM (fp + vector) parameter registers.
2120         SmallVector<SDValue, 11> SaveXMMOps;
2121         SaveXMMOps.push_back(Chain);
2122
2123         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2124         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2125         SaveXMMOps.push_back(ALVal);
2126
2127         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2128                                FuncInfo->getRegSaveFrameIndex()));
2129         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2130                                FuncInfo->getVarArgsFPOffset()));
2131
2132         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2133           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2134                                        &X86::VR128RegClass);
2135           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2136           SaveXMMOps.push_back(Val);
2137         }
2138         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2139                                      MVT::Other,
2140                                      &SaveXMMOps[0], SaveXMMOps.size()));
2141       }
2142
2143       if (!MemOps.empty())
2144         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2145                             &MemOps[0], MemOps.size());
2146     }
2147   }
2148
2149   // Some CCs need callee pop.
2150   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2151                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2152     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2153   } else {
2154     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2155     // If this is an sret function, the return should pop the hidden pointer.
2156     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2157         argsAreStructReturn(Ins) == StackStructReturn)
2158       FuncInfo->setBytesToPopOnReturn(4);
2159   }
2160
2161   if (!Is64Bit) {
2162     // RegSaveFrameIndex is X86-64 only.
2163     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2164     if (CallConv == CallingConv::X86_FastCall ||
2165         CallConv == CallingConv::X86_ThisCall)
2166       // fastcc functions can't have varargs.
2167       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2168   }
2169
2170   FuncInfo->setArgumentStackSize(StackSize);
2171
2172   return Chain;
2173 }
2174
2175 SDValue
2176 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2177                                     SDValue StackPtr, SDValue Arg,
2178                                     DebugLoc dl, SelectionDAG &DAG,
2179                                     const CCValAssign &VA,
2180                                     ISD::ArgFlagsTy Flags) const {
2181   unsigned LocMemOffset = VA.getLocMemOffset();
2182   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2183   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2184   if (Flags.isByVal())
2185     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2186
2187   return DAG.getStore(Chain, dl, Arg, PtrOff,
2188                       MachinePointerInfo::getStack(LocMemOffset),
2189                       false, false, 0);
2190 }
2191
2192 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2193 /// optimization is performed and it is required.
2194 SDValue
2195 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2196                                            SDValue &OutRetAddr, SDValue Chain,
2197                                            bool IsTailCall, bool Is64Bit,
2198                                            int FPDiff, DebugLoc dl) const {
2199   // Adjust the Return address stack slot.
2200   EVT VT = getPointerTy();
2201   OutRetAddr = getReturnAddressFrameIndex(DAG);
2202
2203   // Load the "old" Return address.
2204   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2205                            false, false, false, 0);
2206   return SDValue(OutRetAddr.getNode(), 1);
2207 }
2208
2209 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2210 /// optimization is performed and it is required (FPDiff!=0).
2211 static SDValue
2212 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2213                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2214                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2215   // Store the return address to the appropriate stack slot.
2216   if (!FPDiff) return Chain;
2217   // Calculate the new stack slot for the return address.
2218   int NewReturnAddrFI =
2219     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2220   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2221   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2222                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2223                        false, false, 0);
2224   return Chain;
2225 }
2226
2227 SDValue
2228 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2229                              SmallVectorImpl<SDValue> &InVals) const {
2230   SelectionDAG &DAG                     = CLI.DAG;
2231   DebugLoc &dl                          = CLI.DL;
2232   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2233   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2234   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2235   SDValue Chain                         = CLI.Chain;
2236   SDValue Callee                        = CLI.Callee;
2237   CallingConv::ID CallConv              = CLI.CallConv;
2238   bool &isTailCall                      = CLI.IsTailCall;
2239   bool isVarArg                         = CLI.IsVarArg;
2240
2241   MachineFunction &MF = DAG.getMachineFunction();
2242   bool Is64Bit        = Subtarget->is64Bit();
2243   bool IsWin64        = Subtarget->isTargetWin64();
2244   bool IsWindows      = Subtarget->isTargetWindows();
2245   StructReturnType SR = callIsStructReturn(Outs);
2246   bool IsSibcall      = false;
2247
2248   if (MF.getTarget().Options.DisableTailCalls)
2249     isTailCall = false;
2250
2251   if (isTailCall) {
2252     // Check if it's really possible to do a tail call.
2253     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2254                     isVarArg, SR != NotStructReturn,
2255                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2256                     Outs, OutVals, Ins, DAG);
2257
2258     // Sibcalls are automatically detected tailcalls which do not require
2259     // ABI changes.
2260     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2261       IsSibcall = true;
2262
2263     if (isTailCall)
2264       ++NumTailCalls;
2265   }
2266
2267   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2268          "Var args not supported with calling convention fastcc, ghc or hipe");
2269
2270   // Analyze operands of the call, assigning locations to each operand.
2271   SmallVector<CCValAssign, 16> ArgLocs;
2272   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2273                  ArgLocs, *DAG.getContext());
2274
2275   // Allocate shadow area for Win64
2276   if (IsWin64) {
2277     CCInfo.AllocateStack(32, 8);
2278   }
2279
2280   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2281
2282   // Get a count of how many bytes are to be pushed on the stack.
2283   unsigned NumBytes = CCInfo.getNextStackOffset();
2284   if (IsSibcall)
2285     // This is a sibcall. The memory operands are available in caller's
2286     // own caller's stack.
2287     NumBytes = 0;
2288   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2289            IsTailCallConvention(CallConv))
2290     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2291
2292   int FPDiff = 0;
2293   if (isTailCall && !IsSibcall) {
2294     // Lower arguments at fp - stackoffset + fpdiff.
2295     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2296     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2297
2298     FPDiff = NumBytesCallerPushed - NumBytes;
2299
2300     // Set the delta of movement of the returnaddr stackslot.
2301     // But only set if delta is greater than previous delta.
2302     if (FPDiff < X86Info->getTCReturnAddrDelta())
2303       X86Info->setTCReturnAddrDelta(FPDiff);
2304   }
2305
2306   if (!IsSibcall)
2307     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2308
2309   SDValue RetAddrFrIdx;
2310   // Load return address for tail calls.
2311   if (isTailCall && FPDiff)
2312     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2313                                     Is64Bit, FPDiff, dl);
2314
2315   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2316   SmallVector<SDValue, 8> MemOpChains;
2317   SDValue StackPtr;
2318
2319   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2320   // of tail call optimization arguments are handle later.
2321   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2322     CCValAssign &VA = ArgLocs[i];
2323     EVT RegVT = VA.getLocVT();
2324     SDValue Arg = OutVals[i];
2325     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2326     bool isByVal = Flags.isByVal();
2327
2328     // Promote the value if needed.
2329     switch (VA.getLocInfo()) {
2330     default: llvm_unreachable("Unknown loc info!");
2331     case CCValAssign::Full: break;
2332     case CCValAssign::SExt:
2333       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2334       break;
2335     case CCValAssign::ZExt:
2336       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2337       break;
2338     case CCValAssign::AExt:
2339       if (RegVT.is128BitVector()) {
2340         // Special case: passing MMX values in XMM registers.
2341         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2342         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2343         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2344       } else
2345         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2346       break;
2347     case CCValAssign::BCvt:
2348       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2349       break;
2350     case CCValAssign::Indirect: {
2351       // Store the argument.
2352       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2353       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2354       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2355                            MachinePointerInfo::getFixedStack(FI),
2356                            false, false, 0);
2357       Arg = SpillSlot;
2358       break;
2359     }
2360     }
2361
2362     if (VA.isRegLoc()) {
2363       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2364       if (isVarArg && IsWin64) {
2365         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2366         // shadow reg if callee is a varargs function.
2367         unsigned ShadowReg = 0;
2368         switch (VA.getLocReg()) {
2369         case X86::XMM0: ShadowReg = X86::RCX; break;
2370         case X86::XMM1: ShadowReg = X86::RDX; break;
2371         case X86::XMM2: ShadowReg = X86::R8; break;
2372         case X86::XMM3: ShadowReg = X86::R9; break;
2373         }
2374         if (ShadowReg)
2375           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2376       }
2377     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2378       assert(VA.isMemLoc());
2379       if (StackPtr.getNode() == 0)
2380         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2381                                       getPointerTy());
2382       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2383                                              dl, DAG, VA, Flags));
2384     }
2385   }
2386
2387   if (!MemOpChains.empty())
2388     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2389                         &MemOpChains[0], MemOpChains.size());
2390
2391   if (Subtarget->isPICStyleGOT()) {
2392     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2393     // GOT pointer.
2394     if (!isTailCall) {
2395       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2396                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2397     } else {
2398       // If we are tail calling and generating PIC/GOT style code load the
2399       // address of the callee into ECX. The value in ecx is used as target of
2400       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2401       // for tail calls on PIC/GOT architectures. Normally we would just put the
2402       // address of GOT into ebx and then call target@PLT. But for tail calls
2403       // ebx would be restored (since ebx is callee saved) before jumping to the
2404       // target@PLT.
2405
2406       // Note: The actual moving to ECX is done further down.
2407       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2408       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2409           !G->getGlobal()->hasProtectedVisibility())
2410         Callee = LowerGlobalAddress(Callee, DAG);
2411       else if (isa<ExternalSymbolSDNode>(Callee))
2412         Callee = LowerExternalSymbol(Callee, DAG);
2413     }
2414   }
2415
2416   if (Is64Bit && isVarArg && !IsWin64) {
2417     // From AMD64 ABI document:
2418     // For calls that may call functions that use varargs or stdargs
2419     // (prototype-less calls or calls to functions containing ellipsis (...) in
2420     // the declaration) %al is used as hidden argument to specify the number
2421     // of SSE registers used. The contents of %al do not need to match exactly
2422     // the number of registers, but must be an ubound on the number of SSE
2423     // registers used and is in the range 0 - 8 inclusive.
2424
2425     // Count the number of XMM registers allocated.
2426     static const uint16_t XMMArgRegs[] = {
2427       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2428       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2429     };
2430     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2431     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2432            && "SSE registers cannot be used when SSE is disabled");
2433
2434     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2435                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2436   }
2437
2438   // For tail calls lower the arguments to the 'real' stack slot.
2439   if (isTailCall) {
2440     // Force all the incoming stack arguments to be loaded from the stack
2441     // before any new outgoing arguments are stored to the stack, because the
2442     // outgoing stack slots may alias the incoming argument stack slots, and
2443     // the alias isn't otherwise explicit. This is slightly more conservative
2444     // than necessary, because it means that each store effectively depends
2445     // on every argument instead of just those arguments it would clobber.
2446     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2447
2448     SmallVector<SDValue, 8> MemOpChains2;
2449     SDValue FIN;
2450     int FI = 0;
2451     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2452       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2453         CCValAssign &VA = ArgLocs[i];
2454         if (VA.isRegLoc())
2455           continue;
2456         assert(VA.isMemLoc());
2457         SDValue Arg = OutVals[i];
2458         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2459         // Create frame index.
2460         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2461         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2462         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2463         FIN = DAG.getFrameIndex(FI, getPointerTy());
2464
2465         if (Flags.isByVal()) {
2466           // Copy relative to framepointer.
2467           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2468           if (StackPtr.getNode() == 0)
2469             StackPtr = DAG.getCopyFromReg(Chain, dl,
2470                                           RegInfo->getStackRegister(),
2471                                           getPointerTy());
2472           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2473
2474           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2475                                                            ArgChain,
2476                                                            Flags, DAG, dl));
2477         } else {
2478           // Store relative to framepointer.
2479           MemOpChains2.push_back(
2480             DAG.getStore(ArgChain, dl, Arg, FIN,
2481                          MachinePointerInfo::getFixedStack(FI),
2482                          false, false, 0));
2483         }
2484       }
2485     }
2486
2487     if (!MemOpChains2.empty())
2488       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2489                           &MemOpChains2[0], MemOpChains2.size());
2490
2491     // Store the return address to the appropriate stack slot.
2492     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2493                                      getPointerTy(), RegInfo->getSlotSize(),
2494                                      FPDiff, dl);
2495   }
2496
2497   // Build a sequence of copy-to-reg nodes chained together with token chain
2498   // and flag operands which copy the outgoing args into registers.
2499   SDValue InFlag;
2500   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2501     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2502                              RegsToPass[i].second, InFlag);
2503     InFlag = Chain.getValue(1);
2504   }
2505
2506   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2507     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2508     // In the 64-bit large code model, we have to make all calls
2509     // through a register, since the call instruction's 32-bit
2510     // pc-relative offset may not be large enough to hold the whole
2511     // address.
2512   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2513     // If the callee is a GlobalAddress node (quite common, every direct call
2514     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2515     // it.
2516
2517     // We should use extra load for direct calls to dllimported functions in
2518     // non-JIT mode.
2519     const GlobalValue *GV = G->getGlobal();
2520     if (!GV->hasDLLImportLinkage()) {
2521       unsigned char OpFlags = 0;
2522       bool ExtraLoad = false;
2523       unsigned WrapperKind = ISD::DELETED_NODE;
2524
2525       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2526       // external symbols most go through the PLT in PIC mode.  If the symbol
2527       // has hidden or protected visibility, or if it is static or local, then
2528       // we don't need to use the PLT - we can directly call it.
2529       if (Subtarget->isTargetELF() &&
2530           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2531           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2532         OpFlags = X86II::MO_PLT;
2533       } else if (Subtarget->isPICStyleStubAny() &&
2534                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2535                  (!Subtarget->getTargetTriple().isMacOSX() ||
2536                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2537         // PC-relative references to external symbols should go through $stub,
2538         // unless we're building with the leopard linker or later, which
2539         // automatically synthesizes these stubs.
2540         OpFlags = X86II::MO_DARWIN_STUB;
2541       } else if (Subtarget->isPICStyleRIPRel() &&
2542                  isa<Function>(GV) &&
2543                  cast<Function>(GV)->getFnAttributes().
2544                    hasAttribute(Attribute::NonLazyBind)) {
2545         // If the function is marked as non-lazy, generate an indirect call
2546         // which loads from the GOT directly. This avoids runtime overhead
2547         // at the cost of eager binding (and one extra byte of encoding).
2548         OpFlags = X86II::MO_GOTPCREL;
2549         WrapperKind = X86ISD::WrapperRIP;
2550         ExtraLoad = true;
2551       }
2552
2553       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2554                                           G->getOffset(), OpFlags);
2555
2556       // Add a wrapper if needed.
2557       if (WrapperKind != ISD::DELETED_NODE)
2558         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2559       // Add extra indirection if needed.
2560       if (ExtraLoad)
2561         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2562                              MachinePointerInfo::getGOT(),
2563                              false, false, false, 0);
2564     }
2565   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2566     unsigned char OpFlags = 0;
2567
2568     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2569     // external symbols should go through the PLT.
2570     if (Subtarget->isTargetELF() &&
2571         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2572       OpFlags = X86II::MO_PLT;
2573     } else if (Subtarget->isPICStyleStubAny() &&
2574                (!Subtarget->getTargetTriple().isMacOSX() ||
2575                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2576       // PC-relative references to external symbols should go through $stub,
2577       // unless we're building with the leopard linker or later, which
2578       // automatically synthesizes these stubs.
2579       OpFlags = X86II::MO_DARWIN_STUB;
2580     }
2581
2582     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2583                                          OpFlags);
2584   }
2585
2586   // Returns a chain & a flag for retval copy to use.
2587   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2588   SmallVector<SDValue, 8> Ops;
2589
2590   if (!IsSibcall && isTailCall) {
2591     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2592                            DAG.getIntPtrConstant(0, true), InFlag);
2593     InFlag = Chain.getValue(1);
2594   }
2595
2596   Ops.push_back(Chain);
2597   Ops.push_back(Callee);
2598
2599   if (isTailCall)
2600     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2601
2602   // Add argument registers to the end of the list so that they are known live
2603   // into the call.
2604   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2605     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2606                                   RegsToPass[i].second.getValueType()));
2607
2608   // Add a register mask operand representing the call-preserved registers.
2609   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2610   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2611   assert(Mask && "Missing call preserved mask for calling convention");
2612   Ops.push_back(DAG.getRegisterMask(Mask));
2613
2614   if (InFlag.getNode())
2615     Ops.push_back(InFlag);
2616
2617   if (isTailCall) {
2618     // We used to do:
2619     //// If this is the first return lowered for this function, add the regs
2620     //// to the liveout set for the function.
2621     // This isn't right, although it's probably harmless on x86; liveouts
2622     // should be computed from returns not tail calls.  Consider a void
2623     // function making a tail call to a function returning int.
2624     return DAG.getNode(X86ISD::TC_RETURN, dl,
2625                        NodeTys, &Ops[0], Ops.size());
2626   }
2627
2628   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2629   InFlag = Chain.getValue(1);
2630
2631   // Create the CALLSEQ_END node.
2632   unsigned NumBytesForCalleeToPush;
2633   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2634                        getTargetMachine().Options.GuaranteedTailCallOpt))
2635     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2636   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2637            SR == StackStructReturn)
2638     // If this is a call to a struct-return function, the callee
2639     // pops the hidden struct pointer, so we have to push it back.
2640     // This is common for Darwin/X86, Linux & Mingw32 targets.
2641     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2642     NumBytesForCalleeToPush = 4;
2643   else
2644     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2645
2646   // Returns a flag for retval copy to use.
2647   if (!IsSibcall) {
2648     Chain = DAG.getCALLSEQ_END(Chain,
2649                                DAG.getIntPtrConstant(NumBytes, true),
2650                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2651                                                      true),
2652                                InFlag);
2653     InFlag = Chain.getValue(1);
2654   }
2655
2656   // Handle result values, copying them out of physregs into vregs that we
2657   // return.
2658   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2659                          Ins, dl, DAG, InVals);
2660 }
2661
2662 //===----------------------------------------------------------------------===//
2663 //                Fast Calling Convention (tail call) implementation
2664 //===----------------------------------------------------------------------===//
2665
2666 //  Like std call, callee cleans arguments, convention except that ECX is
2667 //  reserved for storing the tail called function address. Only 2 registers are
2668 //  free for argument passing (inreg). Tail call optimization is performed
2669 //  provided:
2670 //                * tailcallopt is enabled
2671 //                * caller/callee are fastcc
2672 //  On X86_64 architecture with GOT-style position independent code only local
2673 //  (within module) calls are supported at the moment.
2674 //  To keep the stack aligned according to platform abi the function
2675 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2676 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2677 //  If a tail called function callee has more arguments than the caller the
2678 //  caller needs to make sure that there is room to move the RETADDR to. This is
2679 //  achieved by reserving an area the size of the argument delta right after the
2680 //  original REtADDR, but before the saved framepointer or the spilled registers
2681 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2682 //  stack layout:
2683 //    arg1
2684 //    arg2
2685 //    RETADDR
2686 //    [ new RETADDR
2687 //      move area ]
2688 //    (possible EBP)
2689 //    ESI
2690 //    EDI
2691 //    local1 ..
2692
2693 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2694 /// for a 16 byte align requirement.
2695 unsigned
2696 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2697                                                SelectionDAG& DAG) const {
2698   MachineFunction &MF = DAG.getMachineFunction();
2699   const TargetMachine &TM = MF.getTarget();
2700   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2701   unsigned StackAlignment = TFI.getStackAlignment();
2702   uint64_t AlignMask = StackAlignment - 1;
2703   int64_t Offset = StackSize;
2704   unsigned SlotSize = RegInfo->getSlotSize();
2705   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2706     // Number smaller than 12 so just add the difference.
2707     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2708   } else {
2709     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2710     Offset = ((~AlignMask) & Offset) + StackAlignment +
2711       (StackAlignment-SlotSize);
2712   }
2713   return Offset;
2714 }
2715
2716 /// MatchingStackOffset - Return true if the given stack call argument is
2717 /// already available in the same position (relatively) of the caller's
2718 /// incoming argument stack.
2719 static
2720 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2721                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2722                          const X86InstrInfo *TII) {
2723   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2724   int FI = INT_MAX;
2725   if (Arg.getOpcode() == ISD::CopyFromReg) {
2726     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2727     if (!TargetRegisterInfo::isVirtualRegister(VR))
2728       return false;
2729     MachineInstr *Def = MRI->getVRegDef(VR);
2730     if (!Def)
2731       return false;
2732     if (!Flags.isByVal()) {
2733       if (!TII->isLoadFromStackSlot(Def, FI))
2734         return false;
2735     } else {
2736       unsigned Opcode = Def->getOpcode();
2737       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2738           Def->getOperand(1).isFI()) {
2739         FI = Def->getOperand(1).getIndex();
2740         Bytes = Flags.getByValSize();
2741       } else
2742         return false;
2743     }
2744   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2745     if (Flags.isByVal())
2746       // ByVal argument is passed in as a pointer but it's now being
2747       // dereferenced. e.g.
2748       // define @foo(%struct.X* %A) {
2749       //   tail call @bar(%struct.X* byval %A)
2750       // }
2751       return false;
2752     SDValue Ptr = Ld->getBasePtr();
2753     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2754     if (!FINode)
2755       return false;
2756     FI = FINode->getIndex();
2757   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2758     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2759     FI = FINode->getIndex();
2760     Bytes = Flags.getByValSize();
2761   } else
2762     return false;
2763
2764   assert(FI != INT_MAX);
2765   if (!MFI->isFixedObjectIndex(FI))
2766     return false;
2767   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2768 }
2769
2770 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2771 /// for tail call optimization. Targets which want to do tail call
2772 /// optimization should implement this function.
2773 bool
2774 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2775                                                      CallingConv::ID CalleeCC,
2776                                                      bool isVarArg,
2777                                                      bool isCalleeStructRet,
2778                                                      bool isCallerStructRet,
2779                                                      Type *RetTy,
2780                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2781                                     const SmallVectorImpl<SDValue> &OutVals,
2782                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2783                                                      SelectionDAG& DAG) const {
2784   if (!IsTailCallConvention(CalleeCC) &&
2785       CalleeCC != CallingConv::C)
2786     return false;
2787
2788   // If -tailcallopt is specified, make fastcc functions tail-callable.
2789   const MachineFunction &MF = DAG.getMachineFunction();
2790   const Function *CallerF = DAG.getMachineFunction().getFunction();
2791
2792   // If the function return type is x86_fp80 and the callee return type is not,
2793   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2794   // perform a tailcall optimization here.
2795   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2796     return false;
2797
2798   CallingConv::ID CallerCC = CallerF->getCallingConv();
2799   bool CCMatch = CallerCC == CalleeCC;
2800
2801   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2802     if (IsTailCallConvention(CalleeCC) && CCMatch)
2803       return true;
2804     return false;
2805   }
2806
2807   // Look for obvious safe cases to perform tail call optimization that do not
2808   // require ABI changes. This is what gcc calls sibcall.
2809
2810   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2811   // emit a special epilogue.
2812   if (RegInfo->needsStackRealignment(MF))
2813     return false;
2814
2815   // Also avoid sibcall optimization if either caller or callee uses struct
2816   // return semantics.
2817   if (isCalleeStructRet || isCallerStructRet)
2818     return false;
2819
2820   // An stdcall caller is expected to clean up its arguments; the callee
2821   // isn't going to do that.
2822   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2823     return false;
2824
2825   // Do not sibcall optimize vararg calls unless all arguments are passed via
2826   // registers.
2827   if (isVarArg && !Outs.empty()) {
2828
2829     // Optimizing for varargs on Win64 is unlikely to be safe without
2830     // additional testing.
2831     if (Subtarget->isTargetWin64())
2832       return false;
2833
2834     SmallVector<CCValAssign, 16> ArgLocs;
2835     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2836                    getTargetMachine(), ArgLocs, *DAG.getContext());
2837
2838     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2840       if (!ArgLocs[i].isRegLoc())
2841         return false;
2842   }
2843
2844   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2845   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2846   // this into a sibcall.
2847   bool Unused = false;
2848   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2849     if (!Ins[i].Used) {
2850       Unused = true;
2851       break;
2852     }
2853   }
2854   if (Unused) {
2855     SmallVector<CCValAssign, 16> RVLocs;
2856     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2857                    getTargetMachine(), RVLocs, *DAG.getContext());
2858     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2859     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2860       CCValAssign &VA = RVLocs[i];
2861       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2862         return false;
2863     }
2864   }
2865
2866   // If the calling conventions do not match, then we'd better make sure the
2867   // results are returned in the same way as what the caller expects.
2868   if (!CCMatch) {
2869     SmallVector<CCValAssign, 16> RVLocs1;
2870     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2871                     getTargetMachine(), RVLocs1, *DAG.getContext());
2872     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2873
2874     SmallVector<CCValAssign, 16> RVLocs2;
2875     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2876                     getTargetMachine(), RVLocs2, *DAG.getContext());
2877     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2878
2879     if (RVLocs1.size() != RVLocs2.size())
2880       return false;
2881     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2882       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2883         return false;
2884       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2885         return false;
2886       if (RVLocs1[i].isRegLoc()) {
2887         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2888           return false;
2889       } else {
2890         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2891           return false;
2892       }
2893     }
2894   }
2895
2896   // If the callee takes no arguments then go on to check the results of the
2897   // call.
2898   if (!Outs.empty()) {
2899     // Check if stack adjustment is needed. For now, do not do this if any
2900     // argument is passed on the stack.
2901     SmallVector<CCValAssign, 16> ArgLocs;
2902     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2903                    getTargetMachine(), ArgLocs, *DAG.getContext());
2904
2905     // Allocate shadow area for Win64
2906     if (Subtarget->isTargetWin64()) {
2907       CCInfo.AllocateStack(32, 8);
2908     }
2909
2910     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2911     if (CCInfo.getNextStackOffset()) {
2912       MachineFunction &MF = DAG.getMachineFunction();
2913       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2914         return false;
2915
2916       // Check if the arguments are already laid out in the right way as
2917       // the caller's fixed stack objects.
2918       MachineFrameInfo *MFI = MF.getFrameInfo();
2919       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2920       const X86InstrInfo *TII =
2921         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2922       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2923         CCValAssign &VA = ArgLocs[i];
2924         SDValue Arg = OutVals[i];
2925         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2926         if (VA.getLocInfo() == CCValAssign::Indirect)
2927           return false;
2928         if (!VA.isRegLoc()) {
2929           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2930                                    MFI, MRI, TII))
2931             return false;
2932         }
2933       }
2934     }
2935
2936     // If the tailcall address may be in a register, then make sure it's
2937     // possible to register allocate for it. In 32-bit, the call address can
2938     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2939     // callee-saved registers are restored. These happen to be the same
2940     // registers used to pass 'inreg' arguments so watch out for those.
2941     if (!Subtarget->is64Bit() &&
2942         !isa<GlobalAddressSDNode>(Callee) &&
2943         !isa<ExternalSymbolSDNode>(Callee)) {
2944       unsigned NumInRegs = 0;
2945       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2946         CCValAssign &VA = ArgLocs[i];
2947         if (!VA.isRegLoc())
2948           continue;
2949         unsigned Reg = VA.getLocReg();
2950         switch (Reg) {
2951         default: break;
2952         case X86::EAX: case X86::EDX: case X86::ECX:
2953           if (++NumInRegs == 3)
2954             return false;
2955           break;
2956         }
2957       }
2958     }
2959   }
2960
2961   return true;
2962 }
2963
2964 FastISel *
2965 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2966                                   const TargetLibraryInfo *libInfo) const {
2967   return X86::createFastISel(funcInfo, libInfo);
2968 }
2969
2970 //===----------------------------------------------------------------------===//
2971 //                           Other Lowering Hooks
2972 //===----------------------------------------------------------------------===//
2973
2974 static bool MayFoldLoad(SDValue Op) {
2975   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2976 }
2977
2978 static bool MayFoldIntoStore(SDValue Op) {
2979   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2980 }
2981
2982 static bool isTargetShuffle(unsigned Opcode) {
2983   switch(Opcode) {
2984   default: return false;
2985   case X86ISD::PSHUFD:
2986   case X86ISD::PSHUFHW:
2987   case X86ISD::PSHUFLW:
2988   case X86ISD::SHUFP:
2989   case X86ISD::PALIGN:
2990   case X86ISD::MOVLHPS:
2991   case X86ISD::MOVLHPD:
2992   case X86ISD::MOVHLPS:
2993   case X86ISD::MOVLPS:
2994   case X86ISD::MOVLPD:
2995   case X86ISD::MOVSHDUP:
2996   case X86ISD::MOVSLDUP:
2997   case X86ISD::MOVDDUP:
2998   case X86ISD::MOVSS:
2999   case X86ISD::MOVSD:
3000   case X86ISD::UNPCKL:
3001   case X86ISD::UNPCKH:
3002   case X86ISD::VPERMILP:
3003   case X86ISD::VPERM2X128:
3004   case X86ISD::VPERMI:
3005     return true;
3006   }
3007 }
3008
3009 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3010                                     SDValue V1, SelectionDAG &DAG) {
3011   switch(Opc) {
3012   default: llvm_unreachable("Unknown x86 shuffle node");
3013   case X86ISD::MOVSHDUP:
3014   case X86ISD::MOVSLDUP:
3015   case X86ISD::MOVDDUP:
3016     return DAG.getNode(Opc, dl, VT, V1);
3017   }
3018 }
3019
3020 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3021                                     SDValue V1, unsigned TargetMask,
3022                                     SelectionDAG &DAG) {
3023   switch(Opc) {
3024   default: llvm_unreachable("Unknown x86 shuffle node");
3025   case X86ISD::PSHUFD:
3026   case X86ISD::PSHUFHW:
3027   case X86ISD::PSHUFLW:
3028   case X86ISD::VPERMILP:
3029   case X86ISD::VPERMI:
3030     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3031   }
3032 }
3033
3034 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3035                                     SDValue V1, SDValue V2, unsigned TargetMask,
3036                                     SelectionDAG &DAG) {
3037   switch(Opc) {
3038   default: llvm_unreachable("Unknown x86 shuffle node");
3039   case X86ISD::PALIGN:
3040   case X86ISD::SHUFP:
3041   case X86ISD::VPERM2X128:
3042     return DAG.getNode(Opc, dl, VT, V1, V2,
3043                        DAG.getConstant(TargetMask, MVT::i8));
3044   }
3045 }
3046
3047 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3048                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3049   switch(Opc) {
3050   default: llvm_unreachable("Unknown x86 shuffle node");
3051   case X86ISD::MOVLHPS:
3052   case X86ISD::MOVLHPD:
3053   case X86ISD::MOVHLPS:
3054   case X86ISD::MOVLPS:
3055   case X86ISD::MOVLPD:
3056   case X86ISD::MOVSS:
3057   case X86ISD::MOVSD:
3058   case X86ISD::UNPCKL:
3059   case X86ISD::UNPCKH:
3060     return DAG.getNode(Opc, dl, VT, V1, V2);
3061   }
3062 }
3063
3064 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3065   MachineFunction &MF = DAG.getMachineFunction();
3066   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3067   int ReturnAddrIndex = FuncInfo->getRAIndex();
3068
3069   if (ReturnAddrIndex == 0) {
3070     // Set up a frame object for the return address.
3071     unsigned SlotSize = RegInfo->getSlotSize();
3072     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3073                                                            false);
3074     FuncInfo->setRAIndex(ReturnAddrIndex);
3075   }
3076
3077   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3078 }
3079
3080 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3081                                        bool hasSymbolicDisplacement) {
3082   // Offset should fit into 32 bit immediate field.
3083   if (!isInt<32>(Offset))
3084     return false;
3085
3086   // If we don't have a symbolic displacement - we don't have any extra
3087   // restrictions.
3088   if (!hasSymbolicDisplacement)
3089     return true;
3090
3091   // FIXME: Some tweaks might be needed for medium code model.
3092   if (M != CodeModel::Small && M != CodeModel::Kernel)
3093     return false;
3094
3095   // For small code model we assume that latest object is 16MB before end of 31
3096   // bits boundary. We may also accept pretty large negative constants knowing
3097   // that all objects are in the positive half of address space.
3098   if (M == CodeModel::Small && Offset < 16*1024*1024)
3099     return true;
3100
3101   // For kernel code model we know that all object resist in the negative half
3102   // of 32bits address space. We may not accept negative offsets, since they may
3103   // be just off and we may accept pretty large positive ones.
3104   if (M == CodeModel::Kernel && Offset > 0)
3105     return true;
3106
3107   return false;
3108 }
3109
3110 /// isCalleePop - Determines whether the callee is required to pop its
3111 /// own arguments. Callee pop is necessary to support tail calls.
3112 bool X86::isCalleePop(CallingConv::ID CallingConv,
3113                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3114   if (IsVarArg)
3115     return false;
3116
3117   switch (CallingConv) {
3118   default:
3119     return false;
3120   case CallingConv::X86_StdCall:
3121     return !is64Bit;
3122   case CallingConv::X86_FastCall:
3123     return !is64Bit;
3124   case CallingConv::X86_ThisCall:
3125     return !is64Bit;
3126   case CallingConv::Fast:
3127     return TailCallOpt;
3128   case CallingConv::GHC:
3129     return TailCallOpt;
3130   case CallingConv::HiPE:
3131     return TailCallOpt;
3132   }
3133 }
3134
3135 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3136 /// specific condition code, returning the condition code and the LHS/RHS of the
3137 /// comparison to make.
3138 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3139                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3140   if (!isFP) {
3141     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3142       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3143         // X > -1   -> X == 0, jump !sign.
3144         RHS = DAG.getConstant(0, RHS.getValueType());
3145         return X86::COND_NS;
3146       }
3147       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3148         // X < 0   -> X == 0, jump on sign.
3149         return X86::COND_S;
3150       }
3151       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3152         // X < 1   -> X <= 0
3153         RHS = DAG.getConstant(0, RHS.getValueType());
3154         return X86::COND_LE;
3155       }
3156     }
3157
3158     switch (SetCCOpcode) {
3159     default: llvm_unreachable("Invalid integer condition!");
3160     case ISD::SETEQ:  return X86::COND_E;
3161     case ISD::SETGT:  return X86::COND_G;
3162     case ISD::SETGE:  return X86::COND_GE;
3163     case ISD::SETLT:  return X86::COND_L;
3164     case ISD::SETLE:  return X86::COND_LE;
3165     case ISD::SETNE:  return X86::COND_NE;
3166     case ISD::SETULT: return X86::COND_B;
3167     case ISD::SETUGT: return X86::COND_A;
3168     case ISD::SETULE: return X86::COND_BE;
3169     case ISD::SETUGE: return X86::COND_AE;
3170     }
3171   }
3172
3173   // First determine if it is required or is profitable to flip the operands.
3174
3175   // If LHS is a foldable load, but RHS is not, flip the condition.
3176   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3177       !ISD::isNON_EXTLoad(RHS.getNode())) {
3178     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3179     std::swap(LHS, RHS);
3180   }
3181
3182   switch (SetCCOpcode) {
3183   default: break;
3184   case ISD::SETOLT:
3185   case ISD::SETOLE:
3186   case ISD::SETUGT:
3187   case ISD::SETUGE:
3188     std::swap(LHS, RHS);
3189     break;
3190   }
3191
3192   // On a floating point condition, the flags are set as follows:
3193   // ZF  PF  CF   op
3194   //  0 | 0 | 0 | X > Y
3195   //  0 | 0 | 1 | X < Y
3196   //  1 | 0 | 0 | X == Y
3197   //  1 | 1 | 1 | unordered
3198   switch (SetCCOpcode) {
3199   default: llvm_unreachable("Condcode should be pre-legalized away");
3200   case ISD::SETUEQ:
3201   case ISD::SETEQ:   return X86::COND_E;
3202   case ISD::SETOLT:              // flipped
3203   case ISD::SETOGT:
3204   case ISD::SETGT:   return X86::COND_A;
3205   case ISD::SETOLE:              // flipped
3206   case ISD::SETOGE:
3207   case ISD::SETGE:   return X86::COND_AE;
3208   case ISD::SETUGT:              // flipped
3209   case ISD::SETULT:
3210   case ISD::SETLT:   return X86::COND_B;
3211   case ISD::SETUGE:              // flipped
3212   case ISD::SETULE:
3213   case ISD::SETLE:   return X86::COND_BE;
3214   case ISD::SETONE:
3215   case ISD::SETNE:   return X86::COND_NE;
3216   case ISD::SETUO:   return X86::COND_P;
3217   case ISD::SETO:    return X86::COND_NP;
3218   case ISD::SETOEQ:
3219   case ISD::SETUNE:  return X86::COND_INVALID;
3220   }
3221 }
3222
3223 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3224 /// code. Current x86 isa includes the following FP cmov instructions:
3225 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3226 static bool hasFPCMov(unsigned X86CC) {
3227   switch (X86CC) {
3228   default:
3229     return false;
3230   case X86::COND_B:
3231   case X86::COND_BE:
3232   case X86::COND_E:
3233   case X86::COND_P:
3234   case X86::COND_A:
3235   case X86::COND_AE:
3236   case X86::COND_NE:
3237   case X86::COND_NP:
3238     return true;
3239   }
3240 }
3241
3242 /// isFPImmLegal - Returns true if the target can instruction select the
3243 /// specified FP immediate natively. If false, the legalizer will
3244 /// materialize the FP immediate as a load from a constant pool.
3245 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3246   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3247     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3248       return true;
3249   }
3250   return false;
3251 }
3252
3253 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3254 /// the specified range (L, H].
3255 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3256   return (Val < 0) || (Val >= Low && Val < Hi);
3257 }
3258
3259 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3260 /// specified value.
3261 static bool isUndefOrEqual(int Val, int CmpVal) {
3262   return (Val < 0 || Val == CmpVal);
3263 }
3264
3265 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3266 /// from position Pos and ending in Pos+Size, falls within the specified
3267 /// sequential range (L, L+Pos]. or is undef.
3268 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3269                                        unsigned Pos, unsigned Size, int Low) {
3270   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3271     if (!isUndefOrEqual(Mask[i], Low))
3272       return false;
3273   return true;
3274 }
3275
3276 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3277 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3278 /// the second operand.
3279 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3280   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3281     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3282   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3283     return (Mask[0] < 2 && Mask[1] < 2);
3284   return false;
3285 }
3286
3287 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3288 /// is suitable for input to PSHUFHW.
3289 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3290   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3291     return false;
3292
3293   // Lower quadword copied in order or undef.
3294   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3295     return false;
3296
3297   // Upper quadword shuffled.
3298   for (unsigned i = 4; i != 8; ++i)
3299     if (!isUndefOrInRange(Mask[i], 4, 8))
3300       return false;
3301
3302   if (VT == MVT::v16i16) {
3303     // Lower quadword copied in order or undef.
3304     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3305       return false;
3306
3307     // Upper quadword shuffled.
3308     for (unsigned i = 12; i != 16; ++i)
3309       if (!isUndefOrInRange(Mask[i], 12, 16))
3310         return false;
3311   }
3312
3313   return true;
3314 }
3315
3316 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PSHUFLW.
3318 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3319   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3320     return false;
3321
3322   // Upper quadword copied in order.
3323   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3324     return false;
3325
3326   // Lower quadword shuffled.
3327   for (unsigned i = 0; i != 4; ++i)
3328     if (!isUndefOrInRange(Mask[i], 0, 4))
3329       return false;
3330
3331   if (VT == MVT::v16i16) {
3332     // Upper quadword copied in order.
3333     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3334       return false;
3335
3336     // Lower quadword shuffled.
3337     for (unsigned i = 8; i != 12; ++i)
3338       if (!isUndefOrInRange(Mask[i], 8, 12))
3339         return false;
3340   }
3341
3342   return true;
3343 }
3344
3345 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3346 /// is suitable for input to PALIGNR.
3347 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3348                           const X86Subtarget *Subtarget) {
3349   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3350       (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3351     return false;
3352
3353   unsigned NumElts = VT.getVectorNumElements();
3354   unsigned NumLanes = VT.getSizeInBits()/128;
3355   unsigned NumLaneElts = NumElts/NumLanes;
3356
3357   // Do not handle 64-bit element shuffles with palignr.
3358   if (NumLaneElts == 2)
3359     return false;
3360
3361   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3362     unsigned i;
3363     for (i = 0; i != NumLaneElts; ++i) {
3364       if (Mask[i+l] >= 0)
3365         break;
3366     }
3367
3368     // Lane is all undef, go to next lane
3369     if (i == NumLaneElts)
3370       continue;
3371
3372     int Start = Mask[i+l];
3373
3374     // Make sure its in this lane in one of the sources
3375     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3376         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3377       return false;
3378
3379     // If not lane 0, then we must match lane 0
3380     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3381       return false;
3382
3383     // Correct second source to be contiguous with first source
3384     if (Start >= (int)NumElts)
3385       Start -= NumElts - NumLaneElts;
3386
3387     // Make sure we're shifting in the right direction.
3388     if (Start <= (int)(i+l))
3389       return false;
3390
3391     Start -= i;
3392
3393     // Check the rest of the elements to see if they are consecutive.
3394     for (++i; i != NumLaneElts; ++i) {
3395       int Idx = Mask[i+l];
3396
3397       // Make sure its in this lane
3398       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3399           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3400         return false;
3401
3402       // If not lane 0, then we must match lane 0
3403       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3404         return false;
3405
3406       if (Idx >= (int)NumElts)
3407         Idx -= NumElts - NumLaneElts;
3408
3409       if (!isUndefOrEqual(Idx, Start+i))
3410         return false;
3411
3412     }
3413   }
3414
3415   return true;
3416 }
3417
3418 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3419 /// the two vector operands have swapped position.
3420 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3421                                      unsigned NumElems) {
3422   for (unsigned i = 0; i != NumElems; ++i) {
3423     int idx = Mask[i];
3424     if (idx < 0)
3425       continue;
3426     else if (idx < (int)NumElems)
3427       Mask[i] = idx + NumElems;
3428     else
3429       Mask[i] = idx - NumElems;
3430   }
3431 }
3432
3433 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3434 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3435 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3436 /// reverse of what x86 shuffles want.
3437 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3438                         bool Commuted = false) {
3439   if (!HasFp256 && VT.getSizeInBits() == 256)
3440     return false;
3441
3442   unsigned NumElems = VT.getVectorNumElements();
3443   unsigned NumLanes = VT.getSizeInBits()/128;
3444   unsigned NumLaneElems = NumElems/NumLanes;
3445
3446   if (NumLaneElems != 2 && NumLaneElems != 4)
3447     return false;
3448
3449   // VSHUFPSY divides the resulting vector into 4 chunks.
3450   // The sources are also splitted into 4 chunks, and each destination
3451   // chunk must come from a different source chunk.
3452   //
3453   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3454   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3455   //
3456   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3457   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3458   //
3459   // VSHUFPDY divides the resulting vector into 4 chunks.
3460   // The sources are also splitted into 4 chunks, and each destination
3461   // chunk must come from a different source chunk.
3462   //
3463   //  SRC1 =>      X3       X2       X1       X0
3464   //  SRC2 =>      Y3       Y2       Y1       Y0
3465   //
3466   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3467   //
3468   unsigned HalfLaneElems = NumLaneElems/2;
3469   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3470     for (unsigned i = 0; i != NumLaneElems; ++i) {
3471       int Idx = Mask[i+l];
3472       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3473       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3474         return false;
3475       // For VSHUFPSY, the mask of the second half must be the same as the
3476       // first but with the appropriate offsets. This works in the same way as
3477       // VPERMILPS works with masks.
3478       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3479         continue;
3480       if (!isUndefOrEqual(Idx, Mask[i]+l))
3481         return false;
3482     }
3483   }
3484
3485   return true;
3486 }
3487
3488 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3490 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3491   if (!VT.is128BitVector())
3492     return false;
3493
3494   unsigned NumElems = VT.getVectorNumElements();
3495
3496   if (NumElems != 4)
3497     return false;
3498
3499   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3500   return isUndefOrEqual(Mask[0], 6) &&
3501          isUndefOrEqual(Mask[1], 7) &&
3502          isUndefOrEqual(Mask[2], 2) &&
3503          isUndefOrEqual(Mask[3], 3);
3504 }
3505
3506 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3507 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3508 /// <2, 3, 2, 3>
3509 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3510   if (!VT.is128BitVector())
3511     return false;
3512
3513   unsigned NumElems = VT.getVectorNumElements();
3514
3515   if (NumElems != 4)
3516     return false;
3517
3518   return isUndefOrEqual(Mask[0], 2) &&
3519          isUndefOrEqual(Mask[1], 3) &&
3520          isUndefOrEqual(Mask[2], 2) &&
3521          isUndefOrEqual(Mask[3], 3);
3522 }
3523
3524 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3525 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3526 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3527   if (!VT.is128BitVector())
3528     return false;
3529
3530   unsigned NumElems = VT.getVectorNumElements();
3531
3532   if (NumElems != 2 && NumElems != 4)
3533     return false;
3534
3535   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3536     if (!isUndefOrEqual(Mask[i], i + NumElems))
3537       return false;
3538
3539   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3540     if (!isUndefOrEqual(Mask[i], i))
3541       return false;
3542
3543   return true;
3544 }
3545
3546 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3548 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3549   if (!VT.is128BitVector())
3550     return false;
3551
3552   unsigned NumElems = VT.getVectorNumElements();
3553
3554   if (NumElems != 2 && NumElems != 4)
3555     return false;
3556
3557   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3558     if (!isUndefOrEqual(Mask[i], i))
3559       return false;
3560
3561   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3562     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3563       return false;
3564
3565   return true;
3566 }
3567
3568 //
3569 // Some special combinations that can be optimized.
3570 //
3571 static
3572 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3573                                SelectionDAG &DAG) {
3574   EVT VT = SVOp->getValueType(0);
3575   DebugLoc dl = SVOp->getDebugLoc();
3576
3577   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3578     return SDValue();
3579
3580   ArrayRef<int> Mask = SVOp->getMask();
3581
3582   // These are the special masks that may be optimized.
3583   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3584   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3585   bool MatchEvenMask = true;
3586   bool MatchOddMask  = true;
3587   for (int i=0; i<8; ++i) {
3588     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3589       MatchEvenMask = false;
3590     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3591       MatchOddMask = false;
3592   }
3593
3594   if (!MatchEvenMask && !MatchOddMask)
3595     return SDValue();
3596
3597   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3598
3599   SDValue Op0 = SVOp->getOperand(0);
3600   SDValue Op1 = SVOp->getOperand(1);
3601
3602   if (MatchEvenMask) {
3603     // Shift the second operand right to 32 bits.
3604     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3605     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3606   } else {
3607     // Shift the first operand left to 32 bits.
3608     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3609     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3610   }
3611   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3612   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3613 }
3614
3615 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3616 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3617 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3618                          bool HasInt256, bool V2IsSplat = false) {
3619   unsigned NumElts = VT.getVectorNumElements();
3620
3621   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3622          "Unsupported vector type for unpckh");
3623
3624   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3625       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3626     return false;
3627
3628   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3629   // independently on 128-bit lanes.
3630   unsigned NumLanes = VT.getSizeInBits()/128;
3631   unsigned NumLaneElts = NumElts/NumLanes;
3632
3633   for (unsigned l = 0; l != NumLanes; ++l) {
3634     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3635          i != (l+1)*NumLaneElts;
3636          i += 2, ++j) {
3637       int BitI  = Mask[i];
3638       int BitI1 = Mask[i+1];
3639       if (!isUndefOrEqual(BitI, j))
3640         return false;
3641       if (V2IsSplat) {
3642         if (!isUndefOrEqual(BitI1, NumElts))
3643           return false;
3644       } else {
3645         if (!isUndefOrEqual(BitI1, j + NumElts))
3646           return false;
3647       }
3648     }
3649   }
3650
3651   return true;
3652 }
3653
3654 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3655 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3656 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3657                          bool HasInt256, bool V2IsSplat = false) {
3658   unsigned NumElts = VT.getVectorNumElements();
3659
3660   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3661          "Unsupported vector type for unpckh");
3662
3663   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3664       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3665     return false;
3666
3667   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3668   // independently on 128-bit lanes.
3669   unsigned NumLanes = VT.getSizeInBits()/128;
3670   unsigned NumLaneElts = NumElts/NumLanes;
3671
3672   for (unsigned l = 0; l != NumLanes; ++l) {
3673     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3674          i != (l+1)*NumLaneElts; i += 2, ++j) {
3675       int BitI  = Mask[i];
3676       int BitI1 = Mask[i+1];
3677       if (!isUndefOrEqual(BitI, j))
3678         return false;
3679       if (V2IsSplat) {
3680         if (isUndefOrEqual(BitI1, NumElts))
3681           return false;
3682       } else {
3683         if (!isUndefOrEqual(BitI1, j+NumElts))
3684           return false;
3685       }
3686     }
3687   }
3688   return true;
3689 }
3690
3691 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3692 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3693 /// <0, 0, 1, 1>
3694 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3695                                   bool HasInt256) {
3696   unsigned NumElts = VT.getVectorNumElements();
3697
3698   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3699          "Unsupported vector type for unpckh");
3700
3701   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3702       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3703     return false;
3704
3705   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3706   // FIXME: Need a better way to get rid of this, there's no latency difference
3707   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3708   // the former later. We should also remove the "_undef" special mask.
3709   if (NumElts == 4 && VT.getSizeInBits() == 256)
3710     return false;
3711
3712   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3713   // independently on 128-bit lanes.
3714   unsigned NumLanes = VT.getSizeInBits()/128;
3715   unsigned NumLaneElts = NumElts/NumLanes;
3716
3717   for (unsigned l = 0; l != NumLanes; ++l) {
3718     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3719          i != (l+1)*NumLaneElts;
3720          i += 2, ++j) {
3721       int BitI  = Mask[i];
3722       int BitI1 = Mask[i+1];
3723
3724       if (!isUndefOrEqual(BitI, j))
3725         return false;
3726       if (!isUndefOrEqual(BitI1, j))
3727         return false;
3728     }
3729   }
3730
3731   return true;
3732 }
3733
3734 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3735 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3736 /// <2, 2, 3, 3>
3737 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3738   unsigned NumElts = VT.getVectorNumElements();
3739
3740   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3741          "Unsupported vector type for unpckh");
3742
3743   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3744       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3745     return false;
3746
3747   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3748   // independently on 128-bit lanes.
3749   unsigned NumLanes = VT.getSizeInBits()/128;
3750   unsigned NumLaneElts = NumElts/NumLanes;
3751
3752   for (unsigned l = 0; l != NumLanes; ++l) {
3753     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3754          i != (l+1)*NumLaneElts; i += 2, ++j) {
3755       int BitI  = Mask[i];
3756       int BitI1 = Mask[i+1];
3757       if (!isUndefOrEqual(BitI, j))
3758         return false;
3759       if (!isUndefOrEqual(BitI1, j))
3760         return false;
3761     }
3762   }
3763   return true;
3764 }
3765
3766 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3767 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3768 /// MOVSD, and MOVD, i.e. setting the lowest element.
3769 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3770   if (VT.getVectorElementType().getSizeInBits() < 32)
3771     return false;
3772   if (!VT.is128BitVector())
3773     return false;
3774
3775   unsigned NumElts = VT.getVectorNumElements();
3776
3777   if (!isUndefOrEqual(Mask[0], NumElts))
3778     return false;
3779
3780   for (unsigned i = 1; i != NumElts; ++i)
3781     if (!isUndefOrEqual(Mask[i], i))
3782       return false;
3783
3784   return true;
3785 }
3786
3787 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3788 /// as permutations between 128-bit chunks or halves. As an example: this
3789 /// shuffle bellow:
3790 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3791 /// The first half comes from the second half of V1 and the second half from the
3792 /// the second half of V2.
3793 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3794   if (!HasFp256 || !VT.is256BitVector())
3795     return false;
3796
3797   // The shuffle result is divided into half A and half B. In total the two
3798   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3799   // B must come from C, D, E or F.
3800   unsigned HalfSize = VT.getVectorNumElements()/2;
3801   bool MatchA = false, MatchB = false;
3802
3803   // Check if A comes from one of C, D, E, F.
3804   for (unsigned Half = 0; Half != 4; ++Half) {
3805     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3806       MatchA = true;
3807       break;
3808     }
3809   }
3810
3811   // Check if B comes from one of C, D, E, F.
3812   for (unsigned Half = 0; Half != 4; ++Half) {
3813     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3814       MatchB = true;
3815       break;
3816     }
3817   }
3818
3819   return MatchA && MatchB;
3820 }
3821
3822 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3823 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3824 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3825   EVT VT = SVOp->getValueType(0);
3826
3827   unsigned HalfSize = VT.getVectorNumElements()/2;
3828
3829   unsigned FstHalf = 0, SndHalf = 0;
3830   for (unsigned i = 0; i < HalfSize; ++i) {
3831     if (SVOp->getMaskElt(i) > 0) {
3832       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3833       break;
3834     }
3835   }
3836   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3837     if (SVOp->getMaskElt(i) > 0) {
3838       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3839       break;
3840     }
3841   }
3842
3843   return (FstHalf | (SndHalf << 4));
3844 }
3845
3846 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3848 /// Note that VPERMIL mask matching is different depending whether theunderlying
3849 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3850 /// to the same elements of the low, but to the higher half of the source.
3851 /// In VPERMILPD the two lanes could be shuffled independently of each other
3852 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3853 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3854   if (!HasFp256)
3855     return false;
3856
3857   unsigned NumElts = VT.getVectorNumElements();
3858   // Only match 256-bit with 32/64-bit types
3859   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3860     return false;
3861
3862   unsigned NumLanes = VT.getSizeInBits()/128;
3863   unsigned LaneSize = NumElts/NumLanes;
3864   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3865     for (unsigned i = 0; i != LaneSize; ++i) {
3866       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3867         return false;
3868       if (NumElts != 8 || l == 0)
3869         continue;
3870       // VPERMILPS handling
3871       if (Mask[i] < 0)
3872         continue;
3873       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3874         return false;
3875     }
3876   }
3877
3878   return true;
3879 }
3880
3881 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3882 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3883 /// element of vector 2 and the other elements to come from vector 1 in order.
3884 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3885                                bool V2IsSplat = false, bool V2IsUndef = false) {
3886   if (!VT.is128BitVector())
3887     return false;
3888
3889   unsigned NumOps = VT.getVectorNumElements();
3890   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3891     return false;
3892
3893   if (!isUndefOrEqual(Mask[0], 0))
3894     return false;
3895
3896   for (unsigned i = 1; i != NumOps; ++i)
3897     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3898           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3899           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3900       return false;
3901
3902   return true;
3903 }
3904
3905 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3907 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3908 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3909                            const X86Subtarget *Subtarget) {
3910   if (!Subtarget->hasSSE3())
3911     return false;
3912
3913   unsigned NumElems = VT.getVectorNumElements();
3914
3915   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3916       (VT.getSizeInBits() == 256 && NumElems != 8))
3917     return false;
3918
3919   // "i+1" is the value the indexed mask element must have
3920   for (unsigned i = 0; i != NumElems; i += 2)
3921     if (!isUndefOrEqual(Mask[i], i+1) ||
3922         !isUndefOrEqual(Mask[i+1], i+1))
3923       return false;
3924
3925   return true;
3926 }
3927
3928 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3930 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3931 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3932                            const X86Subtarget *Subtarget) {
3933   if (!Subtarget->hasSSE3())
3934     return false;
3935
3936   unsigned NumElems = VT.getVectorNumElements();
3937
3938   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3939       (VT.getSizeInBits() == 256 && NumElems != 8))
3940     return false;
3941
3942   // "i" is the value the indexed mask element must have
3943   for (unsigned i = 0; i != NumElems; i += 2)
3944     if (!isUndefOrEqual(Mask[i], i) ||
3945         !isUndefOrEqual(Mask[i+1], i))
3946       return false;
3947
3948   return true;
3949 }
3950
3951 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to 256-bit
3953 /// version of MOVDDUP.
3954 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3955   if (!HasFp256 || !VT.is256BitVector())
3956     return false;
3957
3958   unsigned NumElts = VT.getVectorNumElements();
3959   if (NumElts != 4)
3960     return false;
3961
3962   for (unsigned i = 0; i != NumElts/2; ++i)
3963     if (!isUndefOrEqual(Mask[i], 0))
3964       return false;
3965   for (unsigned i = NumElts/2; i != NumElts; ++i)
3966     if (!isUndefOrEqual(Mask[i], NumElts/2))
3967       return false;
3968   return true;
3969 }
3970
3971 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to 128-bit
3973 /// version of MOVDDUP.
3974 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3975   if (!VT.is128BitVector())
3976     return false;
3977
3978   unsigned e = VT.getVectorNumElements() / 2;
3979   for (unsigned i = 0; i != e; ++i)
3980     if (!isUndefOrEqual(Mask[i], i))
3981       return false;
3982   for (unsigned i = 0; i != e; ++i)
3983     if (!isUndefOrEqual(Mask[e+i], i))
3984       return false;
3985   return true;
3986 }
3987
3988 /// isVEXTRACTF128Index - Return true if the specified
3989 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3990 /// suitable for input to VEXTRACTF128.
3991 bool X86::isVEXTRACTF128Index(SDNode *N) {
3992   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3993     return false;
3994
3995   // The index should be aligned on a 128-bit boundary.
3996   uint64_t Index =
3997     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3998
3999   unsigned VL = N->getValueType(0).getVectorNumElements();
4000   unsigned VBits = N->getValueType(0).getSizeInBits();
4001   unsigned ElSize = VBits / VL;
4002   bool Result = (Index * ElSize) % 128 == 0;
4003
4004   return Result;
4005 }
4006
4007 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4008 /// operand specifies a subvector insert that is suitable for input to
4009 /// VINSERTF128.
4010 bool X86::isVINSERTF128Index(SDNode *N) {
4011   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4012     return false;
4013
4014   // The index should be aligned on a 128-bit boundary.
4015   uint64_t Index =
4016     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4017
4018   unsigned VL = N->getValueType(0).getVectorNumElements();
4019   unsigned VBits = N->getValueType(0).getSizeInBits();
4020   unsigned ElSize = VBits / VL;
4021   bool Result = (Index * ElSize) % 128 == 0;
4022
4023   return Result;
4024 }
4025
4026 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4027 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4028 /// Handles 128-bit and 256-bit.
4029 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4030   EVT VT = N->getValueType(0);
4031
4032   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4033          "Unsupported vector type for PSHUF/SHUFP");
4034
4035   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4036   // independently on 128-bit lanes.
4037   unsigned NumElts = VT.getVectorNumElements();
4038   unsigned NumLanes = VT.getSizeInBits()/128;
4039   unsigned NumLaneElts = NumElts/NumLanes;
4040
4041   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4042          "Only supports 2 or 4 elements per lane");
4043
4044   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4045   unsigned Mask = 0;
4046   for (unsigned i = 0; i != NumElts; ++i) {
4047     int Elt = N->getMaskElt(i);
4048     if (Elt < 0) continue;
4049     Elt &= NumLaneElts - 1;
4050     unsigned ShAmt = (i << Shift) % 8;
4051     Mask |= Elt << ShAmt;
4052   }
4053
4054   return Mask;
4055 }
4056
4057 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4058 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4059 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4060   EVT VT = N->getValueType(0);
4061
4062   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4063          "Unsupported vector type for PSHUFHW");
4064
4065   unsigned NumElts = VT.getVectorNumElements();
4066
4067   unsigned Mask = 0;
4068   for (unsigned l = 0; l != NumElts; l += 8) {
4069     // 8 nodes per lane, but we only care about the last 4.
4070     for (unsigned i = 0; i < 4; ++i) {
4071       int Elt = N->getMaskElt(l+i+4);
4072       if (Elt < 0) continue;
4073       Elt &= 0x3; // only 2-bits.
4074       Mask |= Elt << (i * 2);
4075     }
4076   }
4077
4078   return Mask;
4079 }
4080
4081 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4083 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4084   EVT VT = N->getValueType(0);
4085
4086   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4087          "Unsupported vector type for PSHUFHW");
4088
4089   unsigned NumElts = VT.getVectorNumElements();
4090
4091   unsigned Mask = 0;
4092   for (unsigned l = 0; l != NumElts; l += 8) {
4093     // 8 nodes per lane, but we only care about the first 4.
4094     for (unsigned i = 0; i < 4; ++i) {
4095       int Elt = N->getMaskElt(l+i);
4096       if (Elt < 0) continue;
4097       Elt &= 0x3; // only 2-bits
4098       Mask |= Elt << (i * 2);
4099     }
4100   }
4101
4102   return Mask;
4103 }
4104
4105 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4106 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4107 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4108   EVT VT = SVOp->getValueType(0);
4109   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4110
4111   unsigned NumElts = VT.getVectorNumElements();
4112   unsigned NumLanes = VT.getSizeInBits()/128;
4113   unsigned NumLaneElts = NumElts/NumLanes;
4114
4115   int Val = 0;
4116   unsigned i;
4117   for (i = 0; i != NumElts; ++i) {
4118     Val = SVOp->getMaskElt(i);
4119     if (Val >= 0)
4120       break;
4121   }
4122   if (Val >= (int)NumElts)
4123     Val -= NumElts - NumLaneElts;
4124
4125   assert(Val - i > 0 && "PALIGNR imm should be positive");
4126   return (Val - i) * EltSize;
4127 }
4128
4129 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4130 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4131 /// instructions.
4132 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4133   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4134     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4135
4136   uint64_t Index =
4137     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4138
4139   EVT VecVT = N->getOperand(0).getValueType();
4140   EVT ElVT = VecVT.getVectorElementType();
4141
4142   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4143   return Index / NumElemsPerChunk;
4144 }
4145
4146 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4147 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4148 /// instructions.
4149 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4150   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4151     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4152
4153   uint64_t Index =
4154     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4155
4156   EVT VecVT = N->getValueType(0);
4157   EVT ElVT = VecVT.getVectorElementType();
4158
4159   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4160   return Index / NumElemsPerChunk;
4161 }
4162
4163 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4164 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4165 /// Handles 256-bit.
4166 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4167   EVT VT = N->getValueType(0);
4168
4169   unsigned NumElts = VT.getVectorNumElements();
4170
4171   assert((VT.is256BitVector() && NumElts == 4) &&
4172          "Unsupported vector type for VPERMQ/VPERMPD");
4173
4174   unsigned Mask = 0;
4175   for (unsigned i = 0; i != NumElts; ++i) {
4176     int Elt = N->getMaskElt(i);
4177     if (Elt < 0)
4178       continue;
4179     Mask |= Elt << (i*2);
4180   }
4181
4182   return Mask;
4183 }
4184 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4185 /// constant +0.0.
4186 bool X86::isZeroNode(SDValue Elt) {
4187   return ((isa<ConstantSDNode>(Elt) &&
4188            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4189           (isa<ConstantFPSDNode>(Elt) &&
4190            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4191 }
4192
4193 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4194 /// their permute mask.
4195 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4196                                     SelectionDAG &DAG) {
4197   EVT VT = SVOp->getValueType(0);
4198   unsigned NumElems = VT.getVectorNumElements();
4199   SmallVector<int, 8> MaskVec;
4200
4201   for (unsigned i = 0; i != NumElems; ++i) {
4202     int Idx = SVOp->getMaskElt(i);
4203     if (Idx >= 0) {
4204       if (Idx < (int)NumElems)
4205         Idx += NumElems;
4206       else
4207         Idx -= NumElems;
4208     }
4209     MaskVec.push_back(Idx);
4210   }
4211   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4212                               SVOp->getOperand(0), &MaskVec[0]);
4213 }
4214
4215 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4216 /// match movhlps. The lower half elements should come from upper half of
4217 /// V1 (and in order), and the upper half elements should come from the upper
4218 /// half of V2 (and in order).
4219 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4220   if (!VT.is128BitVector())
4221     return false;
4222   if (VT.getVectorNumElements() != 4)
4223     return false;
4224   for (unsigned i = 0, e = 2; i != e; ++i)
4225     if (!isUndefOrEqual(Mask[i], i+2))
4226       return false;
4227   for (unsigned i = 2; i != 4; ++i)
4228     if (!isUndefOrEqual(Mask[i], i+4))
4229       return false;
4230   return true;
4231 }
4232
4233 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4234 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4235 /// required.
4236 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4237   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4238     return false;
4239   N = N->getOperand(0).getNode();
4240   if (!ISD::isNON_EXTLoad(N))
4241     return false;
4242   if (LD)
4243     *LD = cast<LoadSDNode>(N);
4244   return true;
4245 }
4246
4247 // Test whether the given value is a vector value which will be legalized
4248 // into a load.
4249 static bool WillBeConstantPoolLoad(SDNode *N) {
4250   if (N->getOpcode() != ISD::BUILD_VECTOR)
4251     return false;
4252
4253   // Check for any non-constant elements.
4254   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4255     switch (N->getOperand(i).getNode()->getOpcode()) {
4256     case ISD::UNDEF:
4257     case ISD::ConstantFP:
4258     case ISD::Constant:
4259       break;
4260     default:
4261       return false;
4262     }
4263
4264   // Vectors of all-zeros and all-ones are materialized with special
4265   // instructions rather than being loaded.
4266   return !ISD::isBuildVectorAllZeros(N) &&
4267          !ISD::isBuildVectorAllOnes(N);
4268 }
4269
4270 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4271 /// match movlp{s|d}. The lower half elements should come from lower half of
4272 /// V1 (and in order), and the upper half elements should come from the upper
4273 /// half of V2 (and in order). And since V1 will become the source of the
4274 /// MOVLP, it must be either a vector load or a scalar load to vector.
4275 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4276                                ArrayRef<int> Mask, EVT VT) {
4277   if (!VT.is128BitVector())
4278     return false;
4279
4280   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4281     return false;
4282   // Is V2 is a vector load, don't do this transformation. We will try to use
4283   // load folding shufps op.
4284   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4285     return false;
4286
4287   unsigned NumElems = VT.getVectorNumElements();
4288
4289   if (NumElems != 2 && NumElems != 4)
4290     return false;
4291   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4292     if (!isUndefOrEqual(Mask[i], i))
4293       return false;
4294   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4295     if (!isUndefOrEqual(Mask[i], i+NumElems))
4296       return false;
4297   return true;
4298 }
4299
4300 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4301 /// all the same.
4302 static bool isSplatVector(SDNode *N) {
4303   if (N->getOpcode() != ISD::BUILD_VECTOR)
4304     return false;
4305
4306   SDValue SplatValue = N->getOperand(0);
4307   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4308     if (N->getOperand(i) != SplatValue)
4309       return false;
4310   return true;
4311 }
4312
4313 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4314 /// to an zero vector.
4315 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4316 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4317   SDValue V1 = N->getOperand(0);
4318   SDValue V2 = N->getOperand(1);
4319   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4320   for (unsigned i = 0; i != NumElems; ++i) {
4321     int Idx = N->getMaskElt(i);
4322     if (Idx >= (int)NumElems) {
4323       unsigned Opc = V2.getOpcode();
4324       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4325         continue;
4326       if (Opc != ISD::BUILD_VECTOR ||
4327           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4328         return false;
4329     } else if (Idx >= 0) {
4330       unsigned Opc = V1.getOpcode();
4331       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4332         continue;
4333       if (Opc != ISD::BUILD_VECTOR ||
4334           !X86::isZeroNode(V1.getOperand(Idx)))
4335         return false;
4336     }
4337   }
4338   return true;
4339 }
4340
4341 /// getZeroVector - Returns a vector of specified type with all zero elements.
4342 ///
4343 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4344                              SelectionDAG &DAG, DebugLoc dl) {
4345   assert(VT.isVector() && "Expected a vector type");
4346   unsigned Size = VT.getSizeInBits();
4347
4348   // Always build SSE zero vectors as <4 x i32> bitcasted
4349   // to their dest type. This ensures they get CSE'd.
4350   SDValue Vec;
4351   if (Size == 128) {  // SSE
4352     if (Subtarget->hasSSE2()) {  // SSE2
4353       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4354       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4355     } else { // SSE1
4356       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4357       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4358     }
4359   } else if (Size == 256) { // AVX
4360     if (Subtarget->hasInt256()) { // AVX2
4361       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4363       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4364     } else {
4365       // 256-bit logic and arithmetic instructions in AVX are all
4366       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4367       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4368       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4369       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4370     }
4371   } else
4372     llvm_unreachable("Unexpected vector type");
4373
4374   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4375 }
4376
4377 /// getOnesVector - Returns a vector of specified type with all bits set.
4378 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4379 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4380 /// Then bitcast to their original type, ensuring they get CSE'd.
4381 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4382                              DebugLoc dl) {
4383   assert(VT.isVector() && "Expected a vector type");
4384   unsigned Size = VT.getSizeInBits();
4385
4386   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4387   SDValue Vec;
4388   if (Size == 256) {
4389     if (HasInt256) { // AVX2
4390       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4391       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4392     } else { // AVX
4393       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4394       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4395     }
4396   } else if (Size == 128) {
4397     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4398   } else
4399     llvm_unreachable("Unexpected vector type");
4400
4401   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4402 }
4403
4404 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4405 /// that point to V2 points to its first element.
4406 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4407   for (unsigned i = 0; i != NumElems; ++i) {
4408     if (Mask[i] > (int)NumElems) {
4409       Mask[i] = NumElems;
4410     }
4411   }
4412 }
4413
4414 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4415 /// operation of specified width.
4416 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4417                        SDValue V2) {
4418   unsigned NumElems = VT.getVectorNumElements();
4419   SmallVector<int, 8> Mask;
4420   Mask.push_back(NumElems);
4421   for (unsigned i = 1; i != NumElems; ++i)
4422     Mask.push_back(i);
4423   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4424 }
4425
4426 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4427 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4428                           SDValue V2) {
4429   unsigned NumElems = VT.getVectorNumElements();
4430   SmallVector<int, 8> Mask;
4431   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4432     Mask.push_back(i);
4433     Mask.push_back(i + NumElems);
4434   }
4435   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4436 }
4437
4438 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4439 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4440                           SDValue V2) {
4441   unsigned NumElems = VT.getVectorNumElements();
4442   SmallVector<int, 8> Mask;
4443   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4444     Mask.push_back(i + Half);
4445     Mask.push_back(i + NumElems + Half);
4446   }
4447   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4448 }
4449
4450 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4451 // a generic shuffle instruction because the target has no such instructions.
4452 // Generate shuffles which repeat i16 and i8 several times until they can be
4453 // represented by v4f32 and then be manipulated by target suported shuffles.
4454 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4455   EVT VT = V.getValueType();
4456   int NumElems = VT.getVectorNumElements();
4457   DebugLoc dl = V.getDebugLoc();
4458
4459   while (NumElems > 4) {
4460     if (EltNo < NumElems/2) {
4461       V = getUnpackl(DAG, dl, VT, V, V);
4462     } else {
4463       V = getUnpackh(DAG, dl, VT, V, V);
4464       EltNo -= NumElems/2;
4465     }
4466     NumElems >>= 1;
4467   }
4468   return V;
4469 }
4470
4471 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4472 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4473   EVT VT = V.getValueType();
4474   DebugLoc dl = V.getDebugLoc();
4475   unsigned Size = VT.getSizeInBits();
4476
4477   if (Size == 128) {
4478     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4479     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4480     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4481                              &SplatMask[0]);
4482   } else if (Size == 256) {
4483     // To use VPERMILPS to splat scalars, the second half of indicies must
4484     // refer to the higher part, which is a duplication of the lower one,
4485     // because VPERMILPS can only handle in-lane permutations.
4486     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4487                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4488
4489     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4490     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4491                              &SplatMask[0]);
4492   } else
4493     llvm_unreachable("Vector size not supported");
4494
4495   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4496 }
4497
4498 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4499 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4500   EVT SrcVT = SV->getValueType(0);
4501   SDValue V1 = SV->getOperand(0);
4502   DebugLoc dl = SV->getDebugLoc();
4503
4504   int EltNo = SV->getSplatIndex();
4505   int NumElems = SrcVT.getVectorNumElements();
4506   unsigned Size = SrcVT.getSizeInBits();
4507
4508   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4509           "Unknown how to promote splat for type");
4510
4511   // Extract the 128-bit part containing the splat element and update
4512   // the splat element index when it refers to the higher register.
4513   if (Size == 256) {
4514     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4515     if (EltNo >= NumElems/2)
4516       EltNo -= NumElems/2;
4517   }
4518
4519   // All i16 and i8 vector types can't be used directly by a generic shuffle
4520   // instruction because the target has no such instruction. Generate shuffles
4521   // which repeat i16 and i8 several times until they fit in i32, and then can
4522   // be manipulated by target suported shuffles.
4523   EVT EltVT = SrcVT.getVectorElementType();
4524   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4525     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4526
4527   // Recreate the 256-bit vector and place the same 128-bit vector
4528   // into the low and high part. This is necessary because we want
4529   // to use VPERM* to shuffle the vectors
4530   if (Size == 256) {
4531     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4532   }
4533
4534   return getLegalSplat(DAG, V1, EltNo);
4535 }
4536
4537 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4538 /// vector of zero or undef vector.  This produces a shuffle where the low
4539 /// element of V2 is swizzled into the zero/undef vector, landing at element
4540 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4541 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4542                                            bool IsZero,
4543                                            const X86Subtarget *Subtarget,
4544                                            SelectionDAG &DAG) {
4545   EVT VT = V2.getValueType();
4546   SDValue V1 = IsZero
4547     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4548   unsigned NumElems = VT.getVectorNumElements();
4549   SmallVector<int, 16> MaskVec;
4550   for (unsigned i = 0; i != NumElems; ++i)
4551     // If this is the insertion idx, put the low elt of V2 here.
4552     MaskVec.push_back(i == Idx ? NumElems : i);
4553   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4554 }
4555
4556 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4557 /// target specific opcode. Returns true if the Mask could be calculated.
4558 /// Sets IsUnary to true if only uses one source.
4559 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4560                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4561   unsigned NumElems = VT.getVectorNumElements();
4562   SDValue ImmN;
4563
4564   IsUnary = false;
4565   switch(N->getOpcode()) {
4566   case X86ISD::SHUFP:
4567     ImmN = N->getOperand(N->getNumOperands()-1);
4568     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4569     break;
4570   case X86ISD::UNPCKH:
4571     DecodeUNPCKHMask(VT, Mask);
4572     break;
4573   case X86ISD::UNPCKL:
4574     DecodeUNPCKLMask(VT, Mask);
4575     break;
4576   case X86ISD::MOVHLPS:
4577     DecodeMOVHLPSMask(NumElems, Mask);
4578     break;
4579   case X86ISD::MOVLHPS:
4580     DecodeMOVLHPSMask(NumElems, Mask);
4581     break;
4582   case X86ISD::PSHUFD:
4583   case X86ISD::VPERMILP:
4584     ImmN = N->getOperand(N->getNumOperands()-1);
4585     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4586     IsUnary = true;
4587     break;
4588   case X86ISD::PSHUFHW:
4589     ImmN = N->getOperand(N->getNumOperands()-1);
4590     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4591     IsUnary = true;
4592     break;
4593   case X86ISD::PSHUFLW:
4594     ImmN = N->getOperand(N->getNumOperands()-1);
4595     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596     IsUnary = true;
4597     break;
4598   case X86ISD::VPERMI:
4599     ImmN = N->getOperand(N->getNumOperands()-1);
4600     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601     IsUnary = true;
4602     break;
4603   case X86ISD::MOVSS:
4604   case X86ISD::MOVSD: {
4605     // The index 0 always comes from the first element of the second source,
4606     // this is why MOVSS and MOVSD are used in the first place. The other
4607     // elements come from the other positions of the first source vector
4608     Mask.push_back(NumElems);
4609     for (unsigned i = 1; i != NumElems; ++i) {
4610       Mask.push_back(i);
4611     }
4612     break;
4613   }
4614   case X86ISD::VPERM2X128:
4615     ImmN = N->getOperand(N->getNumOperands()-1);
4616     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617     if (Mask.empty()) return false;
4618     break;
4619   case X86ISD::MOVDDUP:
4620   case X86ISD::MOVLHPD:
4621   case X86ISD::MOVLPD:
4622   case X86ISD::MOVLPS:
4623   case X86ISD::MOVSHDUP:
4624   case X86ISD::MOVSLDUP:
4625   case X86ISD::PALIGN:
4626     // Not yet implemented
4627     return false;
4628   default: llvm_unreachable("unknown target shuffle node");
4629   }
4630
4631   return true;
4632 }
4633
4634 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4635 /// element of the result of the vector shuffle.
4636 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4637                                    unsigned Depth) {
4638   if (Depth == 6)
4639     return SDValue();  // Limit search depth.
4640
4641   SDValue V = SDValue(N, 0);
4642   EVT VT = V.getValueType();
4643   unsigned Opcode = V.getOpcode();
4644
4645   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4646   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4647     int Elt = SV->getMaskElt(Index);
4648
4649     if (Elt < 0)
4650       return DAG.getUNDEF(VT.getVectorElementType());
4651
4652     unsigned NumElems = VT.getVectorNumElements();
4653     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4654                                          : SV->getOperand(1);
4655     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4656   }
4657
4658   // Recurse into target specific vector shuffles to find scalars.
4659   if (isTargetShuffle(Opcode)) {
4660     MVT ShufVT = V.getValueType().getSimpleVT();
4661     unsigned NumElems = ShufVT.getVectorNumElements();
4662     SmallVector<int, 16> ShuffleMask;
4663     bool IsUnary;
4664
4665     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4666       return SDValue();
4667
4668     int Elt = ShuffleMask[Index];
4669     if (Elt < 0)
4670       return DAG.getUNDEF(ShufVT.getVectorElementType());
4671
4672     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4673                                          : N->getOperand(1);
4674     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4675                                Depth+1);
4676   }
4677
4678   // Actual nodes that may contain scalar elements
4679   if (Opcode == ISD::BITCAST) {
4680     V = V.getOperand(0);
4681     EVT SrcVT = V.getValueType();
4682     unsigned NumElems = VT.getVectorNumElements();
4683
4684     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4685       return SDValue();
4686   }
4687
4688   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4689     return (Index == 0) ? V.getOperand(0)
4690                         : DAG.getUNDEF(VT.getVectorElementType());
4691
4692   if (V.getOpcode() == ISD::BUILD_VECTOR)
4693     return V.getOperand(Index);
4694
4695   return SDValue();
4696 }
4697
4698 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4699 /// shuffle operation which come from a consecutively from a zero. The
4700 /// search can start in two different directions, from left or right.
4701 static
4702 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4703                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4704   unsigned i;
4705   for (i = 0; i != NumElems; ++i) {
4706     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4707     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4708     if (!(Elt.getNode() &&
4709          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4710       break;
4711   }
4712
4713   return i;
4714 }
4715
4716 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4717 /// correspond consecutively to elements from one of the vector operands,
4718 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4719 static
4720 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4721                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4722                               unsigned NumElems, unsigned &OpNum) {
4723   bool SeenV1 = false;
4724   bool SeenV2 = false;
4725
4726   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4727     int Idx = SVOp->getMaskElt(i);
4728     // Ignore undef indicies
4729     if (Idx < 0)
4730       continue;
4731
4732     if (Idx < (int)NumElems)
4733       SeenV1 = true;
4734     else
4735       SeenV2 = true;
4736
4737     // Only accept consecutive elements from the same vector
4738     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4739       return false;
4740   }
4741
4742   OpNum = SeenV1 ? 0 : 1;
4743   return true;
4744 }
4745
4746 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4747 /// logical left shift of a vector.
4748 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4749                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4750   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4751   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4752               false /* check zeros from right */, DAG);
4753   unsigned OpSrc;
4754
4755   if (!NumZeros)
4756     return false;
4757
4758   // Considering the elements in the mask that are not consecutive zeros,
4759   // check if they consecutively come from only one of the source vectors.
4760   //
4761   //               V1 = {X, A, B, C}     0
4762   //                         \  \  \    /
4763   //   vector_shuffle V1, V2 <1, 2, 3, X>
4764   //
4765   if (!isShuffleMaskConsecutive(SVOp,
4766             0,                   // Mask Start Index
4767             NumElems-NumZeros,   // Mask End Index(exclusive)
4768             NumZeros,            // Where to start looking in the src vector
4769             NumElems,            // Number of elements in vector
4770             OpSrc))              // Which source operand ?
4771     return false;
4772
4773   isLeft = false;
4774   ShAmt = NumZeros;
4775   ShVal = SVOp->getOperand(OpSrc);
4776   return true;
4777 }
4778
4779 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4780 /// logical left shift of a vector.
4781 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4782                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4783   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4784   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4785               true /* check zeros from left */, DAG);
4786   unsigned OpSrc;
4787
4788   if (!NumZeros)
4789     return false;
4790
4791   // Considering the elements in the mask that are not consecutive zeros,
4792   // check if they consecutively come from only one of the source vectors.
4793   //
4794   //                           0    { A, B, X, X } = V2
4795   //                          / \    /  /
4796   //   vector_shuffle V1, V2 <X, X, 4, 5>
4797   //
4798   if (!isShuffleMaskConsecutive(SVOp,
4799             NumZeros,     // Mask Start Index
4800             NumElems,     // Mask End Index(exclusive)
4801             0,            // Where to start looking in the src vector
4802             NumElems,     // Number of elements in vector
4803             OpSrc))       // Which source operand ?
4804     return false;
4805
4806   isLeft = true;
4807   ShAmt = NumZeros;
4808   ShVal = SVOp->getOperand(OpSrc);
4809   return true;
4810 }
4811
4812 /// isVectorShift - Returns true if the shuffle can be implemented as a
4813 /// logical left or right shift of a vector.
4814 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4815                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4816   // Although the logic below support any bitwidth size, there are no
4817   // shift instructions which handle more than 128-bit vectors.
4818   if (!SVOp->getValueType(0).is128BitVector())
4819     return false;
4820
4821   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4822       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4823     return true;
4824
4825   return false;
4826 }
4827
4828 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4829 ///
4830 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4831                                        unsigned NumNonZero, unsigned NumZero,
4832                                        SelectionDAG &DAG,
4833                                        const X86Subtarget* Subtarget,
4834                                        const TargetLowering &TLI) {
4835   if (NumNonZero > 8)
4836     return SDValue();
4837
4838   DebugLoc dl = Op.getDebugLoc();
4839   SDValue V(0, 0);
4840   bool First = true;
4841   for (unsigned i = 0; i < 16; ++i) {
4842     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4843     if (ThisIsNonZero && First) {
4844       if (NumZero)
4845         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4846       else
4847         V = DAG.getUNDEF(MVT::v8i16);
4848       First = false;
4849     }
4850
4851     if ((i & 1) != 0) {
4852       SDValue ThisElt(0, 0), LastElt(0, 0);
4853       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4854       if (LastIsNonZero) {
4855         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4856                               MVT::i16, Op.getOperand(i-1));
4857       }
4858       if (ThisIsNonZero) {
4859         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4860         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4861                               ThisElt, DAG.getConstant(8, MVT::i8));
4862         if (LastIsNonZero)
4863           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4864       } else
4865         ThisElt = LastElt;
4866
4867       if (ThisElt.getNode())
4868         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4869                         DAG.getIntPtrConstant(i/2));
4870     }
4871   }
4872
4873   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4874 }
4875
4876 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4877 ///
4878 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4879                                      unsigned NumNonZero, unsigned NumZero,
4880                                      SelectionDAG &DAG,
4881                                      const X86Subtarget* Subtarget,
4882                                      const TargetLowering &TLI) {
4883   if (NumNonZero > 4)
4884     return SDValue();
4885
4886   DebugLoc dl = Op.getDebugLoc();
4887   SDValue V(0, 0);
4888   bool First = true;
4889   for (unsigned i = 0; i < 8; ++i) {
4890     bool isNonZero = (NonZeros & (1 << i)) != 0;
4891     if (isNonZero) {
4892       if (First) {
4893         if (NumZero)
4894           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4895         else
4896           V = DAG.getUNDEF(MVT::v8i16);
4897         First = false;
4898       }
4899       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4900                       MVT::v8i16, V, Op.getOperand(i),
4901                       DAG.getIntPtrConstant(i));
4902     }
4903   }
4904
4905   return V;
4906 }
4907
4908 /// getVShift - Return a vector logical shift node.
4909 ///
4910 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4911                          unsigned NumBits, SelectionDAG &DAG,
4912                          const TargetLowering &TLI, DebugLoc dl) {
4913   assert(VT.is128BitVector() && "Unknown type for VShift");
4914   EVT ShVT = MVT::v2i64;
4915   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4916   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4917   return DAG.getNode(ISD::BITCAST, dl, VT,
4918                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4919                              DAG.getConstant(NumBits,
4920                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4921 }
4922
4923 SDValue
4924 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4925                                           SelectionDAG &DAG) const {
4926
4927   // Check if the scalar load can be widened into a vector load. And if
4928   // the address is "base + cst" see if the cst can be "absorbed" into
4929   // the shuffle mask.
4930   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4931     SDValue Ptr = LD->getBasePtr();
4932     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4933       return SDValue();
4934     EVT PVT = LD->getValueType(0);
4935     if (PVT != MVT::i32 && PVT != MVT::f32)
4936       return SDValue();
4937
4938     int FI = -1;
4939     int64_t Offset = 0;
4940     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4941       FI = FINode->getIndex();
4942       Offset = 0;
4943     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4944                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4945       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4946       Offset = Ptr.getConstantOperandVal(1);
4947       Ptr = Ptr.getOperand(0);
4948     } else {
4949       return SDValue();
4950     }
4951
4952     // FIXME: 256-bit vector instructions don't require a strict alignment,
4953     // improve this code to support it better.
4954     unsigned RequiredAlign = VT.getSizeInBits()/8;
4955     SDValue Chain = LD->getChain();
4956     // Make sure the stack object alignment is at least 16 or 32.
4957     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4958     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4959       if (MFI->isFixedObjectIndex(FI)) {
4960         // Can't change the alignment. FIXME: It's possible to compute
4961         // the exact stack offset and reference FI + adjust offset instead.
4962         // If someone *really* cares about this. That's the way to implement it.
4963         return SDValue();
4964       } else {
4965         MFI->setObjectAlignment(FI, RequiredAlign);
4966       }
4967     }
4968
4969     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4970     // Ptr + (Offset & ~15).
4971     if (Offset < 0)
4972       return SDValue();
4973     if ((Offset % RequiredAlign) & 3)
4974       return SDValue();
4975     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4976     if (StartOffset)
4977       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4978                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4979
4980     int EltNo = (Offset - StartOffset) >> 2;
4981     unsigned NumElems = VT.getVectorNumElements();
4982
4983     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4984     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4985                              LD->getPointerInfo().getWithOffset(StartOffset),
4986                              false, false, false, 0);
4987
4988     SmallVector<int, 8> Mask;
4989     for (unsigned i = 0; i != NumElems; ++i)
4990       Mask.push_back(EltNo);
4991
4992     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4993   }
4994
4995   return SDValue();
4996 }
4997
4998 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4999 /// vector of type 'VT', see if the elements can be replaced by a single large
5000 /// load which has the same value as a build_vector whose operands are 'elts'.
5001 ///
5002 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5003 ///
5004 /// FIXME: we'd also like to handle the case where the last elements are zero
5005 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5006 /// There's even a handy isZeroNode for that purpose.
5007 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5008                                         DebugLoc &DL, SelectionDAG &DAG) {
5009   EVT EltVT = VT.getVectorElementType();
5010   unsigned NumElems = Elts.size();
5011
5012   LoadSDNode *LDBase = NULL;
5013   unsigned LastLoadedElt = -1U;
5014
5015   // For each element in the initializer, see if we've found a load or an undef.
5016   // If we don't find an initial load element, or later load elements are
5017   // non-consecutive, bail out.
5018   for (unsigned i = 0; i < NumElems; ++i) {
5019     SDValue Elt = Elts[i];
5020
5021     if (!Elt.getNode() ||
5022         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5023       return SDValue();
5024     if (!LDBase) {
5025       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5026         return SDValue();
5027       LDBase = cast<LoadSDNode>(Elt.getNode());
5028       LastLoadedElt = i;
5029       continue;
5030     }
5031     if (Elt.getOpcode() == ISD::UNDEF)
5032       continue;
5033
5034     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5035     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5036       return SDValue();
5037     LastLoadedElt = i;
5038   }
5039
5040   // If we have found an entire vector of loads and undefs, then return a large
5041   // load of the entire vector width starting at the base pointer.  If we found
5042   // consecutive loads for the low half, generate a vzext_load node.
5043   if (LastLoadedElt == NumElems - 1) {
5044     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5045       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5046                          LDBase->getPointerInfo(),
5047                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5048                          LDBase->isInvariant(), 0);
5049     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5050                        LDBase->getPointerInfo(),
5051                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5052                        LDBase->isInvariant(), LDBase->getAlignment());
5053   }
5054   if (NumElems == 4 && LastLoadedElt == 1 &&
5055       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5056     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5057     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5058     SDValue ResNode =
5059         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5060                                 LDBase->getPointerInfo(),
5061                                 LDBase->getAlignment(),
5062                                 false/*isVolatile*/, true/*ReadMem*/,
5063                                 false/*WriteMem*/);
5064
5065     // Make sure the newly-created LOAD is in the same position as LDBase in
5066     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5067     // update uses of LDBase's output chain to use the TokenFactor.
5068     if (LDBase->hasAnyUseOfValue(1)) {
5069       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5070                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5071       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5072       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5073                              SDValue(ResNode.getNode(), 1));
5074     }
5075
5076     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5077   }
5078   return SDValue();
5079 }
5080
5081 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5082 /// to generate a splat value for the following cases:
5083 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5084 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5085 /// a scalar load, or a constant.
5086 /// The VBROADCAST node is returned when a pattern is found,
5087 /// or SDValue() otherwise.
5088 SDValue
5089 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5090   if (!Subtarget->hasFp256())
5091     return SDValue();
5092
5093   EVT VT = Op.getValueType();
5094   DebugLoc dl = Op.getDebugLoc();
5095
5096   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5097          "Unsupported vector type for broadcast.");
5098
5099   SDValue Ld;
5100   bool ConstSplatVal;
5101
5102   switch (Op.getOpcode()) {
5103     default:
5104       // Unknown pattern found.
5105       return SDValue();
5106
5107     case ISD::BUILD_VECTOR: {
5108       // The BUILD_VECTOR node must be a splat.
5109       if (!isSplatVector(Op.getNode()))
5110         return SDValue();
5111
5112       Ld = Op.getOperand(0);
5113       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5114                      Ld.getOpcode() == ISD::ConstantFP);
5115
5116       // The suspected load node has several users. Make sure that all
5117       // of its users are from the BUILD_VECTOR node.
5118       // Constants may have multiple users.
5119       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5120         return SDValue();
5121       break;
5122     }
5123
5124     case ISD::VECTOR_SHUFFLE: {
5125       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5126
5127       // Shuffles must have a splat mask where the first element is
5128       // broadcasted.
5129       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5130         return SDValue();
5131
5132       SDValue Sc = Op.getOperand(0);
5133       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5134           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5135
5136         if (!Subtarget->hasInt256())
5137           return SDValue();
5138
5139         // Use the register form of the broadcast instruction available on AVX2.
5140         if (VT.is256BitVector())
5141           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5142         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5143       }
5144
5145       Ld = Sc.getOperand(0);
5146       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5147                        Ld.getOpcode() == ISD::ConstantFP);
5148
5149       // The scalar_to_vector node and the suspected
5150       // load node must have exactly one user.
5151       // Constants may have multiple users.
5152       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5153         return SDValue();
5154       break;
5155     }
5156   }
5157
5158   bool Is256 = VT.is256BitVector();
5159
5160   // Handle the broadcasting a single constant scalar from the constant pool
5161   // into a vector. On Sandybridge it is still better to load a constant vector
5162   // from the constant pool and not to broadcast it from a scalar.
5163   if (ConstSplatVal && Subtarget->hasInt256()) {
5164     EVT CVT = Ld.getValueType();
5165     assert(!CVT.isVector() && "Must not broadcast a vector type");
5166     unsigned ScalarSize = CVT.getSizeInBits();
5167
5168     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5169       const Constant *C = 0;
5170       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5171         C = CI->getConstantIntValue();
5172       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5173         C = CF->getConstantFPValue();
5174
5175       assert(C && "Invalid constant type");
5176
5177       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5178       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5179       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5180                        MachinePointerInfo::getConstantPool(),
5181                        false, false, false, Alignment);
5182
5183       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5184     }
5185   }
5186
5187   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5188   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5189
5190   // Handle AVX2 in-register broadcasts.
5191   if (!IsLoad && Subtarget->hasInt256() &&
5192       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5193     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5194
5195   // The scalar source must be a normal load.
5196   if (!IsLoad)
5197     return SDValue();
5198
5199   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5200     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5201
5202   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5203   // double since there is no vbroadcastsd xmm
5204   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5205     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5206       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5207   }
5208
5209   // Unsupported broadcast.
5210   return SDValue();
5211 }
5212
5213 SDValue
5214 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5215   EVT VT = Op.getValueType();
5216
5217   // Skip if insert_vec_elt is not supported.
5218   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5219     return SDValue();
5220
5221   DebugLoc DL = Op.getDebugLoc();
5222   unsigned NumElems = Op.getNumOperands();
5223
5224   SDValue VecIn1;
5225   SDValue VecIn2;
5226   SmallVector<unsigned, 4> InsertIndices;
5227   SmallVector<int, 8> Mask(NumElems, -1);
5228
5229   for (unsigned i = 0; i != NumElems; ++i) {
5230     unsigned Opc = Op.getOperand(i).getOpcode();
5231
5232     if (Opc == ISD::UNDEF)
5233       continue;
5234
5235     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5236       // Quit if more than 1 elements need inserting.
5237       if (InsertIndices.size() > 1)
5238         return SDValue();
5239
5240       InsertIndices.push_back(i);
5241       continue;
5242     }
5243
5244     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5245     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5246
5247     // Quit if extracted from vector of different type.
5248     if (ExtractedFromVec.getValueType() != VT)
5249       return SDValue();
5250
5251     // Quit if non-constant index.
5252     if (!isa<ConstantSDNode>(ExtIdx))
5253       return SDValue();
5254
5255     if (VecIn1.getNode() == 0)
5256       VecIn1 = ExtractedFromVec;
5257     else if (VecIn1 != ExtractedFromVec) {
5258       if (VecIn2.getNode() == 0)
5259         VecIn2 = ExtractedFromVec;
5260       else if (VecIn2 != ExtractedFromVec)
5261         // Quit if more than 2 vectors to shuffle
5262         return SDValue();
5263     }
5264
5265     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5266
5267     if (ExtractedFromVec == VecIn1)
5268       Mask[i] = Idx;
5269     else if (ExtractedFromVec == VecIn2)
5270       Mask[i] = Idx + NumElems;
5271   }
5272
5273   if (VecIn1.getNode() == 0)
5274     return SDValue();
5275
5276   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5277   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5278   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5279     unsigned Idx = InsertIndices[i];
5280     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5281                      DAG.getIntPtrConstant(Idx));
5282   }
5283
5284   return NV;
5285 }
5286
5287 SDValue
5288 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5289   DebugLoc dl = Op.getDebugLoc();
5290
5291   EVT VT = Op.getValueType();
5292   EVT ExtVT = VT.getVectorElementType();
5293   unsigned NumElems = Op.getNumOperands();
5294
5295   // Vectors containing all zeros can be matched by pxor and xorps later
5296   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5297     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5298     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5299     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5300       return Op;
5301
5302     return getZeroVector(VT, Subtarget, DAG, dl);
5303   }
5304
5305   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5306   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5307   // vpcmpeqd on 256-bit vectors.
5308   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5309     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5310       return Op;
5311
5312     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5313   }
5314
5315   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5316   if (Broadcast.getNode())
5317     return Broadcast;
5318
5319   unsigned EVTBits = ExtVT.getSizeInBits();
5320
5321   unsigned NumZero  = 0;
5322   unsigned NumNonZero = 0;
5323   unsigned NonZeros = 0;
5324   bool IsAllConstants = true;
5325   SmallSet<SDValue, 8> Values;
5326   for (unsigned i = 0; i < NumElems; ++i) {
5327     SDValue Elt = Op.getOperand(i);
5328     if (Elt.getOpcode() == ISD::UNDEF)
5329       continue;
5330     Values.insert(Elt);
5331     if (Elt.getOpcode() != ISD::Constant &&
5332         Elt.getOpcode() != ISD::ConstantFP)
5333       IsAllConstants = false;
5334     if (X86::isZeroNode(Elt))
5335       NumZero++;
5336     else {
5337       NonZeros |= (1 << i);
5338       NumNonZero++;
5339     }
5340   }
5341
5342   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5343   if (NumNonZero == 0)
5344     return DAG.getUNDEF(VT);
5345
5346   // Special case for single non-zero, non-undef, element.
5347   if (NumNonZero == 1) {
5348     unsigned Idx = CountTrailingZeros_32(NonZeros);
5349     SDValue Item = Op.getOperand(Idx);
5350
5351     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5352     // the value are obviously zero, truncate the value to i32 and do the
5353     // insertion that way.  Only do this if the value is non-constant or if the
5354     // value is a constant being inserted into element 0.  It is cheaper to do
5355     // a constant pool load than it is to do a movd + shuffle.
5356     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5357         (!IsAllConstants || Idx == 0)) {
5358       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5359         // Handle SSE only.
5360         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5361         EVT VecVT = MVT::v4i32;
5362         unsigned VecElts = 4;
5363
5364         // Truncate the value (which may itself be a constant) to i32, and
5365         // convert it to a vector with movd (S2V+shuffle to zero extend).
5366         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5367         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5368         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5369
5370         // Now we have our 32-bit value zero extended in the low element of
5371         // a vector.  If Idx != 0, swizzle it into place.
5372         if (Idx != 0) {
5373           SmallVector<int, 4> Mask;
5374           Mask.push_back(Idx);
5375           for (unsigned i = 1; i != VecElts; ++i)
5376             Mask.push_back(i);
5377           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5378                                       &Mask[0]);
5379         }
5380         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5381       }
5382     }
5383
5384     // If we have a constant or non-constant insertion into the low element of
5385     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5386     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5387     // depending on what the source datatype is.
5388     if (Idx == 0) {
5389       if (NumZero == 0)
5390         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5391
5392       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5393           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5394         if (VT.is256BitVector()) {
5395           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5396           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5397                              Item, DAG.getIntPtrConstant(0));
5398         }
5399         assert(VT.is128BitVector() && "Expected an SSE value type!");
5400         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5401         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5402         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5403       }
5404
5405       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5406         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5407         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5408         if (VT.is256BitVector()) {
5409           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5410           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5411         } else {
5412           assert(VT.is128BitVector() && "Expected an SSE value type!");
5413           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5414         }
5415         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5416       }
5417     }
5418
5419     // Is it a vector logical left shift?
5420     if (NumElems == 2 && Idx == 1 &&
5421         X86::isZeroNode(Op.getOperand(0)) &&
5422         !X86::isZeroNode(Op.getOperand(1))) {
5423       unsigned NumBits = VT.getSizeInBits();
5424       return getVShift(true, VT,
5425                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5426                                    VT, Op.getOperand(1)),
5427                        NumBits/2, DAG, *this, dl);
5428     }
5429
5430     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5431       return SDValue();
5432
5433     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5434     // is a non-constant being inserted into an element other than the low one,
5435     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5436     // movd/movss) to move this into the low element, then shuffle it into
5437     // place.
5438     if (EVTBits == 32) {
5439       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5440
5441       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5442       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5443       SmallVector<int, 8> MaskVec;
5444       for (unsigned i = 0; i != NumElems; ++i)
5445         MaskVec.push_back(i == Idx ? 0 : 1);
5446       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5447     }
5448   }
5449
5450   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5451   if (Values.size() == 1) {
5452     if (EVTBits == 32) {
5453       // Instead of a shuffle like this:
5454       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5455       // Check if it's possible to issue this instead.
5456       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5457       unsigned Idx = CountTrailingZeros_32(NonZeros);
5458       SDValue Item = Op.getOperand(Idx);
5459       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5460         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5461     }
5462     return SDValue();
5463   }
5464
5465   // A vector full of immediates; various special cases are already
5466   // handled, so this is best done with a single constant-pool load.
5467   if (IsAllConstants)
5468     return SDValue();
5469
5470   // For AVX-length vectors, build the individual 128-bit pieces and use
5471   // shuffles to put them in place.
5472   if (VT.is256BitVector()) {
5473     SmallVector<SDValue, 32> V;
5474     for (unsigned i = 0; i != NumElems; ++i)
5475       V.push_back(Op.getOperand(i));
5476
5477     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5478
5479     // Build both the lower and upper subvector.
5480     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5481     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5482                                 NumElems/2);
5483
5484     // Recreate the wider vector with the lower and upper part.
5485     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5486   }
5487
5488   // Let legalizer expand 2-wide build_vectors.
5489   if (EVTBits == 64) {
5490     if (NumNonZero == 1) {
5491       // One half is zero or undef.
5492       unsigned Idx = CountTrailingZeros_32(NonZeros);
5493       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5494                                  Op.getOperand(Idx));
5495       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5496     }
5497     return SDValue();
5498   }
5499
5500   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5501   if (EVTBits == 8 && NumElems == 16) {
5502     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5503                                         Subtarget, *this);
5504     if (V.getNode()) return V;
5505   }
5506
5507   if (EVTBits == 16 && NumElems == 8) {
5508     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5509                                       Subtarget, *this);
5510     if (V.getNode()) return V;
5511   }
5512
5513   // If element VT is == 32 bits, turn it into a number of shuffles.
5514   SmallVector<SDValue, 8> V(NumElems);
5515   if (NumElems == 4 && NumZero > 0) {
5516     for (unsigned i = 0; i < 4; ++i) {
5517       bool isZero = !(NonZeros & (1 << i));
5518       if (isZero)
5519         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5520       else
5521         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5522     }
5523
5524     for (unsigned i = 0; i < 2; ++i) {
5525       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5526         default: break;
5527         case 0:
5528           V[i] = V[i*2];  // Must be a zero vector.
5529           break;
5530         case 1:
5531           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5532           break;
5533         case 2:
5534           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5535           break;
5536         case 3:
5537           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5538           break;
5539       }
5540     }
5541
5542     bool Reverse1 = (NonZeros & 0x3) == 2;
5543     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5544     int MaskVec[] = {
5545       Reverse1 ? 1 : 0,
5546       Reverse1 ? 0 : 1,
5547       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5548       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5549     };
5550     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5551   }
5552
5553   if (Values.size() > 1 && VT.is128BitVector()) {
5554     // Check for a build vector of consecutive loads.
5555     for (unsigned i = 0; i < NumElems; ++i)
5556       V[i] = Op.getOperand(i);
5557
5558     // Check for elements which are consecutive loads.
5559     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5560     if (LD.getNode())
5561       return LD;
5562
5563     // Check for a build vector from mostly shuffle plus few inserting.
5564     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5565     if (Sh.getNode())
5566       return Sh;
5567
5568     // For SSE 4.1, use insertps to put the high elements into the low element.
5569     if (getSubtarget()->hasSSE41()) {
5570       SDValue Result;
5571       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5572         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5573       else
5574         Result = DAG.getUNDEF(VT);
5575
5576       for (unsigned i = 1; i < NumElems; ++i) {
5577         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5578         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5579                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5580       }
5581       return Result;
5582     }
5583
5584     // Otherwise, expand into a number of unpckl*, start by extending each of
5585     // our (non-undef) elements to the full vector width with the element in the
5586     // bottom slot of the vector (which generates no code for SSE).
5587     for (unsigned i = 0; i < NumElems; ++i) {
5588       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5589         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5590       else
5591         V[i] = DAG.getUNDEF(VT);
5592     }
5593
5594     // Next, we iteratively mix elements, e.g. for v4f32:
5595     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5596     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5597     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5598     unsigned EltStride = NumElems >> 1;
5599     while (EltStride != 0) {
5600       for (unsigned i = 0; i < EltStride; ++i) {
5601         // If V[i+EltStride] is undef and this is the first round of mixing,
5602         // then it is safe to just drop this shuffle: V[i] is already in the
5603         // right place, the one element (since it's the first round) being
5604         // inserted as undef can be dropped.  This isn't safe for successive
5605         // rounds because they will permute elements within both vectors.
5606         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5607             EltStride == NumElems/2)
5608           continue;
5609
5610         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5611       }
5612       EltStride >>= 1;
5613     }
5614     return V[0];
5615   }
5616   return SDValue();
5617 }
5618
5619 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5620 // to create 256-bit vectors from two other 128-bit ones.
5621 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5622   DebugLoc dl = Op.getDebugLoc();
5623   EVT ResVT = Op.getValueType();
5624
5625   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5626
5627   SDValue V1 = Op.getOperand(0);
5628   SDValue V2 = Op.getOperand(1);
5629   unsigned NumElems = ResVT.getVectorNumElements();
5630
5631   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5632 }
5633
5634 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5635   assert(Op.getNumOperands() == 2);
5636
5637   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5638   // from two other 128-bit ones.
5639   return LowerAVXCONCAT_VECTORS(Op, DAG);
5640 }
5641
5642 // Try to lower a shuffle node into a simple blend instruction.
5643 static SDValue
5644 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5645                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5646   SDValue V1 = SVOp->getOperand(0);
5647   SDValue V2 = SVOp->getOperand(1);
5648   DebugLoc dl = SVOp->getDebugLoc();
5649   EVT VT = SVOp->getValueType(0);
5650   EVT EltVT = VT.getVectorElementType();
5651   unsigned NumElems = VT.getVectorNumElements();
5652
5653   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5654     return SDValue();
5655   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5656     return SDValue();
5657
5658   // Check the mask for BLEND and build the value.
5659   unsigned MaskValue = 0;
5660   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5661   unsigned NumLanes = (NumElems-1)/8 + 1; 
5662   unsigned NumElemsInLane = NumElems / NumLanes;
5663
5664   // Blend for v16i16 should be symetric for the both lanes.
5665   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5666
5667     int SndLaneEltIdx = (NumLanes == 2) ? 
5668       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5669     int EltIdx = SVOp->getMaskElt(i);
5670
5671     if ((EltIdx == -1 || EltIdx == (int)i) && 
5672         (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5673       continue;
5674
5675     if (((unsigned)EltIdx == (i + NumElems)) && 
5676         (SndLaneEltIdx == -1 || 
5677          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5678       MaskValue |= (1<<i);
5679     else 
5680       return SDValue();
5681   }
5682
5683   // Convert i32 vectors to floating point if it is not AVX2.
5684   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5685   EVT BlendVT = VT;
5686   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5687     BlendVT = EVT::getVectorVT(*DAG.getContext(), 
5688                               EVT::getFloatingPointVT(EltVT.getSizeInBits()), 
5689                               NumElems);
5690     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5691     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5692   }
5693   
5694   SDValue Ret =  DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5695                              DAG.getConstant(MaskValue, MVT::i32));
5696   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5697 }
5698
5699 // v8i16 shuffles - Prefer shuffles in the following order:
5700 // 1. [all]   pshuflw, pshufhw, optional move
5701 // 2. [ssse3] 1 x pshufb
5702 // 3. [ssse3] 2 x pshufb + 1 x por
5703 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5704 static SDValue
5705 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5706                          SelectionDAG &DAG) {
5707   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5708   SDValue V1 = SVOp->getOperand(0);
5709   SDValue V2 = SVOp->getOperand(1);
5710   DebugLoc dl = SVOp->getDebugLoc();
5711   SmallVector<int, 8> MaskVals;
5712
5713   // Determine if more than 1 of the words in each of the low and high quadwords
5714   // of the result come from the same quadword of one of the two inputs.  Undef
5715   // mask values count as coming from any quadword, for better codegen.
5716   unsigned LoQuad[] = { 0, 0, 0, 0 };
5717   unsigned HiQuad[] = { 0, 0, 0, 0 };
5718   std::bitset<4> InputQuads;
5719   for (unsigned i = 0; i < 8; ++i) {
5720     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5721     int EltIdx = SVOp->getMaskElt(i);
5722     MaskVals.push_back(EltIdx);
5723     if (EltIdx < 0) {
5724       ++Quad[0];
5725       ++Quad[1];
5726       ++Quad[2];
5727       ++Quad[3];
5728       continue;
5729     }
5730     ++Quad[EltIdx / 4];
5731     InputQuads.set(EltIdx / 4);
5732   }
5733
5734   int BestLoQuad = -1;
5735   unsigned MaxQuad = 1;
5736   for (unsigned i = 0; i < 4; ++i) {
5737     if (LoQuad[i] > MaxQuad) {
5738       BestLoQuad = i;
5739       MaxQuad = LoQuad[i];
5740     }
5741   }
5742
5743   int BestHiQuad = -1;
5744   MaxQuad = 1;
5745   for (unsigned i = 0; i < 4; ++i) {
5746     if (HiQuad[i] > MaxQuad) {
5747       BestHiQuad = i;
5748       MaxQuad = HiQuad[i];
5749     }
5750   }
5751
5752   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5753   // of the two input vectors, shuffle them into one input vector so only a
5754   // single pshufb instruction is necessary. If There are more than 2 input
5755   // quads, disable the next transformation since it does not help SSSE3.
5756   bool V1Used = InputQuads[0] || InputQuads[1];
5757   bool V2Used = InputQuads[2] || InputQuads[3];
5758   if (Subtarget->hasSSSE3()) {
5759     if (InputQuads.count() == 2 && V1Used && V2Used) {
5760       BestLoQuad = InputQuads[0] ? 0 : 1;
5761       BestHiQuad = InputQuads[2] ? 2 : 3;
5762     }
5763     if (InputQuads.count() > 2) {
5764       BestLoQuad = -1;
5765       BestHiQuad = -1;
5766     }
5767   }
5768
5769   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5770   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5771   // words from all 4 input quadwords.
5772   SDValue NewV;
5773   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5774     int MaskV[] = {
5775       BestLoQuad < 0 ? 0 : BestLoQuad,
5776       BestHiQuad < 0 ? 1 : BestHiQuad
5777     };
5778     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5779                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5780                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5781     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5782
5783     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5784     // source words for the shuffle, to aid later transformations.
5785     bool AllWordsInNewV = true;
5786     bool InOrder[2] = { true, true };
5787     for (unsigned i = 0; i != 8; ++i) {
5788       int idx = MaskVals[i];
5789       if (idx != (int)i)
5790         InOrder[i/4] = false;
5791       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5792         continue;
5793       AllWordsInNewV = false;
5794       break;
5795     }
5796
5797     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5798     if (AllWordsInNewV) {
5799       for (int i = 0; i != 8; ++i) {
5800         int idx = MaskVals[i];
5801         if (idx < 0)
5802           continue;
5803         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5804         if ((idx != i) && idx < 4)
5805           pshufhw = false;
5806         if ((idx != i) && idx > 3)
5807           pshuflw = false;
5808       }
5809       V1 = NewV;
5810       V2Used = false;
5811       BestLoQuad = 0;
5812       BestHiQuad = 1;
5813     }
5814
5815     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5816     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5817     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5818       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5819       unsigned TargetMask = 0;
5820       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5821                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5822       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5823       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5824                              getShufflePSHUFLWImmediate(SVOp);
5825       V1 = NewV.getOperand(0);
5826       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5827     }
5828   }
5829
5830   // If we have SSSE3, and all words of the result are from 1 input vector,
5831   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5832   // is present, fall back to case 4.
5833   if (Subtarget->hasSSSE3()) {
5834     SmallVector<SDValue,16> pshufbMask;
5835
5836     // If we have elements from both input vectors, set the high bit of the
5837     // shuffle mask element to zero out elements that come from V2 in the V1
5838     // mask, and elements that come from V1 in the V2 mask, so that the two
5839     // results can be OR'd together.
5840     bool TwoInputs = V1Used && V2Used;
5841     for (unsigned i = 0; i != 8; ++i) {
5842       int EltIdx = MaskVals[i] * 2;
5843       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5844       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5845       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5846       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5847     }
5848     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5849     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5850                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5851                                  MVT::v16i8, &pshufbMask[0], 16));
5852     if (!TwoInputs)
5853       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5854
5855     // Calculate the shuffle mask for the second input, shuffle it, and
5856     // OR it with the first shuffled input.
5857     pshufbMask.clear();
5858     for (unsigned i = 0; i != 8; ++i) {
5859       int EltIdx = MaskVals[i] * 2;
5860       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5861       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5862       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5863       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5864     }
5865     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5866     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5867                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5868                                  MVT::v16i8, &pshufbMask[0], 16));
5869     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5870     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5871   }
5872
5873   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5874   // and update MaskVals with new element order.
5875   std::bitset<8> InOrder;
5876   if (BestLoQuad >= 0) {
5877     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5878     for (int i = 0; i != 4; ++i) {
5879       int idx = MaskVals[i];
5880       if (idx < 0) {
5881         InOrder.set(i);
5882       } else if ((idx / 4) == BestLoQuad) {
5883         MaskV[i] = idx & 3;
5884         InOrder.set(i);
5885       }
5886     }
5887     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5888                                 &MaskV[0]);
5889
5890     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5891       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5892       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5893                                   NewV.getOperand(0),
5894                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5895     }
5896   }
5897
5898   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5899   // and update MaskVals with the new element order.
5900   if (BestHiQuad >= 0) {
5901     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5902     for (unsigned i = 4; i != 8; ++i) {
5903       int idx = MaskVals[i];
5904       if (idx < 0) {
5905         InOrder.set(i);
5906       } else if ((idx / 4) == BestHiQuad) {
5907         MaskV[i] = (idx & 3) + 4;
5908         InOrder.set(i);
5909       }
5910     }
5911     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5912                                 &MaskV[0]);
5913
5914     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5915       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5916       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5917                                   NewV.getOperand(0),
5918                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5919     }
5920   }
5921
5922   // In case BestHi & BestLo were both -1, which means each quadword has a word
5923   // from each of the four input quadwords, calculate the InOrder bitvector now
5924   // before falling through to the insert/extract cleanup.
5925   if (BestLoQuad == -1 && BestHiQuad == -1) {
5926     NewV = V1;
5927     for (int i = 0; i != 8; ++i)
5928       if (MaskVals[i] < 0 || MaskVals[i] == i)
5929         InOrder.set(i);
5930   }
5931
5932   // The other elements are put in the right place using pextrw and pinsrw.
5933   for (unsigned i = 0; i != 8; ++i) {
5934     if (InOrder[i])
5935       continue;
5936     int EltIdx = MaskVals[i];
5937     if (EltIdx < 0)
5938       continue;
5939     SDValue ExtOp = (EltIdx < 8) ?
5940       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5941                   DAG.getIntPtrConstant(EltIdx)) :
5942       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5943                   DAG.getIntPtrConstant(EltIdx - 8));
5944     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5945                        DAG.getIntPtrConstant(i));
5946   }
5947   return NewV;
5948 }
5949
5950 // v16i8 shuffles - Prefer shuffles in the following order:
5951 // 1. [ssse3] 1 x pshufb
5952 // 2. [ssse3] 2 x pshufb + 1 x por
5953 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5954 static
5955 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5956                                  SelectionDAG &DAG,
5957                                  const X86TargetLowering &TLI) {
5958   SDValue V1 = SVOp->getOperand(0);
5959   SDValue V2 = SVOp->getOperand(1);
5960   DebugLoc dl = SVOp->getDebugLoc();
5961   ArrayRef<int> MaskVals = SVOp->getMask();
5962
5963   // If we have SSSE3, case 1 is generated when all result bytes come from
5964   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5965   // present, fall back to case 3.
5966
5967   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5968   if (TLI.getSubtarget()->hasSSSE3()) {
5969     SmallVector<SDValue,16> pshufbMask;
5970
5971     // If all result elements are from one input vector, then only translate
5972     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5973     //
5974     // Otherwise, we have elements from both input vectors, and must zero out
5975     // elements that come from V2 in the first mask, and V1 in the second mask
5976     // so that we can OR them together.
5977     for (unsigned i = 0; i != 16; ++i) {
5978       int EltIdx = MaskVals[i];
5979       if (EltIdx < 0 || EltIdx >= 16)
5980         EltIdx = 0x80;
5981       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5982     }
5983     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5984                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5985                                  MVT::v16i8, &pshufbMask[0], 16));
5986
5987     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5988     // the 2nd operand if it's undefined or zero.
5989     if (V2.getOpcode() == ISD::UNDEF ||
5990         ISD::isBuildVectorAllZeros(V2.getNode()))
5991       return V1;
5992
5993     // Calculate the shuffle mask for the second input, shuffle it, and
5994     // OR it with the first shuffled input.
5995     pshufbMask.clear();
5996     for (unsigned i = 0; i != 16; ++i) {
5997       int EltIdx = MaskVals[i];
5998       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5999       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6000     }
6001     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6002                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6003                                  MVT::v16i8, &pshufbMask[0], 16));
6004     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6005   }
6006
6007   // No SSSE3 - Calculate in place words and then fix all out of place words
6008   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6009   // the 16 different words that comprise the two doublequadword input vectors.
6010   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6011   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6012   SDValue NewV = V1;
6013   for (int i = 0; i != 8; ++i) {
6014     int Elt0 = MaskVals[i*2];
6015     int Elt1 = MaskVals[i*2+1];
6016
6017     // This word of the result is all undef, skip it.
6018     if (Elt0 < 0 && Elt1 < 0)
6019       continue;
6020
6021     // This word of the result is already in the correct place, skip it.
6022     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6023       continue;
6024
6025     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6026     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6027     SDValue InsElt;
6028
6029     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6030     // using a single extract together, load it and store it.
6031     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6032       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6033                            DAG.getIntPtrConstant(Elt1 / 2));
6034       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6035                         DAG.getIntPtrConstant(i));
6036       continue;
6037     }
6038
6039     // If Elt1 is defined, extract it from the appropriate source.  If the
6040     // source byte is not also odd, shift the extracted word left 8 bits
6041     // otherwise clear the bottom 8 bits if we need to do an or.
6042     if (Elt1 >= 0) {
6043       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6044                            DAG.getIntPtrConstant(Elt1 / 2));
6045       if ((Elt1 & 1) == 0)
6046         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6047                              DAG.getConstant(8,
6048                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6049       else if (Elt0 >= 0)
6050         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6051                              DAG.getConstant(0xFF00, MVT::i16));
6052     }
6053     // If Elt0 is defined, extract it from the appropriate source.  If the
6054     // source byte is not also even, shift the extracted word right 8 bits. If
6055     // Elt1 was also defined, OR the extracted values together before
6056     // inserting them in the result.
6057     if (Elt0 >= 0) {
6058       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6059                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6060       if ((Elt0 & 1) != 0)
6061         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6062                               DAG.getConstant(8,
6063                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6064       else if (Elt1 >= 0)
6065         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6066                              DAG.getConstant(0x00FF, MVT::i16));
6067       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6068                          : InsElt0;
6069     }
6070     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6071                        DAG.getIntPtrConstant(i));
6072   }
6073   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6074 }
6075
6076 // v32i8 shuffles - Translate to VPSHUFB if possible.
6077 static
6078 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6079                                  const X86Subtarget *Subtarget,
6080                                  SelectionDAG &DAG) {
6081   EVT VT = SVOp->getValueType(0);
6082   SDValue V1 = SVOp->getOperand(0);
6083   SDValue V2 = SVOp->getOperand(1);
6084   DebugLoc dl = SVOp->getDebugLoc();
6085   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6086
6087   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6088   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6089   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6090
6091   // VPSHUFB may be generated if
6092   // (1) one of input vector is undefined or zeroinitializer.
6093   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6094   // And (2) the mask indexes don't cross the 128-bit lane.
6095   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6096       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6097     return SDValue();
6098
6099   if (V1IsAllZero && !V2IsAllZero) {
6100     CommuteVectorShuffleMask(MaskVals, 32);
6101     V1 = V2;
6102   }
6103   SmallVector<SDValue, 32> pshufbMask;
6104   for (unsigned i = 0; i != 32; i++) {
6105     int EltIdx = MaskVals[i];
6106     if (EltIdx < 0 || EltIdx >= 32)
6107       EltIdx = 0x80;
6108     else {
6109       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6110         // Cross lane is not allowed.
6111         return SDValue();
6112       EltIdx &= 0xf;
6113     }
6114     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6115   }
6116   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6117                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6118                                   MVT::v32i8, &pshufbMask[0], 32));
6119 }
6120
6121 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6122 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6123 /// done when every pair / quad of shuffle mask elements point to elements in
6124 /// the right sequence. e.g.
6125 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6126 static
6127 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6128                                  SelectionDAG &DAG, DebugLoc dl) {
6129   MVT VT = SVOp->getValueType(0).getSimpleVT();
6130   unsigned NumElems = VT.getVectorNumElements();
6131   MVT NewVT;
6132   unsigned Scale;
6133   switch (VT.SimpleTy) {
6134   default: llvm_unreachable("Unexpected!");
6135   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6136   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6137   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6138   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6139   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6140   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6141   }
6142
6143   SmallVector<int, 8> MaskVec;
6144   for (unsigned i = 0; i != NumElems; i += Scale) {
6145     int StartIdx = -1;
6146     for (unsigned j = 0; j != Scale; ++j) {
6147       int EltIdx = SVOp->getMaskElt(i+j);
6148       if (EltIdx < 0)
6149         continue;
6150       if (StartIdx < 0)
6151         StartIdx = (EltIdx / Scale);
6152       if (EltIdx != (int)(StartIdx*Scale + j))
6153         return SDValue();
6154     }
6155     MaskVec.push_back(StartIdx);
6156   }
6157
6158   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6159   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6160   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6161 }
6162
6163 /// getVZextMovL - Return a zero-extending vector move low node.
6164 ///
6165 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6166                             SDValue SrcOp, SelectionDAG &DAG,
6167                             const X86Subtarget *Subtarget, DebugLoc dl) {
6168   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6169     LoadSDNode *LD = NULL;
6170     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6171       LD = dyn_cast<LoadSDNode>(SrcOp);
6172     if (!LD) {
6173       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6174       // instead.
6175       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6176       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6177           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6178           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6179           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6180         // PR2108
6181         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6182         return DAG.getNode(ISD::BITCAST, dl, VT,
6183                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6184                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6185                                                    OpVT,
6186                                                    SrcOp.getOperand(0)
6187                                                           .getOperand(0))));
6188       }
6189     }
6190   }
6191
6192   return DAG.getNode(ISD::BITCAST, dl, VT,
6193                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6194                                  DAG.getNode(ISD::BITCAST, dl,
6195                                              OpVT, SrcOp)));
6196 }
6197
6198 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6199 /// which could not be matched by any known target speficic shuffle
6200 static SDValue
6201 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6202
6203   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6204   if (NewOp.getNode())
6205     return NewOp;
6206
6207   EVT VT = SVOp->getValueType(0);
6208
6209   unsigned NumElems = VT.getVectorNumElements();
6210   unsigned NumLaneElems = NumElems / 2;
6211
6212   DebugLoc dl = SVOp->getDebugLoc();
6213   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6214   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6215   SDValue Output[2];
6216
6217   SmallVector<int, 16> Mask;
6218   for (unsigned l = 0; l < 2; ++l) {
6219     // Build a shuffle mask for the output, discovering on the fly which
6220     // input vectors to use as shuffle operands (recorded in InputUsed).
6221     // If building a suitable shuffle vector proves too hard, then bail
6222     // out with UseBuildVector set.
6223     bool UseBuildVector = false;
6224     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6225     unsigned LaneStart = l * NumLaneElems;
6226     for (unsigned i = 0; i != NumLaneElems; ++i) {
6227       // The mask element.  This indexes into the input.
6228       int Idx = SVOp->getMaskElt(i+LaneStart);
6229       if (Idx < 0) {
6230         // the mask element does not index into any input vector.
6231         Mask.push_back(-1);
6232         continue;
6233       }
6234
6235       // The input vector this mask element indexes into.
6236       int Input = Idx / NumLaneElems;
6237
6238       // Turn the index into an offset from the start of the input vector.
6239       Idx -= Input * NumLaneElems;
6240
6241       // Find or create a shuffle vector operand to hold this input.
6242       unsigned OpNo;
6243       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6244         if (InputUsed[OpNo] == Input)
6245           // This input vector is already an operand.
6246           break;
6247         if (InputUsed[OpNo] < 0) {
6248           // Create a new operand for this input vector.
6249           InputUsed[OpNo] = Input;
6250           break;
6251         }
6252       }
6253
6254       if (OpNo >= array_lengthof(InputUsed)) {
6255         // More than two input vectors used!  Give up on trying to create a
6256         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6257         UseBuildVector = true;
6258         break;
6259       }
6260
6261       // Add the mask index for the new shuffle vector.
6262       Mask.push_back(Idx + OpNo * NumLaneElems);
6263     }
6264
6265     if (UseBuildVector) {
6266       SmallVector<SDValue, 16> SVOps;
6267       for (unsigned i = 0; i != NumLaneElems; ++i) {
6268         // The mask element.  This indexes into the input.
6269         int Idx = SVOp->getMaskElt(i+LaneStart);
6270         if (Idx < 0) {
6271           SVOps.push_back(DAG.getUNDEF(EltVT));
6272           continue;
6273         }
6274
6275         // The input vector this mask element indexes into.
6276         int Input = Idx / NumElems;
6277
6278         // Turn the index into an offset from the start of the input vector.
6279         Idx -= Input * NumElems;
6280
6281         // Extract the vector element by hand.
6282         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6283                                     SVOp->getOperand(Input),
6284                                     DAG.getIntPtrConstant(Idx)));
6285       }
6286
6287       // Construct the output using a BUILD_VECTOR.
6288       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6289                               SVOps.size());
6290     } else if (InputUsed[0] < 0) {
6291       // No input vectors were used! The result is undefined.
6292       Output[l] = DAG.getUNDEF(NVT);
6293     } else {
6294       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6295                                         (InputUsed[0] % 2) * NumLaneElems,
6296                                         DAG, dl);
6297       // If only one input was used, use an undefined vector for the other.
6298       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6299         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6300                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6301       // At least one input vector was used. Create a new shuffle vector.
6302       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6303     }
6304
6305     Mask.clear();
6306   }
6307
6308   // Concatenate the result back
6309   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6310 }
6311
6312 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6313 /// 4 elements, and match them with several different shuffle types.
6314 static SDValue
6315 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6316   SDValue V1 = SVOp->getOperand(0);
6317   SDValue V2 = SVOp->getOperand(1);
6318   DebugLoc dl = SVOp->getDebugLoc();
6319   EVT VT = SVOp->getValueType(0);
6320
6321   assert(VT.is128BitVector() && "Unsupported vector size");
6322
6323   std::pair<int, int> Locs[4];
6324   int Mask1[] = { -1, -1, -1, -1 };
6325   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6326
6327   unsigned NumHi = 0;
6328   unsigned NumLo = 0;
6329   for (unsigned i = 0; i != 4; ++i) {
6330     int Idx = PermMask[i];
6331     if (Idx < 0) {
6332       Locs[i] = std::make_pair(-1, -1);
6333     } else {
6334       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6335       if (Idx < 4) {
6336         Locs[i] = std::make_pair(0, NumLo);
6337         Mask1[NumLo] = Idx;
6338         NumLo++;
6339       } else {
6340         Locs[i] = std::make_pair(1, NumHi);
6341         if (2+NumHi < 4)
6342           Mask1[2+NumHi] = Idx;
6343         NumHi++;
6344       }
6345     }
6346   }
6347
6348   if (NumLo <= 2 && NumHi <= 2) {
6349     // If no more than two elements come from either vector. This can be
6350     // implemented with two shuffles. First shuffle gather the elements.
6351     // The second shuffle, which takes the first shuffle as both of its
6352     // vector operands, put the elements into the right order.
6353     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6354
6355     int Mask2[] = { -1, -1, -1, -1 };
6356
6357     for (unsigned i = 0; i != 4; ++i)
6358       if (Locs[i].first != -1) {
6359         unsigned Idx = (i < 2) ? 0 : 4;
6360         Idx += Locs[i].first * 2 + Locs[i].second;
6361         Mask2[i] = Idx;
6362       }
6363
6364     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6365   }
6366
6367   if (NumLo == 3 || NumHi == 3) {
6368     // Otherwise, we must have three elements from one vector, call it X, and
6369     // one element from the other, call it Y.  First, use a shufps to build an
6370     // intermediate vector with the one element from Y and the element from X
6371     // that will be in the same half in the final destination (the indexes don't
6372     // matter). Then, use a shufps to build the final vector, taking the half
6373     // containing the element from Y from the intermediate, and the other half
6374     // from X.
6375     if (NumHi == 3) {
6376       // Normalize it so the 3 elements come from V1.
6377       CommuteVectorShuffleMask(PermMask, 4);
6378       std::swap(V1, V2);
6379     }
6380
6381     // Find the element from V2.
6382     unsigned HiIndex;
6383     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6384       int Val = PermMask[HiIndex];
6385       if (Val < 0)
6386         continue;
6387       if (Val >= 4)
6388         break;
6389     }
6390
6391     Mask1[0] = PermMask[HiIndex];
6392     Mask1[1] = -1;
6393     Mask1[2] = PermMask[HiIndex^1];
6394     Mask1[3] = -1;
6395     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6396
6397     if (HiIndex >= 2) {
6398       Mask1[0] = PermMask[0];
6399       Mask1[1] = PermMask[1];
6400       Mask1[2] = HiIndex & 1 ? 6 : 4;
6401       Mask1[3] = HiIndex & 1 ? 4 : 6;
6402       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6403     }
6404
6405     Mask1[0] = HiIndex & 1 ? 2 : 0;
6406     Mask1[1] = HiIndex & 1 ? 0 : 2;
6407     Mask1[2] = PermMask[2];
6408     Mask1[3] = PermMask[3];
6409     if (Mask1[2] >= 0)
6410       Mask1[2] += 4;
6411     if (Mask1[3] >= 0)
6412       Mask1[3] += 4;
6413     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6414   }
6415
6416   // Break it into (shuffle shuffle_hi, shuffle_lo).
6417   int LoMask[] = { -1, -1, -1, -1 };
6418   int HiMask[] = { -1, -1, -1, -1 };
6419
6420   int *MaskPtr = LoMask;
6421   unsigned MaskIdx = 0;
6422   unsigned LoIdx = 0;
6423   unsigned HiIdx = 2;
6424   for (unsigned i = 0; i != 4; ++i) {
6425     if (i == 2) {
6426       MaskPtr = HiMask;
6427       MaskIdx = 1;
6428       LoIdx = 0;
6429       HiIdx = 2;
6430     }
6431     int Idx = PermMask[i];
6432     if (Idx < 0) {
6433       Locs[i] = std::make_pair(-1, -1);
6434     } else if (Idx < 4) {
6435       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6436       MaskPtr[LoIdx] = Idx;
6437       LoIdx++;
6438     } else {
6439       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6440       MaskPtr[HiIdx] = Idx;
6441       HiIdx++;
6442     }
6443   }
6444
6445   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6446   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6447   int MaskOps[] = { -1, -1, -1, -1 };
6448   for (unsigned i = 0; i != 4; ++i)
6449     if (Locs[i].first != -1)
6450       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6451   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6452 }
6453
6454 static bool MayFoldVectorLoad(SDValue V) {
6455   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6456     V = V.getOperand(0);
6457
6458   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6459     V = V.getOperand(0);
6460   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6461       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6462     // BUILD_VECTOR (load), undef
6463     V = V.getOperand(0);
6464
6465   return MayFoldLoad(V);
6466 }
6467
6468 static
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470   EVT VT = Op.getValueType();
6471
6472   // Canonizalize to v2f64.
6473   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474   return DAG.getNode(ISD::BITCAST, dl, VT,
6475                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6476                                           V1, DAG));
6477 }
6478
6479 static
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6481                         bool HasSSE2) {
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484   EVT VT = Op.getValueType();
6485
6486   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6487
6488   if (HasSSE2 && VT == MVT::v2f64)
6489     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6490
6491   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492   return DAG.getNode(ISD::BITCAST, dl, VT,
6493                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6496 }
6497
6498 static
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500   SDValue V1 = Op.getOperand(0);
6501   SDValue V2 = Op.getOperand(1);
6502   EVT VT = Op.getValueType();
6503
6504   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505          "unsupported shuffle type");
6506
6507   if (V2.getOpcode() == ISD::UNDEF)
6508     V2 = V1;
6509
6510   // v4i32 or v4f32
6511   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6512 }
6513
6514 static
6515 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6516   SDValue V1 = Op.getOperand(0);
6517   SDValue V2 = Op.getOperand(1);
6518   EVT VT = Op.getValueType();
6519   unsigned NumElems = VT.getVectorNumElements();
6520
6521   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6522   // operand of these instructions is only memory, so check if there's a
6523   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6524   // same masks.
6525   bool CanFoldLoad = false;
6526
6527   // Trivial case, when V2 comes from a load.
6528   if (MayFoldVectorLoad(V2))
6529     CanFoldLoad = true;
6530
6531   // When V1 is a load, it can be folded later into a store in isel, example:
6532   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6533   //    turns into:
6534   //  (MOVLPSmr addr:$src1, VR128:$src2)
6535   // So, recognize this potential and also use MOVLPS or MOVLPD
6536   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6537     CanFoldLoad = true;
6538
6539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6540   if (CanFoldLoad) {
6541     if (HasSSE2 && NumElems == 2)
6542       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6543
6544     if (NumElems == 4)
6545       // If we don't care about the second element, proceed to use movss.
6546       if (SVOp->getMaskElt(1) != -1)
6547         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6548   }
6549
6550   // movl and movlp will both match v2i64, but v2i64 is never matched by
6551   // movl earlier because we make it strict to avoid messing with the movlp load
6552   // folding logic (see the code above getMOVLP call). Match it here then,
6553   // this is horrible, but will stay like this until we move all shuffle
6554   // matching to x86 specific nodes. Note that for the 1st condition all
6555   // types are matched with movsd.
6556   if (HasSSE2) {
6557     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6558     // as to remove this logic from here, as much as possible
6559     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6560       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6561     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6562   }
6563
6564   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6565
6566   // Invert the operand order and use SHUFPS to match it.
6567   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6568                               getShuffleSHUFImmediate(SVOp), DAG);
6569 }
6570
6571 // Reduce a vector shuffle to zext.
6572 SDValue
6573 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6574   // PMOVZX is only available from SSE41.
6575   if (!Subtarget->hasSSE41())
6576     return SDValue();
6577
6578   EVT VT = Op.getValueType();
6579
6580   // Only AVX2 support 256-bit vector integer extending.
6581   if (!Subtarget->hasInt256() && VT.is256BitVector())
6582     return SDValue();
6583
6584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6585   DebugLoc DL = Op.getDebugLoc();
6586   SDValue V1 = Op.getOperand(0);
6587   SDValue V2 = Op.getOperand(1);
6588   unsigned NumElems = VT.getVectorNumElements();
6589
6590   // Extending is an unary operation and the element type of the source vector
6591   // won't be equal to or larger than i64.
6592   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6593       VT.getVectorElementType() == MVT::i64)
6594     return SDValue();
6595
6596   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6597   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6598   while ((1U << Shift) < NumElems) {
6599     if (SVOp->getMaskElt(1U << Shift) == 1)
6600       break;
6601     Shift += 1;
6602     // The maximal ratio is 8, i.e. from i8 to i64.
6603     if (Shift > 3)
6604       return SDValue();
6605   }
6606
6607   // Check the shuffle mask.
6608   unsigned Mask = (1U << Shift) - 1;
6609   for (unsigned i = 0; i != NumElems; ++i) {
6610     int EltIdx = SVOp->getMaskElt(i);
6611     if ((i & Mask) != 0 && EltIdx != -1)
6612       return SDValue();
6613     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6614       return SDValue();
6615   }
6616
6617   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6618   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6619   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6620
6621   if (!isTypeLegal(NVT))
6622     return SDValue();
6623
6624   // Simplify the operand as it's prepared to be fed into shuffle.
6625   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6626   if (V1.getOpcode() == ISD::BITCAST &&
6627       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6628       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6629       V1.getOperand(0)
6630         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6631     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6632     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6633     ConstantSDNode *CIdx =
6634       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6635     // If it's foldable, i.e. normal load with single use, we will let code
6636     // selection to fold it. Otherwise, we will short the conversion sequence.
6637     if (CIdx && CIdx->getZExtValue() == 0 &&
6638         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6639       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6640   }
6641
6642   return DAG.getNode(ISD::BITCAST, DL, VT,
6643                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6644 }
6645
6646 SDValue
6647 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6648   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6649   EVT VT = Op.getValueType();
6650   DebugLoc dl = Op.getDebugLoc();
6651   SDValue V1 = Op.getOperand(0);
6652   SDValue V2 = Op.getOperand(1);
6653
6654   if (isZeroShuffle(SVOp))
6655     return getZeroVector(VT, Subtarget, DAG, dl);
6656
6657   // Handle splat operations
6658   if (SVOp->isSplat()) {
6659     unsigned NumElem = VT.getVectorNumElements();
6660     int Size = VT.getSizeInBits();
6661
6662     // Use vbroadcast whenever the splat comes from a foldable load
6663     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6664     if (Broadcast.getNode())
6665       return Broadcast;
6666
6667     // Handle splats by matching through known shuffle masks
6668     if ((Size == 128 && NumElem <= 4) ||
6669         (Size == 256 && NumElem <= 8))
6670       return SDValue();
6671
6672     // All remaning splats are promoted to target supported vector shuffles.
6673     return PromoteSplat(SVOp, DAG);
6674   }
6675
6676   // Check integer expanding shuffles.
6677   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6678   if (NewOp.getNode())
6679     return NewOp;
6680
6681   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6682   // do it!
6683   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6684       VT == MVT::v16i16 || VT == MVT::v32i8) {
6685     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6686     if (NewOp.getNode())
6687       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6688   } else if ((VT == MVT::v4i32 ||
6689              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6690     // FIXME: Figure out a cleaner way to do this.
6691     // Try to make use of movq to zero out the top part.
6692     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6693       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694       if (NewOp.getNode()) {
6695         EVT NewVT = NewOp.getValueType();
6696         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6697                                NewVT, true, false))
6698           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6699                               DAG, Subtarget, dl);
6700       }
6701     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6702       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6703       if (NewOp.getNode()) {
6704         EVT NewVT = NewOp.getValueType();
6705         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6706           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6707                               DAG, Subtarget, dl);
6708       }
6709     }
6710   }
6711   return SDValue();
6712 }
6713
6714 SDValue
6715 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6717   SDValue V1 = Op.getOperand(0);
6718   SDValue V2 = Op.getOperand(1);
6719   EVT VT = Op.getValueType();
6720   DebugLoc dl = Op.getDebugLoc();
6721   unsigned NumElems = VT.getVectorNumElements();
6722   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6723   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6724   bool V1IsSplat = false;
6725   bool V2IsSplat = false;
6726   bool HasSSE2 = Subtarget->hasSSE2();
6727   bool HasFp256    = Subtarget->hasFp256();
6728   bool HasInt256   = Subtarget->hasInt256();
6729   MachineFunction &MF = DAG.getMachineFunction();
6730   bool OptForSize = MF.getFunction()->getFnAttributes().
6731     hasAttribute(Attribute::OptimizeForSize);
6732
6733   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6734
6735   if (V1IsUndef && V2IsUndef)
6736     return DAG.getUNDEF(VT);
6737
6738   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6739
6740   // Vector shuffle lowering takes 3 steps:
6741   //
6742   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6743   //    narrowing and commutation of operands should be handled.
6744   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6745   //    shuffle nodes.
6746   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6747   //    so the shuffle can be broken into other shuffles and the legalizer can
6748   //    try the lowering again.
6749   //
6750   // The general idea is that no vector_shuffle operation should be left to
6751   // be matched during isel, all of them must be converted to a target specific
6752   // node here.
6753
6754   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6755   // narrowing and commutation of operands should be handled. The actual code
6756   // doesn't include all of those, work in progress...
6757   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6758   if (NewOp.getNode())
6759     return NewOp;
6760
6761   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6762
6763   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6764   // unpckh_undef). Only use pshufd if speed is more important than size.
6765   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6766     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6767   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6768     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6769
6770   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6771       V2IsUndef && MayFoldVectorLoad(V1))
6772     return getMOVDDup(Op, dl, V1, DAG);
6773
6774   if (isMOVHLPS_v_undef_Mask(M, VT))
6775     return getMOVHighToLow(Op, dl, DAG);
6776
6777   // Use to match splats
6778   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6779       (VT == MVT::v2f64 || VT == MVT::v2i64))
6780     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6781
6782   if (isPSHUFDMask(M, VT)) {
6783     // The actual implementation will match the mask in the if above and then
6784     // during isel it can match several different instructions, not only pshufd
6785     // as its name says, sad but true, emulate the behavior for now...
6786     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6787       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6788
6789     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6790
6791     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6792       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6793
6794     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6795       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6796                                   DAG);
6797
6798     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6799                                 TargetMask, DAG);
6800   }
6801
6802   // Check if this can be converted into a logical shift.
6803   bool isLeft = false;
6804   unsigned ShAmt = 0;
6805   SDValue ShVal;
6806   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6807   if (isShift && ShVal.hasOneUse()) {
6808     // If the shifted value has multiple uses, it may be cheaper to use
6809     // v_set0 + movlhps or movhlps, etc.
6810     EVT EltVT = VT.getVectorElementType();
6811     ShAmt *= EltVT.getSizeInBits();
6812     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6813   }
6814
6815   if (isMOVLMask(M, VT)) {
6816     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6817       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6818     if (!isMOVLPMask(M, VT)) {
6819       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6820         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6821
6822       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6823         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6824     }
6825   }
6826
6827   // FIXME: fold these into legal mask.
6828   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6829     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6830
6831   if (isMOVHLPSMask(M, VT))
6832     return getMOVHighToLow(Op, dl, DAG);
6833
6834   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6835     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6836
6837   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6838     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6839
6840   if (isMOVLPMask(M, VT))
6841     return getMOVLP(Op, dl, DAG, HasSSE2);
6842
6843   if (ShouldXformToMOVHLPS(M, VT) ||
6844       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6845     return CommuteVectorShuffle(SVOp, DAG);
6846
6847   if (isShift) {
6848     // No better options. Use a vshldq / vsrldq.
6849     EVT EltVT = VT.getVectorElementType();
6850     ShAmt *= EltVT.getSizeInBits();
6851     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6852   }
6853
6854   bool Commuted = false;
6855   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6856   // 1,1,1,1 -> v8i16 though.
6857   V1IsSplat = isSplatVector(V1.getNode());
6858   V2IsSplat = isSplatVector(V2.getNode());
6859
6860   // Canonicalize the splat or undef, if present, to be on the RHS.
6861   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6862     CommuteVectorShuffleMask(M, NumElems);
6863     std::swap(V1, V2);
6864     std::swap(V1IsSplat, V2IsSplat);
6865     Commuted = true;
6866   }
6867
6868   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6869     // Shuffling low element of v1 into undef, just return v1.
6870     if (V2IsUndef)
6871       return V1;
6872     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6873     // the instruction selector will not match, so get a canonical MOVL with
6874     // swapped operands to undo the commute.
6875     return getMOVL(DAG, dl, VT, V2, V1);
6876   }
6877
6878   if (isUNPCKLMask(M, VT, HasInt256))
6879     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6880
6881   if (isUNPCKHMask(M, VT, HasInt256))
6882     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6883
6884   if (V2IsSplat) {
6885     // Normalize mask so all entries that point to V2 points to its first
6886     // element then try to match unpck{h|l} again. If match, return a
6887     // new vector_shuffle with the corrected mask.p
6888     SmallVector<int, 8> NewMask(M.begin(), M.end());
6889     NormalizeMask(NewMask, NumElems);
6890     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6891       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6892     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6893       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6894   }
6895
6896   if (Commuted) {
6897     // Commute is back and try unpck* again.
6898     // FIXME: this seems wrong.
6899     CommuteVectorShuffleMask(M, NumElems);
6900     std::swap(V1, V2);
6901     std::swap(V1IsSplat, V2IsSplat);
6902     Commuted = false;
6903
6904     if (isUNPCKLMask(M, VT, HasInt256))
6905       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6906
6907     if (isUNPCKHMask(M, VT, HasInt256))
6908       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6909   }
6910
6911   // Normalize the node to match x86 shuffle ops if needed
6912   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6913     return CommuteVectorShuffle(SVOp, DAG);
6914
6915   // The checks below are all present in isShuffleMaskLegal, but they are
6916   // inlined here right now to enable us to directly emit target specific
6917   // nodes, and remove one by one until they don't return Op anymore.
6918
6919   if (isPALIGNRMask(M, VT, Subtarget))
6920     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6921                                 getShufflePALIGNRImmediate(SVOp),
6922                                 DAG);
6923
6924   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6925       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6926     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6927       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6928   }
6929
6930   if (isPSHUFHWMask(M, VT, HasInt256))
6931     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6932                                 getShufflePSHUFHWImmediate(SVOp),
6933                                 DAG);
6934
6935   if (isPSHUFLWMask(M, VT, HasInt256))
6936     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6937                                 getShufflePSHUFLWImmediate(SVOp),
6938                                 DAG);
6939
6940   if (isSHUFPMask(M, VT, HasFp256))
6941     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6942                                 getShuffleSHUFImmediate(SVOp), DAG);
6943
6944   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6945     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6946   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6947     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6948
6949   //===--------------------------------------------------------------------===//
6950   // Generate target specific nodes for 128 or 256-bit shuffles only
6951   // supported in the AVX instruction set.
6952   //
6953
6954   // Handle VMOVDDUPY permutations
6955   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6956     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6957
6958   // Handle VPERMILPS/D* permutations
6959   if (isVPERMILPMask(M, VT, HasFp256)) {
6960     if (HasInt256 && VT == MVT::v8i32)
6961       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6962                                   getShuffleSHUFImmediate(SVOp), DAG);
6963     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6964                                 getShuffleSHUFImmediate(SVOp), DAG);
6965   }
6966
6967   // Handle VPERM2F128/VPERM2I128 permutations
6968   if (isVPERM2X128Mask(M, VT, HasFp256))
6969     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6970                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6971
6972   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6973   if (BlendOp.getNode())
6974     return BlendOp;
6975
6976   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6977     SmallVector<SDValue, 8> permclMask;
6978     for (unsigned i = 0; i != 8; ++i) {
6979       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6980     }
6981     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6982                                &permclMask[0], 8);
6983     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6984     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6985                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6986   }
6987
6988   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6989     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6990                                 getShuffleCLImmediate(SVOp), DAG);
6991
6992   //===--------------------------------------------------------------------===//
6993   // Since no target specific shuffle was selected for this generic one,
6994   // lower it into other known shuffles. FIXME: this isn't true yet, but
6995   // this is the plan.
6996   //
6997
6998   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6999   if (VT == MVT::v8i16) {
7000     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7001     if (NewOp.getNode())
7002       return NewOp;
7003   }
7004
7005   if (VT == MVT::v16i8) {
7006     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7007     if (NewOp.getNode())
7008       return NewOp;
7009   }
7010
7011   if (VT == MVT::v32i8) {
7012     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7013     if (NewOp.getNode())
7014       return NewOp;
7015   }
7016
7017   // Handle all 128-bit wide vectors with 4 elements, and match them with
7018   // several different shuffle types.
7019   if (NumElems == 4 && VT.is128BitVector())
7020     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7021
7022   // Handle general 256-bit shuffles
7023   if (VT.is256BitVector())
7024     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7025
7026   return SDValue();
7027 }
7028
7029 SDValue
7030 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7031                                                 SelectionDAG &DAG) const {
7032   EVT VT = Op.getValueType();
7033   DebugLoc dl = Op.getDebugLoc();
7034
7035   if (!Op.getOperand(0).getValueType().is128BitVector())
7036     return SDValue();
7037
7038   if (VT.getSizeInBits() == 8) {
7039     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7040                                   Op.getOperand(0), Op.getOperand(1));
7041     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7042                                   DAG.getValueType(VT));
7043     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7044   }
7045
7046   if (VT.getSizeInBits() == 16) {
7047     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7048     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7049     if (Idx == 0)
7050       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7051                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7052                                      DAG.getNode(ISD::BITCAST, dl,
7053                                                  MVT::v4i32,
7054                                                  Op.getOperand(0)),
7055                                      Op.getOperand(1)));
7056     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7057                                   Op.getOperand(0), Op.getOperand(1));
7058     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7059                                   DAG.getValueType(VT));
7060     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7061   }
7062
7063   if (VT == MVT::f32) {
7064     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7065     // the result back to FR32 register. It's only worth matching if the
7066     // result has a single use which is a store or a bitcast to i32.  And in
7067     // the case of a store, it's not worth it if the index is a constant 0,
7068     // because a MOVSSmr can be used instead, which is smaller and faster.
7069     if (!Op.hasOneUse())
7070       return SDValue();
7071     SDNode *User = *Op.getNode()->use_begin();
7072     if ((User->getOpcode() != ISD::STORE ||
7073          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7074           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7075         (User->getOpcode() != ISD::BITCAST ||
7076          User->getValueType(0) != MVT::i32))
7077       return SDValue();
7078     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7079                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7080                                               Op.getOperand(0)),
7081                                               Op.getOperand(1));
7082     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7083   }
7084
7085   if (VT == MVT::i32 || VT == MVT::i64) {
7086     // ExtractPS/pextrq works with constant index.
7087     if (isa<ConstantSDNode>(Op.getOperand(1)))
7088       return Op;
7089   }
7090   return SDValue();
7091 }
7092
7093 SDValue
7094 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7095                                            SelectionDAG &DAG) const {
7096   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7097     return SDValue();
7098
7099   SDValue Vec = Op.getOperand(0);
7100   EVT VecVT = Vec.getValueType();
7101
7102   // If this is a 256-bit vector result, first extract the 128-bit vector and
7103   // then extract the element from the 128-bit vector.
7104   if (VecVT.is256BitVector()) {
7105     DebugLoc dl = Op.getNode()->getDebugLoc();
7106     unsigned NumElems = VecVT.getVectorNumElements();
7107     SDValue Idx = Op.getOperand(1);
7108     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7109
7110     // Get the 128-bit vector.
7111     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7112
7113     if (IdxVal >= NumElems/2)
7114       IdxVal -= NumElems/2;
7115     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7116                        DAG.getConstant(IdxVal, MVT::i32));
7117   }
7118
7119   assert(VecVT.is128BitVector() && "Unexpected vector length");
7120
7121   if (Subtarget->hasSSE41()) {
7122     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7123     if (Res.getNode())
7124       return Res;
7125   }
7126
7127   EVT VT = Op.getValueType();
7128   DebugLoc dl = Op.getDebugLoc();
7129   // TODO: handle v16i8.
7130   if (VT.getSizeInBits() == 16) {
7131     SDValue Vec = Op.getOperand(0);
7132     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7133     if (Idx == 0)
7134       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7135                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7136                                      DAG.getNode(ISD::BITCAST, dl,
7137                                                  MVT::v4i32, Vec),
7138                                      Op.getOperand(1)));
7139     // Transform it so it match pextrw which produces a 32-bit result.
7140     EVT EltVT = MVT::i32;
7141     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7142                                   Op.getOperand(0), Op.getOperand(1));
7143     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7144                                   DAG.getValueType(VT));
7145     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7146   }
7147
7148   if (VT.getSizeInBits() == 32) {
7149     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7150     if (Idx == 0)
7151       return Op;
7152
7153     // SHUFPS the element to the lowest double word, then movss.
7154     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7155     EVT VVT = Op.getOperand(0).getValueType();
7156     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7157                                        DAG.getUNDEF(VVT), Mask);
7158     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7159                        DAG.getIntPtrConstant(0));
7160   }
7161
7162   if (VT.getSizeInBits() == 64) {
7163     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7164     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7165     //        to match extract_elt for f64.
7166     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7167     if (Idx == 0)
7168       return Op;
7169
7170     // UNPCKHPD the element to the lowest double word, then movsd.
7171     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7172     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7173     int Mask[2] = { 1, -1 };
7174     EVT VVT = Op.getOperand(0).getValueType();
7175     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7176                                        DAG.getUNDEF(VVT), Mask);
7177     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7178                        DAG.getIntPtrConstant(0));
7179   }
7180
7181   return SDValue();
7182 }
7183
7184 SDValue
7185 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7186                                                SelectionDAG &DAG) const {
7187   EVT VT = Op.getValueType();
7188   EVT EltVT = VT.getVectorElementType();
7189   DebugLoc dl = Op.getDebugLoc();
7190
7191   SDValue N0 = Op.getOperand(0);
7192   SDValue N1 = Op.getOperand(1);
7193   SDValue N2 = Op.getOperand(2);
7194
7195   if (!VT.is128BitVector())
7196     return SDValue();
7197
7198   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7199       isa<ConstantSDNode>(N2)) {
7200     unsigned Opc;
7201     if (VT == MVT::v8i16)
7202       Opc = X86ISD::PINSRW;
7203     else if (VT == MVT::v16i8)
7204       Opc = X86ISD::PINSRB;
7205     else
7206       Opc = X86ISD::PINSRB;
7207
7208     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7209     // argument.
7210     if (N1.getValueType() != MVT::i32)
7211       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7212     if (N2.getValueType() != MVT::i32)
7213       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7214     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7215   }
7216
7217   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7218     // Bits [7:6] of the constant are the source select.  This will always be
7219     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7220     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7221     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7222     // Bits [5:4] of the constant are the destination select.  This is the
7223     //  value of the incoming immediate.
7224     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7225     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7226     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7227     // Create this as a scalar to vector..
7228     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7229     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7230   }
7231
7232   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7233     // PINSR* works with constant index.
7234     return Op;
7235   }
7236   return SDValue();
7237 }
7238
7239 SDValue
7240 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7241   EVT VT = Op.getValueType();
7242   EVT EltVT = VT.getVectorElementType();
7243
7244   DebugLoc dl = Op.getDebugLoc();
7245   SDValue N0 = Op.getOperand(0);
7246   SDValue N1 = Op.getOperand(1);
7247   SDValue N2 = Op.getOperand(2);
7248
7249   // If this is a 256-bit vector result, first extract the 128-bit vector,
7250   // insert the element into the extracted half and then place it back.
7251   if (VT.is256BitVector()) {
7252     if (!isa<ConstantSDNode>(N2))
7253       return SDValue();
7254
7255     // Get the desired 128-bit vector half.
7256     unsigned NumElems = VT.getVectorNumElements();
7257     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7258     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7259
7260     // Insert the element into the desired half.
7261     bool Upper = IdxVal >= NumElems/2;
7262     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7263                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7264
7265     // Insert the changed part back to the 256-bit vector
7266     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7267   }
7268
7269   if (Subtarget->hasSSE41())
7270     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7271
7272   if (EltVT == MVT::i8)
7273     return SDValue();
7274
7275   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7276     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7277     // as its second argument.
7278     if (N1.getValueType() != MVT::i32)
7279       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7280     if (N2.getValueType() != MVT::i32)
7281       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7282     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7283   }
7284   return SDValue();
7285 }
7286
7287 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7288   LLVMContext *Context = DAG.getContext();
7289   DebugLoc dl = Op.getDebugLoc();
7290   EVT OpVT = Op.getValueType();
7291
7292   // If this is a 256-bit vector result, first insert into a 128-bit
7293   // vector and then insert into the 256-bit vector.
7294   if (!OpVT.is128BitVector()) {
7295     // Insert into a 128-bit vector.
7296     EVT VT128 = EVT::getVectorVT(*Context,
7297                                  OpVT.getVectorElementType(),
7298                                  OpVT.getVectorNumElements() / 2);
7299
7300     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7301
7302     // Insert the 128-bit vector.
7303     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7304   }
7305
7306   if (OpVT == MVT::v1i64 &&
7307       Op.getOperand(0).getValueType() == MVT::i64)
7308     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7309
7310   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7311   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7312   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7313                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7314 }
7315
7316 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7317 // a simple subregister reference or explicit instructions to grab
7318 // upper bits of a vector.
7319 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7320                                       SelectionDAG &DAG) {
7321   if (Subtarget->hasFp256()) {
7322     DebugLoc dl = Op.getNode()->getDebugLoc();
7323     SDValue Vec = Op.getNode()->getOperand(0);
7324     SDValue Idx = Op.getNode()->getOperand(1);
7325
7326     if (Op.getNode()->getValueType(0).is128BitVector() &&
7327         Vec.getNode()->getValueType(0).is256BitVector() &&
7328         isa<ConstantSDNode>(Idx)) {
7329       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7330       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7331     }
7332   }
7333   return SDValue();
7334 }
7335
7336 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7337 // simple superregister reference or explicit instructions to insert
7338 // the upper bits of a vector.
7339 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7340                                      SelectionDAG &DAG) {
7341   if (Subtarget->hasFp256()) {
7342     DebugLoc dl = Op.getNode()->getDebugLoc();
7343     SDValue Vec = Op.getNode()->getOperand(0);
7344     SDValue SubVec = Op.getNode()->getOperand(1);
7345     SDValue Idx = Op.getNode()->getOperand(2);
7346
7347     if (Op.getNode()->getValueType(0).is256BitVector() &&
7348         SubVec.getNode()->getValueType(0).is128BitVector() &&
7349         isa<ConstantSDNode>(Idx)) {
7350       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7351       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7352     }
7353   }
7354   return SDValue();
7355 }
7356
7357 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7358 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7359 // one of the above mentioned nodes. It has to be wrapped because otherwise
7360 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7361 // be used to form addressing mode. These wrapped nodes will be selected
7362 // into MOV32ri.
7363 SDValue
7364 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7365   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7366
7367   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7368   // global base reg.
7369   unsigned char OpFlag = 0;
7370   unsigned WrapperKind = X86ISD::Wrapper;
7371   CodeModel::Model M = getTargetMachine().getCodeModel();
7372
7373   if (Subtarget->isPICStyleRIPRel() &&
7374       (M == CodeModel::Small || M == CodeModel::Kernel))
7375     WrapperKind = X86ISD::WrapperRIP;
7376   else if (Subtarget->isPICStyleGOT())
7377     OpFlag = X86II::MO_GOTOFF;
7378   else if (Subtarget->isPICStyleStubPIC())
7379     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7380
7381   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7382                                              CP->getAlignment(),
7383                                              CP->getOffset(), OpFlag);
7384   DebugLoc DL = CP->getDebugLoc();
7385   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7386   // With PIC, the address is actually $g + Offset.
7387   if (OpFlag) {
7388     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7389                          DAG.getNode(X86ISD::GlobalBaseReg,
7390                                      DebugLoc(), getPointerTy()),
7391                          Result);
7392   }
7393
7394   return Result;
7395 }
7396
7397 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7398   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7399
7400   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7401   // global base reg.
7402   unsigned char OpFlag = 0;
7403   unsigned WrapperKind = X86ISD::Wrapper;
7404   CodeModel::Model M = getTargetMachine().getCodeModel();
7405
7406   if (Subtarget->isPICStyleRIPRel() &&
7407       (M == CodeModel::Small || M == CodeModel::Kernel))
7408     WrapperKind = X86ISD::WrapperRIP;
7409   else if (Subtarget->isPICStyleGOT())
7410     OpFlag = X86II::MO_GOTOFF;
7411   else if (Subtarget->isPICStyleStubPIC())
7412     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7413
7414   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7415                                           OpFlag);
7416   DebugLoc DL = JT->getDebugLoc();
7417   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7418
7419   // With PIC, the address is actually $g + Offset.
7420   if (OpFlag)
7421     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7422                          DAG.getNode(X86ISD::GlobalBaseReg,
7423                                      DebugLoc(), getPointerTy()),
7424                          Result);
7425
7426   return Result;
7427 }
7428
7429 SDValue
7430 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7431   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7432
7433   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7434   // global base reg.
7435   unsigned char OpFlag = 0;
7436   unsigned WrapperKind = X86ISD::Wrapper;
7437   CodeModel::Model M = getTargetMachine().getCodeModel();
7438
7439   if (Subtarget->isPICStyleRIPRel() &&
7440       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7441     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7442       OpFlag = X86II::MO_GOTPCREL;
7443     WrapperKind = X86ISD::WrapperRIP;
7444   } else if (Subtarget->isPICStyleGOT()) {
7445     OpFlag = X86II::MO_GOT;
7446   } else if (Subtarget->isPICStyleStubPIC()) {
7447     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7448   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7449     OpFlag = X86II::MO_DARWIN_NONLAZY;
7450   }
7451
7452   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7453
7454   DebugLoc DL = Op.getDebugLoc();
7455   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7456
7457   // With PIC, the address is actually $g + Offset.
7458   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7459       !Subtarget->is64Bit()) {
7460     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461                          DAG.getNode(X86ISD::GlobalBaseReg,
7462                                      DebugLoc(), getPointerTy()),
7463                          Result);
7464   }
7465
7466   // For symbols that require a load from a stub to get the address, emit the
7467   // load.
7468   if (isGlobalStubReference(OpFlag))
7469     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7470                          MachinePointerInfo::getGOT(), false, false, false, 0);
7471
7472   return Result;
7473 }
7474
7475 SDValue
7476 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7477   // Create the TargetBlockAddressAddress node.
7478   unsigned char OpFlags =
7479     Subtarget->ClassifyBlockAddressReference();
7480   CodeModel::Model M = getTargetMachine().getCodeModel();
7481   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7482   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7483   DebugLoc dl = Op.getDebugLoc();
7484   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7485                                              OpFlags);
7486
7487   if (Subtarget->isPICStyleRIPRel() &&
7488       (M == CodeModel::Small || M == CodeModel::Kernel))
7489     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7490   else
7491     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7492
7493   // With PIC, the address is actually $g + Offset.
7494   if (isGlobalRelativeToPICBase(OpFlags)) {
7495     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7496                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7497                          Result);
7498   }
7499
7500   return Result;
7501 }
7502
7503 SDValue
7504 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7505                                       int64_t Offset,
7506                                       SelectionDAG &DAG) const {
7507   // Create the TargetGlobalAddress node, folding in the constant
7508   // offset if it is legal.
7509   unsigned char OpFlags =
7510     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7511   CodeModel::Model M = getTargetMachine().getCodeModel();
7512   SDValue Result;
7513   if (OpFlags == X86II::MO_NO_FLAG &&
7514       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7515     // A direct static reference to a global.
7516     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7517     Offset = 0;
7518   } else {
7519     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7520   }
7521
7522   if (Subtarget->isPICStyleRIPRel() &&
7523       (M == CodeModel::Small || M == CodeModel::Kernel))
7524     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7525   else
7526     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7527
7528   // With PIC, the address is actually $g + Offset.
7529   if (isGlobalRelativeToPICBase(OpFlags)) {
7530     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7531                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7532                          Result);
7533   }
7534
7535   // For globals that require a load from a stub to get the address, emit the
7536   // load.
7537   if (isGlobalStubReference(OpFlags))
7538     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7539                          MachinePointerInfo::getGOT(), false, false, false, 0);
7540
7541   // If there was a non-zero offset that we didn't fold, create an explicit
7542   // addition for it.
7543   if (Offset != 0)
7544     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7545                          DAG.getConstant(Offset, getPointerTy()));
7546
7547   return Result;
7548 }
7549
7550 SDValue
7551 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7552   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7553   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7554   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7555 }
7556
7557 static SDValue
7558 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7559            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7560            unsigned char OperandFlags, bool LocalDynamic = false) {
7561   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7562   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7563   DebugLoc dl = GA->getDebugLoc();
7564   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7565                                            GA->getValueType(0),
7566                                            GA->getOffset(),
7567                                            OperandFlags);
7568
7569   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7570                                            : X86ISD::TLSADDR;
7571
7572   if (InFlag) {
7573     SDValue Ops[] = { Chain,  TGA, *InFlag };
7574     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7575   } else {
7576     SDValue Ops[]  = { Chain, TGA };
7577     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7578   }
7579
7580   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7581   MFI->setAdjustsStack(true);
7582
7583   SDValue Flag = Chain.getValue(1);
7584   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7585 }
7586
7587 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7588 static SDValue
7589 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7590                                 const EVT PtrVT) {
7591   SDValue InFlag;
7592   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7593   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7594                                    DAG.getNode(X86ISD::GlobalBaseReg,
7595                                                DebugLoc(), PtrVT), InFlag);
7596   InFlag = Chain.getValue(1);
7597
7598   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7599 }
7600
7601 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7602 static SDValue
7603 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7604                                 const EVT PtrVT) {
7605   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7606                     X86::RAX, X86II::MO_TLSGD);
7607 }
7608
7609 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7610                                            SelectionDAG &DAG,
7611                                            const EVT PtrVT,
7612                                            bool is64Bit) {
7613   DebugLoc dl = GA->getDebugLoc();
7614
7615   // Get the start address of the TLS block for this module.
7616   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7617       .getInfo<X86MachineFunctionInfo>();
7618   MFI->incNumLocalDynamicTLSAccesses();
7619
7620   SDValue Base;
7621   if (is64Bit) {
7622     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7623                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7624   } else {
7625     SDValue InFlag;
7626     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7627         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7628     InFlag = Chain.getValue(1);
7629     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7630                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7631   }
7632
7633   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7634   // of Base.
7635
7636   // Build x@dtpoff.
7637   unsigned char OperandFlags = X86II::MO_DTPOFF;
7638   unsigned WrapperKind = X86ISD::Wrapper;
7639   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7640                                            GA->getValueType(0),
7641                                            GA->getOffset(), OperandFlags);
7642   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7643
7644   // Add x@dtpoff with the base.
7645   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7646 }
7647
7648 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7649 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7650                                    const EVT PtrVT, TLSModel::Model model,
7651                                    bool is64Bit, bool isPIC) {
7652   DebugLoc dl = GA->getDebugLoc();
7653
7654   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7655   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7656                                                          is64Bit ? 257 : 256));
7657
7658   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7659                                       DAG.getIntPtrConstant(0),
7660                                       MachinePointerInfo(Ptr),
7661                                       false, false, false, 0);
7662
7663   unsigned char OperandFlags = 0;
7664   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7665   // initialexec.
7666   unsigned WrapperKind = X86ISD::Wrapper;
7667   if (model == TLSModel::LocalExec) {
7668     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7669   } else if (model == TLSModel::InitialExec) {
7670     if (is64Bit) {
7671       OperandFlags = X86II::MO_GOTTPOFF;
7672       WrapperKind = X86ISD::WrapperRIP;
7673     } else {
7674       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7675     }
7676   } else {
7677     llvm_unreachable("Unexpected model");
7678   }
7679
7680   // emit "addl x@ntpoff,%eax" (local exec)
7681   // or "addl x@indntpoff,%eax" (initial exec)
7682   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7683   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7684                                            GA->getValueType(0),
7685                                            GA->getOffset(), OperandFlags);
7686   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7687
7688   if (model == TLSModel::InitialExec) {
7689     if (isPIC && !is64Bit) {
7690       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7691                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7692                            Offset);
7693     }
7694
7695     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7696                          MachinePointerInfo::getGOT(), false, false, false,
7697                          0);
7698   }
7699
7700   // The address of the thread local variable is the add of the thread
7701   // pointer with the offset of the variable.
7702   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7703 }
7704
7705 SDValue
7706 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7707
7708   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7709   const GlobalValue *GV = GA->getGlobal();
7710
7711   if (Subtarget->isTargetELF()) {
7712     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7713
7714     switch (model) {
7715       case TLSModel::GeneralDynamic:
7716         if (Subtarget->is64Bit())
7717           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7718         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7719       case TLSModel::LocalDynamic:
7720         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7721                                            Subtarget->is64Bit());
7722       case TLSModel::InitialExec:
7723       case TLSModel::LocalExec:
7724         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7725                                    Subtarget->is64Bit(),
7726                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7727     }
7728     llvm_unreachable("Unknown TLS model.");
7729   }
7730
7731   if (Subtarget->isTargetDarwin()) {
7732     // Darwin only has one model of TLS.  Lower to that.
7733     unsigned char OpFlag = 0;
7734     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7735                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7736
7737     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7738     // global base reg.
7739     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7740                   !Subtarget->is64Bit();
7741     if (PIC32)
7742       OpFlag = X86II::MO_TLVP_PIC_BASE;
7743     else
7744       OpFlag = X86II::MO_TLVP;
7745     DebugLoc DL = Op.getDebugLoc();
7746     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7747                                                 GA->getValueType(0),
7748                                                 GA->getOffset(), OpFlag);
7749     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7750
7751     // With PIC32, the address is actually $g + Offset.
7752     if (PIC32)
7753       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7754                            DAG.getNode(X86ISD::GlobalBaseReg,
7755                                        DebugLoc(), getPointerTy()),
7756                            Offset);
7757
7758     // Lowering the machine isd will make sure everything is in the right
7759     // location.
7760     SDValue Chain = DAG.getEntryNode();
7761     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7762     SDValue Args[] = { Chain, Offset };
7763     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7764
7765     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7766     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7767     MFI->setAdjustsStack(true);
7768
7769     // And our return value (tls address) is in the standard call return value
7770     // location.
7771     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7772     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7773                               Chain.getValue(1));
7774   }
7775
7776   if (Subtarget->isTargetWindows()) {
7777     // Just use the implicit TLS architecture
7778     // Need to generate someting similar to:
7779     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7780     //                                  ; from TEB
7781     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7782     //   mov     rcx, qword [rdx+rcx*8]
7783     //   mov     eax, .tls$:tlsvar
7784     //   [rax+rcx] contains the address
7785     // Windows 64bit: gs:0x58
7786     // Windows 32bit: fs:__tls_array
7787
7788     // If GV is an alias then use the aliasee for determining
7789     // thread-localness.
7790     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7791       GV = GA->resolveAliasedGlobal(false);
7792     DebugLoc dl = GA->getDebugLoc();
7793     SDValue Chain = DAG.getEntryNode();
7794
7795     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7796     // %gs:0x58 (64-bit).
7797     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7798                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7799                                                              256)
7800                                         : Type::getInt32PtrTy(*DAG.getContext(),
7801                                                               257));
7802
7803     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7804                                         Subtarget->is64Bit()
7805                                         ? DAG.getIntPtrConstant(0x58)
7806                                         : DAG.getExternalSymbol("_tls_array",
7807                                                                 getPointerTy()),
7808                                         MachinePointerInfo(Ptr),
7809                                         false, false, false, 0);
7810
7811     // Load the _tls_index variable
7812     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7813     if (Subtarget->is64Bit())
7814       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7815                            IDX, MachinePointerInfo(), MVT::i32,
7816                            false, false, 0);
7817     else
7818       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7819                         false, false, false, 0);
7820
7821     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7822                                     getPointerTy());
7823     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7824
7825     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7826     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7827                       false, false, false, 0);
7828
7829     // Get the offset of start of .tls section
7830     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7831                                              GA->getValueType(0),
7832                                              GA->getOffset(), X86II::MO_SECREL);
7833     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7834
7835     // The address of the thread local variable is the add of the thread
7836     // pointer with the offset of the variable.
7837     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7838   }
7839
7840   llvm_unreachable("TLS not implemented for this target.");
7841 }
7842
7843 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7844 /// and take a 2 x i32 value to shift plus a shift amount.
7845 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7846   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7847   EVT VT = Op.getValueType();
7848   unsigned VTBits = VT.getSizeInBits();
7849   DebugLoc dl = Op.getDebugLoc();
7850   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7851   SDValue ShOpLo = Op.getOperand(0);
7852   SDValue ShOpHi = Op.getOperand(1);
7853   SDValue ShAmt  = Op.getOperand(2);
7854   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7855                                      DAG.getConstant(VTBits - 1, MVT::i8))
7856                        : DAG.getConstant(0, VT);
7857
7858   SDValue Tmp2, Tmp3;
7859   if (Op.getOpcode() == ISD::SHL_PARTS) {
7860     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7861     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7862   } else {
7863     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7864     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7865   }
7866
7867   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7868                                 DAG.getConstant(VTBits, MVT::i8));
7869   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7870                              AndNode, DAG.getConstant(0, MVT::i8));
7871
7872   SDValue Hi, Lo;
7873   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7874   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7875   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7876
7877   if (Op.getOpcode() == ISD::SHL_PARTS) {
7878     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7879     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7880   } else {
7881     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7882     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7883   }
7884
7885   SDValue Ops[2] = { Lo, Hi };
7886   return DAG.getMergeValues(Ops, 2, dl);
7887 }
7888
7889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7890                                            SelectionDAG &DAG) const {
7891   EVT SrcVT = Op.getOperand(0).getValueType();
7892
7893   if (SrcVT.isVector())
7894     return SDValue();
7895
7896   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7897          "Unknown SINT_TO_FP to lower!");
7898
7899   // These are really Legal; return the operand so the caller accepts it as
7900   // Legal.
7901   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7902     return Op;
7903   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7904       Subtarget->is64Bit()) {
7905     return Op;
7906   }
7907
7908   DebugLoc dl = Op.getDebugLoc();
7909   unsigned Size = SrcVT.getSizeInBits()/8;
7910   MachineFunction &MF = DAG.getMachineFunction();
7911   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7912   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7913   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7914                                StackSlot,
7915                                MachinePointerInfo::getFixedStack(SSFI),
7916                                false, false, 0);
7917   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7918 }
7919
7920 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7921                                      SDValue StackSlot,
7922                                      SelectionDAG &DAG) const {
7923   // Build the FILD
7924   DebugLoc DL = Op.getDebugLoc();
7925   SDVTList Tys;
7926   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7927   if (useSSE)
7928     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7929   else
7930     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7931
7932   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7933
7934   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7935   MachineMemOperand *MMO;
7936   if (FI) {
7937     int SSFI = FI->getIndex();
7938     MMO =
7939       DAG.getMachineFunction()
7940       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7941                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7942   } else {
7943     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7944     StackSlot = StackSlot.getOperand(1);
7945   }
7946   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7947   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7948                                            X86ISD::FILD, DL,
7949                                            Tys, Ops, array_lengthof(Ops),
7950                                            SrcVT, MMO);
7951
7952   if (useSSE) {
7953     Chain = Result.getValue(1);
7954     SDValue InFlag = Result.getValue(2);
7955
7956     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7957     // shouldn't be necessary except that RFP cannot be live across
7958     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7959     MachineFunction &MF = DAG.getMachineFunction();
7960     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7961     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7962     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963     Tys = DAG.getVTList(MVT::Other);
7964     SDValue Ops[] = {
7965       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7966     };
7967     MachineMemOperand *MMO =
7968       DAG.getMachineFunction()
7969       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7971
7972     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7973                                     Ops, array_lengthof(Ops),
7974                                     Op.getValueType(), MMO);
7975     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7976                          MachinePointerInfo::getFixedStack(SSFI),
7977                          false, false, false, 0);
7978   }
7979
7980   return Result;
7981 }
7982
7983 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7984 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7985                                                SelectionDAG &DAG) const {
7986   // This algorithm is not obvious. Here it is what we're trying to output:
7987   /*
7988      movq       %rax,  %xmm0
7989      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7990      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7991      #ifdef __SSE3__
7992        haddpd   %xmm0, %xmm0
7993      #else
7994        pshufd   $0x4e, %xmm0, %xmm1
7995        addpd    %xmm1, %xmm0
7996      #endif
7997   */
7998
7999   DebugLoc dl = Op.getDebugLoc();
8000   LLVMContext *Context = DAG.getContext();
8001
8002   // Build some magic constants.
8003   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8004   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8005   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8006
8007   SmallVector<Constant*,2> CV1;
8008   CV1.push_back(
8009         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8010   CV1.push_back(
8011         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8012   Constant *C1 = ConstantVector::get(CV1);
8013   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8014
8015   // Load the 64-bit value into an XMM register.
8016   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8017                             Op.getOperand(0));
8018   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8019                               MachinePointerInfo::getConstantPool(),
8020                               false, false, false, 16);
8021   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8022                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8023                               CLod0);
8024
8025   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8026                               MachinePointerInfo::getConstantPool(),
8027                               false, false, false, 16);
8028   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8029   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8030   SDValue Result;
8031
8032   if (Subtarget->hasSSE3()) {
8033     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8034     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8035   } else {
8036     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8037     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8038                                            S2F, 0x4E, DAG);
8039     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8040                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8041                          Sub);
8042   }
8043
8044   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8045                      DAG.getIntPtrConstant(0));
8046 }
8047
8048 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8049 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8050                                                SelectionDAG &DAG) const {
8051   DebugLoc dl = Op.getDebugLoc();
8052   // FP constant to bias correct the final result.
8053   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8054                                    MVT::f64);
8055
8056   // Load the 32-bit value into an XMM register.
8057   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8058                              Op.getOperand(0));
8059
8060   // Zero out the upper parts of the register.
8061   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8062
8063   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8064                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8065                      DAG.getIntPtrConstant(0));
8066
8067   // Or the load with the bias.
8068   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8069                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8070                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8071                                                    MVT::v2f64, Load)),
8072                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8073                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8074                                                    MVT::v2f64, Bias)));
8075   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8077                    DAG.getIntPtrConstant(0));
8078
8079   // Subtract the bias.
8080   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8081
8082   // Handle final rounding.
8083   EVT DestVT = Op.getValueType();
8084
8085   if (DestVT.bitsLT(MVT::f64))
8086     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8087                        DAG.getIntPtrConstant(0));
8088   if (DestVT.bitsGT(MVT::f64))
8089     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8090
8091   // Handle final rounding.
8092   return Sub;
8093 }
8094
8095 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8096                                                SelectionDAG &DAG) const {
8097   SDValue N0 = Op.getOperand(0);
8098   EVT SVT = N0.getValueType();
8099   DebugLoc dl = Op.getDebugLoc();
8100
8101   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8102           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8103          "Custom UINT_TO_FP is not supported!");
8104
8105   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8106   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8107                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8108 }
8109
8110 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8111                                            SelectionDAG &DAG) const {
8112   SDValue N0 = Op.getOperand(0);
8113   DebugLoc dl = Op.getDebugLoc();
8114
8115   if (Op.getValueType().isVector())
8116     return lowerUINT_TO_FP_vec(Op, DAG);
8117
8118   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8119   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8120   // the optimization here.
8121   if (DAG.SignBitIsZero(N0))
8122     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8123
8124   EVT SrcVT = N0.getValueType();
8125   EVT DstVT = Op.getValueType();
8126   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8127     return LowerUINT_TO_FP_i64(Op, DAG);
8128   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8129     return LowerUINT_TO_FP_i32(Op, DAG);
8130   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8131     return SDValue();
8132
8133   // Make a 64-bit buffer, and use it to build an FILD.
8134   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8135   if (SrcVT == MVT::i32) {
8136     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8137     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8138                                      getPointerTy(), StackSlot, WordOff);
8139     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8140                                   StackSlot, MachinePointerInfo(),
8141                                   false, false, 0);
8142     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8143                                   OffsetSlot, MachinePointerInfo(),
8144                                   false, false, 0);
8145     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8146     return Fild;
8147   }
8148
8149   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8150   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8151                                StackSlot, MachinePointerInfo(),
8152                                false, false, 0);
8153   // For i64 source, we need to add the appropriate power of 2 if the input
8154   // was negative.  This is the same as the optimization in
8155   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8156   // we must be careful to do the computation in x87 extended precision, not
8157   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8158   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8159   MachineMemOperand *MMO =
8160     DAG.getMachineFunction()
8161     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8162                           MachineMemOperand::MOLoad, 8, 8);
8163
8164   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8165   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8166   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8167                                          MVT::i64, MMO);
8168
8169   APInt FF(32, 0x5F800000ULL);
8170
8171   // Check whether the sign bit is set.
8172   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8173                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8174                                  ISD::SETLT);
8175
8176   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8177   SDValue FudgePtr = DAG.getConstantPool(
8178                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8179                                          getPointerTy());
8180
8181   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8182   SDValue Zero = DAG.getIntPtrConstant(0);
8183   SDValue Four = DAG.getIntPtrConstant(4);
8184   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8185                                Zero, Four);
8186   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8187
8188   // Load the value out, extending it from f32 to f80.
8189   // FIXME: Avoid the extend by constructing the right constant pool?
8190   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8191                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8192                                  MVT::f32, false, false, 4);
8193   // Extend everything to 80 bits to force it to be done on x87.
8194   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8195   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8196 }
8197
8198 std::pair<SDValue,SDValue> X86TargetLowering::
8199 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8200   DebugLoc DL = Op.getDebugLoc();
8201
8202   EVT DstTy = Op.getValueType();
8203
8204   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8205     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8206     DstTy = MVT::i64;
8207   }
8208
8209   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8210          DstTy.getSimpleVT() >= MVT::i16 &&
8211          "Unknown FP_TO_INT to lower!");
8212
8213   // These are really Legal.
8214   if (DstTy == MVT::i32 &&
8215       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8216     return std::make_pair(SDValue(), SDValue());
8217   if (Subtarget->is64Bit() &&
8218       DstTy == MVT::i64 &&
8219       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8220     return std::make_pair(SDValue(), SDValue());
8221
8222   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8223   // stack slot, or into the FTOL runtime function.
8224   MachineFunction &MF = DAG.getMachineFunction();
8225   unsigned MemSize = DstTy.getSizeInBits()/8;
8226   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8227   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8228
8229   unsigned Opc;
8230   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8231     Opc = X86ISD::WIN_FTOL;
8232   else
8233     switch (DstTy.getSimpleVT().SimpleTy) {
8234     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8235     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8236     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8237     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8238     }
8239
8240   SDValue Chain = DAG.getEntryNode();
8241   SDValue Value = Op.getOperand(0);
8242   EVT TheVT = Op.getOperand(0).getValueType();
8243   // FIXME This causes a redundant load/store if the SSE-class value is already
8244   // in memory, such as if it is on the callstack.
8245   if (isScalarFPTypeInSSEReg(TheVT)) {
8246     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8247     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8248                          MachinePointerInfo::getFixedStack(SSFI),
8249                          false, false, 0);
8250     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8251     SDValue Ops[] = {
8252       Chain, StackSlot, DAG.getValueType(TheVT)
8253     };
8254
8255     MachineMemOperand *MMO =
8256       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8257                               MachineMemOperand::MOLoad, MemSize, MemSize);
8258     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8259                                     DstTy, MMO);
8260     Chain = Value.getValue(1);
8261     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8262     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8263   }
8264
8265   MachineMemOperand *MMO =
8266     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8267                             MachineMemOperand::MOStore, MemSize, MemSize);
8268
8269   if (Opc != X86ISD::WIN_FTOL) {
8270     // Build the FP_TO_INT*_IN_MEM
8271     SDValue Ops[] = { Chain, Value, StackSlot };
8272     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8273                                            Ops, 3, DstTy, MMO);
8274     return std::make_pair(FIST, StackSlot);
8275   } else {
8276     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8277       DAG.getVTList(MVT::Other, MVT::Glue),
8278       Chain, Value);
8279     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8280       MVT::i32, ftol.getValue(1));
8281     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8282       MVT::i32, eax.getValue(2));
8283     SDValue Ops[] = { eax, edx };
8284     SDValue pair = IsReplace
8285       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8286       : DAG.getMergeValues(Ops, 2, DL);
8287     return std::make_pair(pair, SDValue());
8288   }
8289 }
8290
8291 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8292   DebugLoc DL = Op.getDebugLoc();
8293   EVT VT = Op.getValueType();
8294   SDValue In = Op.getOperand(0);
8295   EVT SVT = In.getValueType();
8296
8297   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8298       VT.getVectorNumElements() != SVT.getVectorNumElements())
8299     return SDValue();
8300
8301   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8302
8303   // AVX2 has better support of integer extending.
8304   if (Subtarget->hasInt256())
8305     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8306
8307   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8308   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8309   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8310                            DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8311
8312   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8313 }
8314
8315 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8316   DebugLoc DL = Op.getDebugLoc();
8317   EVT VT = Op.getValueType();
8318   EVT SVT = Op.getOperand(0).getValueType();
8319
8320   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8321       VT.getVectorNumElements() != SVT.getVectorNumElements())
8322     return SDValue();
8323
8324   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8325
8326   unsigned NumElems = VT.getVectorNumElements();
8327   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8328                              NumElems * 2);
8329
8330   SDValue In = Op.getOperand(0);
8331   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8332   // Prepare truncation shuffle mask
8333   for (unsigned i = 0; i != NumElems; ++i)
8334     MaskVec[i] = i * 2;
8335   SDValue V = DAG.getVectorShuffle(NVT, DL,
8336                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8337                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8338   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8339                      DAG.getIntPtrConstant(0));
8340 }
8341
8342 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8343                                            SelectionDAG &DAG) const {
8344   if (Op.getValueType().isVector()) {
8345     if (Op.getValueType() == MVT::v8i16)
8346       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8347                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8348                                      MVT::v8i32, Op.getOperand(0)));
8349     return SDValue();
8350   }
8351
8352   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8353     /*IsSigned=*/ true, /*IsReplace=*/ false);
8354   SDValue FIST = Vals.first, StackSlot = Vals.second;
8355   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8356   if (FIST.getNode() == 0) return Op;
8357
8358   if (StackSlot.getNode())
8359     // Load the result.
8360     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8361                        FIST, StackSlot, MachinePointerInfo(),
8362                        false, false, false, 0);
8363
8364   // The node is the result.
8365   return FIST;
8366 }
8367
8368 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8369                                            SelectionDAG &DAG) const {
8370   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8371     /*IsSigned=*/ false, /*IsReplace=*/ false);
8372   SDValue FIST = Vals.first, StackSlot = Vals.second;
8373   assert(FIST.getNode() && "Unexpected failure");
8374
8375   if (StackSlot.getNode())
8376     // Load the result.
8377     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8378                        FIST, StackSlot, MachinePointerInfo(),
8379                        false, false, false, 0);
8380
8381   // The node is the result.
8382   return FIST;
8383 }
8384
8385 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8386                                           SelectionDAG &DAG) const {
8387   DebugLoc DL = Op.getDebugLoc();
8388   EVT VT = Op.getValueType();
8389   SDValue In = Op.getOperand(0);
8390   EVT SVT = In.getValueType();
8391
8392   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8393
8394   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8395                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8396                                  In, DAG.getUNDEF(SVT)));
8397 }
8398
8399 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8400   LLVMContext *Context = DAG.getContext();
8401   DebugLoc dl = Op.getDebugLoc();
8402   EVT VT = Op.getValueType();
8403   EVT EltVT = VT;
8404   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8405   if (VT.isVector()) {
8406     EltVT = VT.getVectorElementType();
8407     NumElts = VT.getVectorNumElements();
8408   }
8409   Constant *C;
8410   if (EltVT == MVT::f64)
8411     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8412   else
8413     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8414   C = ConstantVector::getSplat(NumElts, C);
8415   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8416   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8417   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8418                              MachinePointerInfo::getConstantPool(),
8419                              false, false, false, Alignment);
8420   if (VT.isVector()) {
8421     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8422     return DAG.getNode(ISD::BITCAST, dl, VT,
8423                        DAG.getNode(ISD::AND, dl, ANDVT,
8424                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8425                                                Op.getOperand(0)),
8426                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8427   }
8428   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8429 }
8430
8431 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8432   LLVMContext *Context = DAG.getContext();
8433   DebugLoc dl = Op.getDebugLoc();
8434   EVT VT = Op.getValueType();
8435   EVT EltVT = VT;
8436   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8437   if (VT.isVector()) {
8438     EltVT = VT.getVectorElementType();
8439     NumElts = VT.getVectorNumElements();
8440   }
8441   Constant *C;
8442   if (EltVT == MVT::f64)
8443     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8444   else
8445     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8446   C = ConstantVector::getSplat(NumElts, C);
8447   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8448   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8449   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8450                              MachinePointerInfo::getConstantPool(),
8451                              false, false, false, Alignment);
8452   if (VT.isVector()) {
8453     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8454     return DAG.getNode(ISD::BITCAST, dl, VT,
8455                        DAG.getNode(ISD::XOR, dl, XORVT,
8456                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8457                                                Op.getOperand(0)),
8458                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8459   }
8460
8461   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8462 }
8463
8464 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8465   LLVMContext *Context = DAG.getContext();
8466   SDValue Op0 = Op.getOperand(0);
8467   SDValue Op1 = Op.getOperand(1);
8468   DebugLoc dl = Op.getDebugLoc();
8469   EVT VT = Op.getValueType();
8470   EVT SrcVT = Op1.getValueType();
8471
8472   // If second operand is smaller, extend it first.
8473   if (SrcVT.bitsLT(VT)) {
8474     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8475     SrcVT = VT;
8476   }
8477   // And if it is bigger, shrink it first.
8478   if (SrcVT.bitsGT(VT)) {
8479     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8480     SrcVT = VT;
8481   }
8482
8483   // At this point the operands and the result should have the same
8484   // type, and that won't be f80 since that is not custom lowered.
8485
8486   // First get the sign bit of second operand.
8487   SmallVector<Constant*,4> CV;
8488   if (SrcVT == MVT::f64) {
8489     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8490     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8491   } else {
8492     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8493     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8494     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8495     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8496   }
8497   Constant *C = ConstantVector::get(CV);
8498   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8499   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8500                               MachinePointerInfo::getConstantPool(),
8501                               false, false, false, 16);
8502   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8503
8504   // Shift sign bit right or left if the two operands have different types.
8505   if (SrcVT.bitsGT(VT)) {
8506     // Op0 is MVT::f32, Op1 is MVT::f64.
8507     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8508     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8509                           DAG.getConstant(32, MVT::i32));
8510     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8511     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8512                           DAG.getIntPtrConstant(0));
8513   }
8514
8515   // Clear first operand sign bit.
8516   CV.clear();
8517   if (VT == MVT::f64) {
8518     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8519     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8520   } else {
8521     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8522     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8523     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8524     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8525   }
8526   C = ConstantVector::get(CV);
8527   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8528   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8529                               MachinePointerInfo::getConstantPool(),
8530                               false, false, false, 16);
8531   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8532
8533   // Or the value with the sign bit.
8534   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8535 }
8536
8537 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8538   SDValue N0 = Op.getOperand(0);
8539   DebugLoc dl = Op.getDebugLoc();
8540   EVT VT = Op.getValueType();
8541
8542   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8543   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8544                                   DAG.getConstant(1, VT));
8545   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8546 }
8547
8548 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8549 //
8550 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8551   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8552
8553   if (!Subtarget->hasSSE41())
8554     return SDValue();
8555
8556   if (!Op->hasOneUse())
8557     return SDValue();
8558
8559   SDNode *N = Op.getNode();
8560   DebugLoc DL = N->getDebugLoc();
8561
8562   SmallVector<SDValue, 8> Opnds;
8563   DenseMap<SDValue, unsigned> VecInMap;
8564   EVT VT = MVT::Other;
8565
8566   // Recognize a special case where a vector is casted into wide integer to
8567   // test all 0s.
8568   Opnds.push_back(N->getOperand(0));
8569   Opnds.push_back(N->getOperand(1));
8570
8571   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8572     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8573     // BFS traverse all OR'd operands.
8574     if (I->getOpcode() == ISD::OR) {
8575       Opnds.push_back(I->getOperand(0));
8576       Opnds.push_back(I->getOperand(1));
8577       // Re-evaluate the number of nodes to be traversed.
8578       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8579       continue;
8580     }
8581
8582     // Quit if a non-EXTRACT_VECTOR_ELT
8583     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8584       return SDValue();
8585
8586     // Quit if without a constant index.
8587     SDValue Idx = I->getOperand(1);
8588     if (!isa<ConstantSDNode>(Idx))
8589       return SDValue();
8590
8591     SDValue ExtractedFromVec = I->getOperand(0);
8592     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8593     if (M == VecInMap.end()) {
8594       VT = ExtractedFromVec.getValueType();
8595       // Quit if not 128/256-bit vector.
8596       if (!VT.is128BitVector() && !VT.is256BitVector())
8597         return SDValue();
8598       // Quit if not the same type.
8599       if (VecInMap.begin() != VecInMap.end() &&
8600           VT != VecInMap.begin()->first.getValueType())
8601         return SDValue();
8602       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8603     }
8604     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8605   }
8606
8607   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8608          "Not extracted from 128-/256-bit vector.");
8609
8610   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8611   SmallVector<SDValue, 8> VecIns;
8612
8613   for (DenseMap<SDValue, unsigned>::const_iterator
8614         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8615     // Quit if not all elements are used.
8616     if (I->second != FullMask)
8617       return SDValue();
8618     VecIns.push_back(I->first);
8619   }
8620
8621   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8622
8623   // Cast all vectors into TestVT for PTEST.
8624   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8625     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8626
8627   // If more than one full vectors are evaluated, OR them first before PTEST.
8628   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8629     // Each iteration will OR 2 nodes and append the result until there is only
8630     // 1 node left, i.e. the final OR'd value of all vectors.
8631     SDValue LHS = VecIns[Slot];
8632     SDValue RHS = VecIns[Slot + 1];
8633     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8634   }
8635
8636   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8637                      VecIns.back(), VecIns.back());
8638 }
8639
8640 /// Emit nodes that will be selected as "test Op0,Op0", or something
8641 /// equivalent.
8642 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8643                                     SelectionDAG &DAG) const {
8644   DebugLoc dl = Op.getDebugLoc();
8645
8646   // CF and OF aren't always set the way we want. Determine which
8647   // of these we need.
8648   bool NeedCF = false;
8649   bool NeedOF = false;
8650   switch (X86CC) {
8651   default: break;
8652   case X86::COND_A: case X86::COND_AE:
8653   case X86::COND_B: case X86::COND_BE:
8654     NeedCF = true;
8655     break;
8656   case X86::COND_G: case X86::COND_GE:
8657   case X86::COND_L: case X86::COND_LE:
8658   case X86::COND_O: case X86::COND_NO:
8659     NeedOF = true;
8660     break;
8661   }
8662
8663   // See if we can use the EFLAGS value from the operand instead of
8664   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8665   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8666   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8667     // Emit a CMP with 0, which is the TEST pattern.
8668     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8669                        DAG.getConstant(0, Op.getValueType()));
8670
8671   unsigned Opcode = 0;
8672   unsigned NumOperands = 0;
8673
8674   // Truncate operations may prevent the merge of the SETCC instruction
8675   // and the arithmetic intruction before it. Attempt to truncate the operands
8676   // of the arithmetic instruction and use a reduced bit-width instruction.
8677   bool NeedTruncation = false;
8678   SDValue ArithOp = Op;
8679   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8680     SDValue Arith = Op->getOperand(0);
8681     // Both the trunc and the arithmetic op need to have one user each.
8682     if (Arith->hasOneUse())
8683       switch (Arith.getOpcode()) {
8684         default: break;
8685         case ISD::ADD:
8686         case ISD::SUB:
8687         case ISD::AND:
8688         case ISD::OR:
8689         case ISD::XOR: {
8690           NeedTruncation = true;
8691           ArithOp = Arith;
8692         }
8693       }
8694   }
8695
8696   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8697   // which may be the result of a CAST.  We use the variable 'Op', which is the
8698   // non-casted variable when we check for possible users.
8699   switch (ArithOp.getOpcode()) {
8700   case ISD::ADD:
8701     // Due to an isel shortcoming, be conservative if this add is likely to be
8702     // selected as part of a load-modify-store instruction. When the root node
8703     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8704     // uses of other nodes in the match, such as the ADD in this case. This
8705     // leads to the ADD being left around and reselected, with the result being
8706     // two adds in the output.  Alas, even if none our users are stores, that
8707     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8708     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8709     // climbing the DAG back to the root, and it doesn't seem to be worth the
8710     // effort.
8711     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8712          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8713       if (UI->getOpcode() != ISD::CopyToReg &&
8714           UI->getOpcode() != ISD::SETCC &&
8715           UI->getOpcode() != ISD::STORE)
8716         goto default_case;
8717
8718     if (ConstantSDNode *C =
8719         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8720       // An add of one will be selected as an INC.
8721       if (C->getAPIntValue() == 1) {
8722         Opcode = X86ISD::INC;
8723         NumOperands = 1;
8724         break;
8725       }
8726
8727       // An add of negative one (subtract of one) will be selected as a DEC.
8728       if (C->getAPIntValue().isAllOnesValue()) {
8729         Opcode = X86ISD::DEC;
8730         NumOperands = 1;
8731         break;
8732       }
8733     }
8734
8735     // Otherwise use a regular EFLAGS-setting add.
8736     Opcode = X86ISD::ADD;
8737     NumOperands = 2;
8738     break;
8739   case ISD::AND: {
8740     // If the primary and result isn't used, don't bother using X86ISD::AND,
8741     // because a TEST instruction will be better.
8742     bool NonFlagUse = false;
8743     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8744            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8745       SDNode *User = *UI;
8746       unsigned UOpNo = UI.getOperandNo();
8747       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8748         // Look pass truncate.
8749         UOpNo = User->use_begin().getOperandNo();
8750         User = *User->use_begin();
8751       }
8752
8753       if (User->getOpcode() != ISD::BRCOND &&
8754           User->getOpcode() != ISD::SETCC &&
8755           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8756         NonFlagUse = true;
8757         break;
8758       }
8759     }
8760
8761     if (!NonFlagUse)
8762       break;
8763   }
8764     // FALL THROUGH
8765   case ISD::SUB:
8766   case ISD::OR:
8767   case ISD::XOR:
8768     // Due to the ISEL shortcoming noted above, be conservative if this op is
8769     // likely to be selected as part of a load-modify-store instruction.
8770     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8771            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8772       if (UI->getOpcode() == ISD::STORE)
8773         goto default_case;
8774
8775     // Otherwise use a regular EFLAGS-setting instruction.
8776     switch (ArithOp.getOpcode()) {
8777     default: llvm_unreachable("unexpected operator!");
8778     case ISD::SUB: Opcode = X86ISD::SUB; break;
8779     case ISD::XOR: Opcode = X86ISD::XOR; break;
8780     case ISD::AND: Opcode = X86ISD::AND; break;
8781     case ISD::OR: {
8782       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8783         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8784         if (EFLAGS.getNode())
8785           return EFLAGS;
8786       }
8787       Opcode = X86ISD::OR;
8788       break;
8789     }
8790     }
8791
8792     NumOperands = 2;
8793     break;
8794   case X86ISD::ADD:
8795   case X86ISD::SUB:
8796   case X86ISD::INC:
8797   case X86ISD::DEC:
8798   case X86ISD::OR:
8799   case X86ISD::XOR:
8800   case X86ISD::AND:
8801     return SDValue(Op.getNode(), 1);
8802   default:
8803   default_case:
8804     break;
8805   }
8806
8807   // If we found that truncation is beneficial, perform the truncation and
8808   // update 'Op'.
8809   if (NeedTruncation) {
8810     EVT VT = Op.getValueType();
8811     SDValue WideVal = Op->getOperand(0);
8812     EVT WideVT = WideVal.getValueType();
8813     unsigned ConvertedOp = 0;
8814     // Use a target machine opcode to prevent further DAGCombine
8815     // optimizations that may separate the arithmetic operations
8816     // from the setcc node.
8817     switch (WideVal.getOpcode()) {
8818       default: break;
8819       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8820       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8821       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8822       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8823       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8824     }
8825
8826     if (ConvertedOp) {
8827       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8828       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8829         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8830         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8831         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8832       }
8833     }
8834   }
8835
8836   if (Opcode == 0)
8837     // Emit a CMP with 0, which is the TEST pattern.
8838     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8839                        DAG.getConstant(0, Op.getValueType()));
8840
8841   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8842   SmallVector<SDValue, 4> Ops;
8843   for (unsigned i = 0; i != NumOperands; ++i)
8844     Ops.push_back(Op.getOperand(i));
8845
8846   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8847   DAG.ReplaceAllUsesWith(Op, New);
8848   return SDValue(New.getNode(), 1);
8849 }
8850
8851 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8852 /// equivalent.
8853 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8854                                    SelectionDAG &DAG) const {
8855   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8856     if (C->getAPIntValue() == 0)
8857       return EmitTest(Op0, X86CC, DAG);
8858
8859   DebugLoc dl = Op0.getDebugLoc();
8860   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8861        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8862     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8863     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8864     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8865                               Op0, Op1);
8866     return SDValue(Sub.getNode(), 1);
8867   }
8868   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8869 }
8870
8871 /// Convert a comparison if required by the subtarget.
8872 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8873                                                  SelectionDAG &DAG) const {
8874   // If the subtarget does not support the FUCOMI instruction, floating-point
8875   // comparisons have to be converted.
8876   if (Subtarget->hasCMov() ||
8877       Cmp.getOpcode() != X86ISD::CMP ||
8878       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8879       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8880     return Cmp;
8881
8882   // The instruction selector will select an FUCOM instruction instead of
8883   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8884   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8885   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8886   DebugLoc dl = Cmp.getDebugLoc();
8887   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8888   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8889   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8890                             DAG.getConstant(8, MVT::i8));
8891   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8892   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8893 }
8894
8895 static bool isAllOnes(SDValue V) {
8896   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8897   return C && C->isAllOnesValue();
8898 }
8899
8900 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8901 /// if it's possible.
8902 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8903                                      DebugLoc dl, SelectionDAG &DAG) const {
8904   SDValue Op0 = And.getOperand(0);
8905   SDValue Op1 = And.getOperand(1);
8906   if (Op0.getOpcode() == ISD::TRUNCATE)
8907     Op0 = Op0.getOperand(0);
8908   if (Op1.getOpcode() == ISD::TRUNCATE)
8909     Op1 = Op1.getOperand(0);
8910
8911   SDValue LHS, RHS;
8912   if (Op1.getOpcode() == ISD::SHL)
8913     std::swap(Op0, Op1);
8914   if (Op0.getOpcode() == ISD::SHL) {
8915     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8916       if (And00C->getZExtValue() == 1) {
8917         // If we looked past a truncate, check that it's only truncating away
8918         // known zeros.
8919         unsigned BitWidth = Op0.getValueSizeInBits();
8920         unsigned AndBitWidth = And.getValueSizeInBits();
8921         if (BitWidth > AndBitWidth) {
8922           APInt Zeros, Ones;
8923           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8924           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8925             return SDValue();
8926         }
8927         LHS = Op1;
8928         RHS = Op0.getOperand(1);
8929       }
8930   } else if (Op1.getOpcode() == ISD::Constant) {
8931     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8932     uint64_t AndRHSVal = AndRHS->getZExtValue();
8933     SDValue AndLHS = Op0;
8934
8935     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8936       LHS = AndLHS.getOperand(0);
8937       RHS = AndLHS.getOperand(1);
8938     }
8939
8940     // Use BT if the immediate can't be encoded in a TEST instruction.
8941     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8942       LHS = AndLHS;
8943       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8944     }
8945   }
8946
8947   if (LHS.getNode()) {
8948     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
8949     // the condition code later.
8950     bool Invert = false;
8951     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
8952       Invert = true;
8953       LHS = LHS.getOperand(0);
8954     }
8955
8956     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8957     // instruction.  Since the shift amount is in-range-or-undefined, we know
8958     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8959     // the encoding for the i16 version is larger than the i32 version.
8960     // Also promote i16 to i32 for performance / code size reason.
8961     if (LHS.getValueType() == MVT::i8 ||
8962         LHS.getValueType() == MVT::i16)
8963       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8964
8965     // If the operand types disagree, extend the shift amount to match.  Since
8966     // BT ignores high bits (like shifts) we can use anyextend.
8967     if (LHS.getValueType() != RHS.getValueType())
8968       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8969
8970     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8971     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8972     // Flip the condition if the LHS was a not instruction
8973     if (Invert)
8974       Cond = X86::GetOppositeBranchCondition(Cond);
8975     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8976                        DAG.getConstant(Cond, MVT::i8), BT);
8977   }
8978
8979   return SDValue();
8980 }
8981
8982 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8983
8984   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8985
8986   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8987   SDValue Op0 = Op.getOperand(0);
8988   SDValue Op1 = Op.getOperand(1);
8989   DebugLoc dl = Op.getDebugLoc();
8990   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8991
8992   // Optimize to BT if possible.
8993   // Lower (X & (1 << N)) == 0 to BT(X, N).
8994   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8995   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8996   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8997       Op1.getOpcode() == ISD::Constant &&
8998       cast<ConstantSDNode>(Op1)->isNullValue() &&
8999       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9000     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9001     if (NewSetCC.getNode())
9002       return NewSetCC;
9003   }
9004
9005   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9006   // these.
9007   if (Op1.getOpcode() == ISD::Constant &&
9008       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9009        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9010       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9011
9012     // If the input is a setcc, then reuse the input setcc or use a new one with
9013     // the inverted condition.
9014     if (Op0.getOpcode() == X86ISD::SETCC) {
9015       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9016       bool Invert = (CC == ISD::SETNE) ^
9017         cast<ConstantSDNode>(Op1)->isNullValue();
9018       if (!Invert) return Op0;
9019
9020       CCode = X86::GetOppositeBranchCondition(CCode);
9021       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9022                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9023     }
9024   }
9025
9026   bool isFP = Op1.getValueType().isFloatingPoint();
9027   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9028   if (X86CC == X86::COND_INVALID)
9029     return SDValue();
9030
9031   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9032   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9033   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9034                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9035 }
9036
9037 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9038 // ones, and then concatenate the result back.
9039 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9040   EVT VT = Op.getValueType();
9041
9042   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9043          "Unsupported value type for operation");
9044
9045   unsigned NumElems = VT.getVectorNumElements();
9046   DebugLoc dl = Op.getDebugLoc();
9047   SDValue CC = Op.getOperand(2);
9048
9049   // Extract the LHS vectors
9050   SDValue LHS = Op.getOperand(0);
9051   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9052   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9053
9054   // Extract the RHS vectors
9055   SDValue RHS = Op.getOperand(1);
9056   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9057   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9058
9059   // Issue the operation on the smaller types and concatenate the result back
9060   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9061   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9062   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9063                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9064                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9065 }
9066
9067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9068   SDValue Cond;
9069   SDValue Op0 = Op.getOperand(0);
9070   SDValue Op1 = Op.getOperand(1);
9071   SDValue CC = Op.getOperand(2);
9072   EVT VT = Op.getValueType();
9073   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9074   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9075   DebugLoc dl = Op.getDebugLoc();
9076
9077   if (isFP) {
9078 #ifndef NDEBUG
9079     EVT EltVT = Op0.getValueType().getVectorElementType();
9080     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9081 #endif
9082
9083     unsigned SSECC;
9084     bool Swap = false;
9085
9086     // SSE Condition code mapping:
9087     //  0 - EQ
9088     //  1 - LT
9089     //  2 - LE
9090     //  3 - UNORD
9091     //  4 - NEQ
9092     //  5 - NLT
9093     //  6 - NLE
9094     //  7 - ORD
9095     switch (SetCCOpcode) {
9096     default: llvm_unreachable("Unexpected SETCC condition");
9097     case ISD::SETOEQ:
9098     case ISD::SETEQ:  SSECC = 0; break;
9099     case ISD::SETOGT:
9100     case ISD::SETGT: Swap = true; // Fallthrough
9101     case ISD::SETLT:
9102     case ISD::SETOLT: SSECC = 1; break;
9103     case ISD::SETOGE:
9104     case ISD::SETGE: Swap = true; // Fallthrough
9105     case ISD::SETLE:
9106     case ISD::SETOLE: SSECC = 2; break;
9107     case ISD::SETUO:  SSECC = 3; break;
9108     case ISD::SETUNE:
9109     case ISD::SETNE:  SSECC = 4; break;
9110     case ISD::SETULE: Swap = true; // Fallthrough
9111     case ISD::SETUGE: SSECC = 5; break;
9112     case ISD::SETULT: Swap = true; // Fallthrough
9113     case ISD::SETUGT: SSECC = 6; break;
9114     case ISD::SETO:   SSECC = 7; break;
9115     case ISD::SETUEQ:
9116     case ISD::SETONE: SSECC = 8; break;
9117     }
9118     if (Swap)
9119       std::swap(Op0, Op1);
9120
9121     // In the two special cases we can't handle, emit two comparisons.
9122     if (SSECC == 8) {
9123       unsigned CC0, CC1;
9124       unsigned CombineOpc;
9125       if (SetCCOpcode == ISD::SETUEQ) {
9126         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9127       } else {
9128         assert(SetCCOpcode == ISD::SETONE);
9129         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9130       }
9131
9132       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9133                                  DAG.getConstant(CC0, MVT::i8));
9134       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9135                                  DAG.getConstant(CC1, MVT::i8));
9136       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9137     }
9138     // Handle all other FP comparisons here.
9139     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9140                        DAG.getConstant(SSECC, MVT::i8));
9141   }
9142
9143   // Break 256-bit integer vector compare into smaller ones.
9144   if (VT.is256BitVector() && !Subtarget->hasInt256())
9145     return Lower256IntVSETCC(Op, DAG);
9146
9147   // We are handling one of the integer comparisons here.  Since SSE only has
9148   // GT and EQ comparisons for integer, swapping operands and multiple
9149   // operations may be required for some comparisons.
9150   unsigned Opc;
9151   bool Swap = false, Invert = false, FlipSigns = false;
9152
9153   switch (SetCCOpcode) {
9154   default: llvm_unreachable("Unexpected SETCC condition");
9155   case ISD::SETNE:  Invert = true;
9156   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9157   case ISD::SETLT:  Swap = true;
9158   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9159   case ISD::SETGE:  Swap = true;
9160   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9161   case ISD::SETULT: Swap = true;
9162   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9163   case ISD::SETUGE: Swap = true;
9164   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9165   }
9166   if (Swap)
9167     std::swap(Op0, Op1);
9168
9169   // Check that the operation in question is available (most are plain SSE2,
9170   // but PCMPGTQ and PCMPEQQ have different requirements).
9171   if (VT == MVT::v2i64) {
9172     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9173       return SDValue();
9174     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9175       return SDValue();
9176   }
9177
9178   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9179   // bits of the inputs before performing those operations.
9180   if (FlipSigns) {
9181     EVT EltVT = VT.getVectorElementType();
9182     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9183                                       EltVT);
9184     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9185     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9186                                     SignBits.size());
9187     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9188     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9189   }
9190
9191   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9192
9193   // If the logical-not of the result is required, perform that now.
9194   if (Invert)
9195     Result = DAG.getNOT(dl, Result, VT);
9196
9197   return Result;
9198 }
9199
9200 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9201 static bool isX86LogicalCmp(SDValue Op) {
9202   unsigned Opc = Op.getNode()->getOpcode();
9203   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9204       Opc == X86ISD::SAHF)
9205     return true;
9206   if (Op.getResNo() == 1 &&
9207       (Opc == X86ISD::ADD ||
9208        Opc == X86ISD::SUB ||
9209        Opc == X86ISD::ADC ||
9210        Opc == X86ISD::SBB ||
9211        Opc == X86ISD::SMUL ||
9212        Opc == X86ISD::UMUL ||
9213        Opc == X86ISD::INC ||
9214        Opc == X86ISD::DEC ||
9215        Opc == X86ISD::OR ||
9216        Opc == X86ISD::XOR ||
9217        Opc == X86ISD::AND))
9218     return true;
9219
9220   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9221     return true;
9222
9223   return false;
9224 }
9225
9226 static bool isZero(SDValue V) {
9227   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9228   return C && C->isNullValue();
9229 }
9230
9231 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9232   if (V.getOpcode() != ISD::TRUNCATE)
9233     return false;
9234
9235   SDValue VOp0 = V.getOperand(0);
9236   unsigned InBits = VOp0.getValueSizeInBits();
9237   unsigned Bits = V.getValueSizeInBits();
9238   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9239 }
9240
9241 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9242   bool addTest = true;
9243   SDValue Cond  = Op.getOperand(0);
9244   SDValue Op1 = Op.getOperand(1);
9245   SDValue Op2 = Op.getOperand(2);
9246   DebugLoc DL = Op.getDebugLoc();
9247   SDValue CC;
9248
9249   if (Cond.getOpcode() == ISD::SETCC) {
9250     SDValue NewCond = LowerSETCC(Cond, DAG);
9251     if (NewCond.getNode())
9252       Cond = NewCond;
9253   }
9254
9255   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9256   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9257   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9258   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9259   if (Cond.getOpcode() == X86ISD::SETCC &&
9260       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9261       isZero(Cond.getOperand(1).getOperand(1))) {
9262     SDValue Cmp = Cond.getOperand(1);
9263
9264     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9265
9266     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9267         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9268       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9269
9270       SDValue CmpOp0 = Cmp.getOperand(0);
9271       // Apply further optimizations for special cases
9272       // (select (x != 0), -1, 0) -> neg & sbb
9273       // (select (x == 0), 0, -1) -> neg & sbb
9274       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9275         if (YC->isNullValue() &&
9276             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9277           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9278           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9279                                     DAG.getConstant(0, CmpOp0.getValueType()),
9280                                     CmpOp0);
9281           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9282                                     DAG.getConstant(X86::COND_B, MVT::i8),
9283                                     SDValue(Neg.getNode(), 1));
9284           return Res;
9285         }
9286
9287       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9288                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9289       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9290
9291       SDValue Res =   // Res = 0 or -1.
9292         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9293                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9294
9295       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9296         Res = DAG.getNOT(DL, Res, Res.getValueType());
9297
9298       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9299       if (N2C == 0 || !N2C->isNullValue())
9300         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9301       return Res;
9302     }
9303   }
9304
9305   // Look past (and (setcc_carry (cmp ...)), 1).
9306   if (Cond.getOpcode() == ISD::AND &&
9307       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9308     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9309     if (C && C->getAPIntValue() == 1)
9310       Cond = Cond.getOperand(0);
9311   }
9312
9313   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9314   // setting operand in place of the X86ISD::SETCC.
9315   unsigned CondOpcode = Cond.getOpcode();
9316   if (CondOpcode == X86ISD::SETCC ||
9317       CondOpcode == X86ISD::SETCC_CARRY) {
9318     CC = Cond.getOperand(0);
9319
9320     SDValue Cmp = Cond.getOperand(1);
9321     unsigned Opc = Cmp.getOpcode();
9322     EVT VT = Op.getValueType();
9323
9324     bool IllegalFPCMov = false;
9325     if (VT.isFloatingPoint() && !VT.isVector() &&
9326         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9327       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9328
9329     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9330         Opc == X86ISD::BT) { // FIXME
9331       Cond = Cmp;
9332       addTest = false;
9333     }
9334   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9335              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9336              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9337               Cond.getOperand(0).getValueType() != MVT::i8)) {
9338     SDValue LHS = Cond.getOperand(0);
9339     SDValue RHS = Cond.getOperand(1);
9340     unsigned X86Opcode;
9341     unsigned X86Cond;
9342     SDVTList VTs;
9343     switch (CondOpcode) {
9344     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9345     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9346     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9347     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9348     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9349     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9350     default: llvm_unreachable("unexpected overflowing operator");
9351     }
9352     if (CondOpcode == ISD::UMULO)
9353       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9354                           MVT::i32);
9355     else
9356       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9357
9358     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9359
9360     if (CondOpcode == ISD::UMULO)
9361       Cond = X86Op.getValue(2);
9362     else
9363       Cond = X86Op.getValue(1);
9364
9365     CC = DAG.getConstant(X86Cond, MVT::i8);
9366     addTest = false;
9367   }
9368
9369   if (addTest) {
9370     // Look pass the truncate if the high bits are known zero.
9371     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9372         Cond = Cond.getOperand(0);
9373
9374     // We know the result of AND is compared against zero. Try to match
9375     // it to BT.
9376     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9377       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9378       if (NewSetCC.getNode()) {
9379         CC = NewSetCC.getOperand(0);
9380         Cond = NewSetCC.getOperand(1);
9381         addTest = false;
9382       }
9383     }
9384   }
9385
9386   if (addTest) {
9387     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9388     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9389   }
9390
9391   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9392   // a <  b ?  0 : -1 -> RES = setcc_carry
9393   // a >= b ? -1 :  0 -> RES = setcc_carry
9394   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9395   if (Cond.getOpcode() == X86ISD::SUB) {
9396     Cond = ConvertCmpIfNecessary(Cond, DAG);
9397     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9398
9399     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9400         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9401       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9402                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9403       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9404         return DAG.getNOT(DL, Res, Res.getValueType());
9405       return Res;
9406     }
9407   }
9408
9409   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9410   // widen the cmov and push the truncate through. This avoids introducing a new
9411   // branch during isel and doesn't add any extensions.
9412   if (Op.getValueType() == MVT::i8 &&
9413       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9414     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9415     if (T1.getValueType() == T2.getValueType() &&
9416         // Blacklist CopyFromReg to avoid partial register stalls.
9417         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9418       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9419       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9420       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9421     }
9422   }
9423
9424   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9425   // condition is true.
9426   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9427   SDValue Ops[] = { Op2, Op1, CC, Cond };
9428   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9429 }
9430
9431 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9432 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9433 // from the AND / OR.
9434 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9435   Opc = Op.getOpcode();
9436   if (Opc != ISD::OR && Opc != ISD::AND)
9437     return false;
9438   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9439           Op.getOperand(0).hasOneUse() &&
9440           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9441           Op.getOperand(1).hasOneUse());
9442 }
9443
9444 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9445 // 1 and that the SETCC node has a single use.
9446 static bool isXor1OfSetCC(SDValue Op) {
9447   if (Op.getOpcode() != ISD::XOR)
9448     return false;
9449   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9450   if (N1C && N1C->getAPIntValue() == 1) {
9451     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9452       Op.getOperand(0).hasOneUse();
9453   }
9454   return false;
9455 }
9456
9457 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9458   bool addTest = true;
9459   SDValue Chain = Op.getOperand(0);
9460   SDValue Cond  = Op.getOperand(1);
9461   SDValue Dest  = Op.getOperand(2);
9462   DebugLoc dl = Op.getDebugLoc();
9463   SDValue CC;
9464   bool Inverted = false;
9465
9466   if (Cond.getOpcode() == ISD::SETCC) {
9467     // Check for setcc([su]{add,sub,mul}o == 0).
9468     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9469         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9470         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9471         Cond.getOperand(0).getResNo() == 1 &&
9472         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9473          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9474          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9475          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9476          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9477          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9478       Inverted = true;
9479       Cond = Cond.getOperand(0);
9480     } else {
9481       SDValue NewCond = LowerSETCC(Cond, DAG);
9482       if (NewCond.getNode())
9483         Cond = NewCond;
9484     }
9485   }
9486 #if 0
9487   // FIXME: LowerXALUO doesn't handle these!!
9488   else if (Cond.getOpcode() == X86ISD::ADD  ||
9489            Cond.getOpcode() == X86ISD::SUB  ||
9490            Cond.getOpcode() == X86ISD::SMUL ||
9491            Cond.getOpcode() == X86ISD::UMUL)
9492     Cond = LowerXALUO(Cond, DAG);
9493 #endif
9494
9495   // Look pass (and (setcc_carry (cmp ...)), 1).
9496   if (Cond.getOpcode() == ISD::AND &&
9497       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9498     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9499     if (C && C->getAPIntValue() == 1)
9500       Cond = Cond.getOperand(0);
9501   }
9502
9503   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9504   // setting operand in place of the X86ISD::SETCC.
9505   unsigned CondOpcode = Cond.getOpcode();
9506   if (CondOpcode == X86ISD::SETCC ||
9507       CondOpcode == X86ISD::SETCC_CARRY) {
9508     CC = Cond.getOperand(0);
9509
9510     SDValue Cmp = Cond.getOperand(1);
9511     unsigned Opc = Cmp.getOpcode();
9512     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9513     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9514       Cond = Cmp;
9515       addTest = false;
9516     } else {
9517       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9518       default: break;
9519       case X86::COND_O:
9520       case X86::COND_B:
9521         // These can only come from an arithmetic instruction with overflow,
9522         // e.g. SADDO, UADDO.
9523         Cond = Cond.getNode()->getOperand(1);
9524         addTest = false;
9525         break;
9526       }
9527     }
9528   }
9529   CondOpcode = Cond.getOpcode();
9530   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9531       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9532       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9533        Cond.getOperand(0).getValueType() != MVT::i8)) {
9534     SDValue LHS = Cond.getOperand(0);
9535     SDValue RHS = Cond.getOperand(1);
9536     unsigned X86Opcode;
9537     unsigned X86Cond;
9538     SDVTList VTs;
9539     switch (CondOpcode) {
9540     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9541     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9542     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9543     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9544     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9545     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9546     default: llvm_unreachable("unexpected overflowing operator");
9547     }
9548     if (Inverted)
9549       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9550     if (CondOpcode == ISD::UMULO)
9551       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9552                           MVT::i32);
9553     else
9554       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9555
9556     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9557
9558     if (CondOpcode == ISD::UMULO)
9559       Cond = X86Op.getValue(2);
9560     else
9561       Cond = X86Op.getValue(1);
9562
9563     CC = DAG.getConstant(X86Cond, MVT::i8);
9564     addTest = false;
9565   } else {
9566     unsigned CondOpc;
9567     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9568       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9569       if (CondOpc == ISD::OR) {
9570         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9571         // two branches instead of an explicit OR instruction with a
9572         // separate test.
9573         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9574             isX86LogicalCmp(Cmp)) {
9575           CC = Cond.getOperand(0).getOperand(0);
9576           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9577                               Chain, Dest, CC, Cmp);
9578           CC = Cond.getOperand(1).getOperand(0);
9579           Cond = Cmp;
9580           addTest = false;
9581         }
9582       } else { // ISD::AND
9583         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9584         // two branches instead of an explicit AND instruction with a
9585         // separate test. However, we only do this if this block doesn't
9586         // have a fall-through edge, because this requires an explicit
9587         // jmp when the condition is false.
9588         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9589             isX86LogicalCmp(Cmp) &&
9590             Op.getNode()->hasOneUse()) {
9591           X86::CondCode CCode =
9592             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9593           CCode = X86::GetOppositeBranchCondition(CCode);
9594           CC = DAG.getConstant(CCode, MVT::i8);
9595           SDNode *User = *Op.getNode()->use_begin();
9596           // Look for an unconditional branch following this conditional branch.
9597           // We need this because we need to reverse the successors in order
9598           // to implement FCMP_OEQ.
9599           if (User->getOpcode() == ISD::BR) {
9600             SDValue FalseBB = User->getOperand(1);
9601             SDNode *NewBR =
9602               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9603             assert(NewBR == User);
9604             (void)NewBR;
9605             Dest = FalseBB;
9606
9607             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9608                                 Chain, Dest, CC, Cmp);
9609             X86::CondCode CCode =
9610               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9611             CCode = X86::GetOppositeBranchCondition(CCode);
9612             CC = DAG.getConstant(CCode, MVT::i8);
9613             Cond = Cmp;
9614             addTest = false;
9615           }
9616         }
9617       }
9618     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9619       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9620       // It should be transformed during dag combiner except when the condition
9621       // is set by a arithmetics with overflow node.
9622       X86::CondCode CCode =
9623         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9624       CCode = X86::GetOppositeBranchCondition(CCode);
9625       CC = DAG.getConstant(CCode, MVT::i8);
9626       Cond = Cond.getOperand(0).getOperand(1);
9627       addTest = false;
9628     } else if (Cond.getOpcode() == ISD::SETCC &&
9629                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9630       // For FCMP_OEQ, we can emit
9631       // two branches instead of an explicit AND instruction with a
9632       // separate test. However, we only do this if this block doesn't
9633       // have a fall-through edge, because this requires an explicit
9634       // jmp when the condition is false.
9635       if (Op.getNode()->hasOneUse()) {
9636         SDNode *User = *Op.getNode()->use_begin();
9637         // Look for an unconditional branch following this conditional branch.
9638         // We need this because we need to reverse the successors in order
9639         // to implement FCMP_OEQ.
9640         if (User->getOpcode() == ISD::BR) {
9641           SDValue FalseBB = User->getOperand(1);
9642           SDNode *NewBR =
9643             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9644           assert(NewBR == User);
9645           (void)NewBR;
9646           Dest = FalseBB;
9647
9648           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9649                                     Cond.getOperand(0), Cond.getOperand(1));
9650           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9651           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9652           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9653                               Chain, Dest, CC, Cmp);
9654           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9655           Cond = Cmp;
9656           addTest = false;
9657         }
9658       }
9659     } else if (Cond.getOpcode() == ISD::SETCC &&
9660                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9661       // For FCMP_UNE, we can emit
9662       // two branches instead of an explicit AND instruction with a
9663       // separate test. However, we only do this if this block doesn't
9664       // have a fall-through edge, because this requires an explicit
9665       // jmp when the condition is false.
9666       if (Op.getNode()->hasOneUse()) {
9667         SDNode *User = *Op.getNode()->use_begin();
9668         // Look for an unconditional branch following this conditional branch.
9669         // We need this because we need to reverse the successors in order
9670         // to implement FCMP_UNE.
9671         if (User->getOpcode() == ISD::BR) {
9672           SDValue FalseBB = User->getOperand(1);
9673           SDNode *NewBR =
9674             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9675           assert(NewBR == User);
9676           (void)NewBR;
9677
9678           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9679                                     Cond.getOperand(0), Cond.getOperand(1));
9680           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9681           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9682           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9683                               Chain, Dest, CC, Cmp);
9684           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9685           Cond = Cmp;
9686           addTest = false;
9687           Dest = FalseBB;
9688         }
9689       }
9690     }
9691   }
9692
9693   if (addTest) {
9694     // Look pass the truncate if the high bits are known zero.
9695     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9696         Cond = Cond.getOperand(0);
9697
9698     // We know the result of AND is compared against zero. Try to match
9699     // it to BT.
9700     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9701       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9702       if (NewSetCC.getNode()) {
9703         CC = NewSetCC.getOperand(0);
9704         Cond = NewSetCC.getOperand(1);
9705         addTest = false;
9706       }
9707     }
9708   }
9709
9710   if (addTest) {
9711     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9712     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9713   }
9714   Cond = ConvertCmpIfNecessary(Cond, DAG);
9715   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9716                      Chain, Dest, CC, Cond);
9717 }
9718
9719 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9720 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9721 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9722 // that the guard pages used by the OS virtual memory manager are allocated in
9723 // correct sequence.
9724 SDValue
9725 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9726                                            SelectionDAG &DAG) const {
9727   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9728           getTargetMachine().Options.EnableSegmentedStacks) &&
9729          "This should be used only on Windows targets or when segmented stacks "
9730          "are being used");
9731   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9732   DebugLoc dl = Op.getDebugLoc();
9733
9734   // Get the inputs.
9735   SDValue Chain = Op.getOperand(0);
9736   SDValue Size  = Op.getOperand(1);
9737   // FIXME: Ensure alignment here
9738
9739   bool Is64Bit = Subtarget->is64Bit();
9740   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9741
9742   if (getTargetMachine().Options.EnableSegmentedStacks) {
9743     MachineFunction &MF = DAG.getMachineFunction();
9744     MachineRegisterInfo &MRI = MF.getRegInfo();
9745
9746     if (Is64Bit) {
9747       // The 64 bit implementation of segmented stacks needs to clobber both r10
9748       // r11. This makes it impossible to use it along with nested parameters.
9749       const Function *F = MF.getFunction();
9750
9751       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9752            I != E; ++I)
9753         if (I->hasNestAttr())
9754           report_fatal_error("Cannot use segmented stacks with functions that "
9755                              "have nested arguments.");
9756     }
9757
9758     const TargetRegisterClass *AddrRegClass =
9759       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9760     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9761     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9762     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9763                                 DAG.getRegister(Vreg, SPTy));
9764     SDValue Ops1[2] = { Value, Chain };
9765     return DAG.getMergeValues(Ops1, 2, dl);
9766   } else {
9767     SDValue Flag;
9768     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9769
9770     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9771     Flag = Chain.getValue(1);
9772     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9773
9774     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9775     Flag = Chain.getValue(1);
9776
9777     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
9778                                SPTy).getValue(1);
9779
9780     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9781     return DAG.getMergeValues(Ops1, 2, dl);
9782   }
9783 }
9784
9785 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9786   MachineFunction &MF = DAG.getMachineFunction();
9787   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9788
9789   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9790   DebugLoc DL = Op.getDebugLoc();
9791
9792   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9793     // vastart just stores the address of the VarArgsFrameIndex slot into the
9794     // memory location argument.
9795     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9796                                    getPointerTy());
9797     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9798                         MachinePointerInfo(SV), false, false, 0);
9799   }
9800
9801   // __va_list_tag:
9802   //   gp_offset         (0 - 6 * 8)
9803   //   fp_offset         (48 - 48 + 8 * 16)
9804   //   overflow_arg_area (point to parameters coming in memory).
9805   //   reg_save_area
9806   SmallVector<SDValue, 8> MemOps;
9807   SDValue FIN = Op.getOperand(1);
9808   // Store gp_offset
9809   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9810                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9811                                                MVT::i32),
9812                                FIN, MachinePointerInfo(SV), false, false, 0);
9813   MemOps.push_back(Store);
9814
9815   // Store fp_offset
9816   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9817                     FIN, DAG.getIntPtrConstant(4));
9818   Store = DAG.getStore(Op.getOperand(0), DL,
9819                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9820                                        MVT::i32),
9821                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9822   MemOps.push_back(Store);
9823
9824   // Store ptr to overflow_arg_area
9825   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9826                     FIN, DAG.getIntPtrConstant(4));
9827   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9828                                     getPointerTy());
9829   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9830                        MachinePointerInfo(SV, 8),
9831                        false, false, 0);
9832   MemOps.push_back(Store);
9833
9834   // Store ptr to reg_save_area.
9835   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9836                     FIN, DAG.getIntPtrConstant(8));
9837   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9838                                     getPointerTy());
9839   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9840                        MachinePointerInfo(SV, 16), false, false, 0);
9841   MemOps.push_back(Store);
9842   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9843                      &MemOps[0], MemOps.size());
9844 }
9845
9846 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9847   assert(Subtarget->is64Bit() &&
9848          "LowerVAARG only handles 64-bit va_arg!");
9849   assert((Subtarget->isTargetLinux() ||
9850           Subtarget->isTargetDarwin()) &&
9851           "Unhandled target in LowerVAARG");
9852   assert(Op.getNode()->getNumOperands() == 4);
9853   SDValue Chain = Op.getOperand(0);
9854   SDValue SrcPtr = Op.getOperand(1);
9855   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9856   unsigned Align = Op.getConstantOperandVal(3);
9857   DebugLoc dl = Op.getDebugLoc();
9858
9859   EVT ArgVT = Op.getNode()->getValueType(0);
9860   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9861   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9862   uint8_t ArgMode;
9863
9864   // Decide which area this value should be read from.
9865   // TODO: Implement the AMD64 ABI in its entirety. This simple
9866   // selection mechanism works only for the basic types.
9867   if (ArgVT == MVT::f80) {
9868     llvm_unreachable("va_arg for f80 not yet implemented");
9869   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9870     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9871   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9872     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9873   } else {
9874     llvm_unreachable("Unhandled argument type in LowerVAARG");
9875   }
9876
9877   if (ArgMode == 2) {
9878     // Sanity Check: Make sure using fp_offset makes sense.
9879     assert(!getTargetMachine().Options.UseSoftFloat &&
9880            !(DAG.getMachineFunction()
9881                 .getFunction()->getFnAttributes()
9882                 .hasAttribute(Attribute::NoImplicitFloat)) &&
9883            Subtarget->hasSSE1());
9884   }
9885
9886   // Insert VAARG_64 node into the DAG
9887   // VAARG_64 returns two values: Variable Argument Address, Chain
9888   SmallVector<SDValue, 11> InstOps;
9889   InstOps.push_back(Chain);
9890   InstOps.push_back(SrcPtr);
9891   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9892   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9893   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9894   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9895   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9896                                           VTs, &InstOps[0], InstOps.size(),
9897                                           MVT::i64,
9898                                           MachinePointerInfo(SV),
9899                                           /*Align=*/0,
9900                                           /*Volatile=*/false,
9901                                           /*ReadMem=*/true,
9902                                           /*WriteMem=*/true);
9903   Chain = VAARG.getValue(1);
9904
9905   // Load the next argument and return it
9906   return DAG.getLoad(ArgVT, dl,
9907                      Chain,
9908                      VAARG,
9909                      MachinePointerInfo(),
9910                      false, false, false, 0);
9911 }
9912
9913 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9914                            SelectionDAG &DAG) {
9915   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9916   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9917   SDValue Chain = Op.getOperand(0);
9918   SDValue DstPtr = Op.getOperand(1);
9919   SDValue SrcPtr = Op.getOperand(2);
9920   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9921   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9922   DebugLoc DL = Op.getDebugLoc();
9923
9924   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9925                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9926                        false,
9927                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9928 }
9929
9930 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9931 // may or may not be a constant. Takes immediate version of shift as input.
9932 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9933                                    SDValue SrcOp, SDValue ShAmt,
9934                                    SelectionDAG &DAG) {
9935   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9936
9937   if (isa<ConstantSDNode>(ShAmt)) {
9938     // Constant may be a TargetConstant. Use a regular constant.
9939     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9940     switch (Opc) {
9941       default: llvm_unreachable("Unknown target vector shift node");
9942       case X86ISD::VSHLI:
9943       case X86ISD::VSRLI:
9944       case X86ISD::VSRAI:
9945         return DAG.getNode(Opc, dl, VT, SrcOp,
9946                            DAG.getConstant(ShiftAmt, MVT::i32));
9947     }
9948   }
9949
9950   // Change opcode to non-immediate version
9951   switch (Opc) {
9952     default: llvm_unreachable("Unknown target vector shift node");
9953     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9954     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9955     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9956   }
9957
9958   // Need to build a vector containing shift amount
9959   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9960   SDValue ShOps[4];
9961   ShOps[0] = ShAmt;
9962   ShOps[1] = DAG.getConstant(0, MVT::i32);
9963   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9964   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9965
9966   // The return type has to be a 128-bit type with the same element
9967   // type as the input type.
9968   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9969   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9970
9971   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9972   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9973 }
9974
9975 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9976   DebugLoc dl = Op.getDebugLoc();
9977   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9978   switch (IntNo) {
9979   default: return SDValue();    // Don't custom lower most intrinsics.
9980   // Comparison intrinsics.
9981   case Intrinsic::x86_sse_comieq_ss:
9982   case Intrinsic::x86_sse_comilt_ss:
9983   case Intrinsic::x86_sse_comile_ss:
9984   case Intrinsic::x86_sse_comigt_ss:
9985   case Intrinsic::x86_sse_comige_ss:
9986   case Intrinsic::x86_sse_comineq_ss:
9987   case Intrinsic::x86_sse_ucomieq_ss:
9988   case Intrinsic::x86_sse_ucomilt_ss:
9989   case Intrinsic::x86_sse_ucomile_ss:
9990   case Intrinsic::x86_sse_ucomigt_ss:
9991   case Intrinsic::x86_sse_ucomige_ss:
9992   case Intrinsic::x86_sse_ucomineq_ss:
9993   case Intrinsic::x86_sse2_comieq_sd:
9994   case Intrinsic::x86_sse2_comilt_sd:
9995   case Intrinsic::x86_sse2_comile_sd:
9996   case Intrinsic::x86_sse2_comigt_sd:
9997   case Intrinsic::x86_sse2_comige_sd:
9998   case Intrinsic::x86_sse2_comineq_sd:
9999   case Intrinsic::x86_sse2_ucomieq_sd:
10000   case Intrinsic::x86_sse2_ucomilt_sd:
10001   case Intrinsic::x86_sse2_ucomile_sd:
10002   case Intrinsic::x86_sse2_ucomigt_sd:
10003   case Intrinsic::x86_sse2_ucomige_sd:
10004   case Intrinsic::x86_sse2_ucomineq_sd: {
10005     unsigned Opc;
10006     ISD::CondCode CC;
10007     switch (IntNo) {
10008     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10009     case Intrinsic::x86_sse_comieq_ss:
10010     case Intrinsic::x86_sse2_comieq_sd:
10011       Opc = X86ISD::COMI;
10012       CC = ISD::SETEQ;
10013       break;
10014     case Intrinsic::x86_sse_comilt_ss:
10015     case Intrinsic::x86_sse2_comilt_sd:
10016       Opc = X86ISD::COMI;
10017       CC = ISD::SETLT;
10018       break;
10019     case Intrinsic::x86_sse_comile_ss:
10020     case Intrinsic::x86_sse2_comile_sd:
10021       Opc = X86ISD::COMI;
10022       CC = ISD::SETLE;
10023       break;
10024     case Intrinsic::x86_sse_comigt_ss:
10025     case Intrinsic::x86_sse2_comigt_sd:
10026       Opc = X86ISD::COMI;
10027       CC = ISD::SETGT;
10028       break;
10029     case Intrinsic::x86_sse_comige_ss:
10030     case Intrinsic::x86_sse2_comige_sd:
10031       Opc = X86ISD::COMI;
10032       CC = ISD::SETGE;
10033       break;
10034     case Intrinsic::x86_sse_comineq_ss:
10035     case Intrinsic::x86_sse2_comineq_sd:
10036       Opc = X86ISD::COMI;
10037       CC = ISD::SETNE;
10038       break;
10039     case Intrinsic::x86_sse_ucomieq_ss:
10040     case Intrinsic::x86_sse2_ucomieq_sd:
10041       Opc = X86ISD::UCOMI;
10042       CC = ISD::SETEQ;
10043       break;
10044     case Intrinsic::x86_sse_ucomilt_ss:
10045     case Intrinsic::x86_sse2_ucomilt_sd:
10046       Opc = X86ISD::UCOMI;
10047       CC = ISD::SETLT;
10048       break;
10049     case Intrinsic::x86_sse_ucomile_ss:
10050     case Intrinsic::x86_sse2_ucomile_sd:
10051       Opc = X86ISD::UCOMI;
10052       CC = ISD::SETLE;
10053       break;
10054     case Intrinsic::x86_sse_ucomigt_ss:
10055     case Intrinsic::x86_sse2_ucomigt_sd:
10056       Opc = X86ISD::UCOMI;
10057       CC = ISD::SETGT;
10058       break;
10059     case Intrinsic::x86_sse_ucomige_ss:
10060     case Intrinsic::x86_sse2_ucomige_sd:
10061       Opc = X86ISD::UCOMI;
10062       CC = ISD::SETGE;
10063       break;
10064     case Intrinsic::x86_sse_ucomineq_ss:
10065     case Intrinsic::x86_sse2_ucomineq_sd:
10066       Opc = X86ISD::UCOMI;
10067       CC = ISD::SETNE;
10068       break;
10069     }
10070
10071     SDValue LHS = Op.getOperand(1);
10072     SDValue RHS = Op.getOperand(2);
10073     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10074     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10075     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10076     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10077                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10078     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10079   }
10080
10081   // Arithmetic intrinsics.
10082   case Intrinsic::x86_sse2_pmulu_dq:
10083   case Intrinsic::x86_avx2_pmulu_dq:
10084     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10085                        Op.getOperand(1), Op.getOperand(2));
10086
10087   // SSE2/AVX2 sub with unsigned saturation intrinsics
10088   case Intrinsic::x86_sse2_psubus_b:
10089   case Intrinsic::x86_sse2_psubus_w:
10090   case Intrinsic::x86_avx2_psubus_b:
10091   case Intrinsic::x86_avx2_psubus_w:
10092     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10093                        Op.getOperand(1), Op.getOperand(2));
10094
10095   // SSE3/AVX horizontal add/sub intrinsics
10096   case Intrinsic::x86_sse3_hadd_ps:
10097   case Intrinsic::x86_sse3_hadd_pd:
10098   case Intrinsic::x86_avx_hadd_ps_256:
10099   case Intrinsic::x86_avx_hadd_pd_256:
10100   case Intrinsic::x86_sse3_hsub_ps:
10101   case Intrinsic::x86_sse3_hsub_pd:
10102   case Intrinsic::x86_avx_hsub_ps_256:
10103   case Intrinsic::x86_avx_hsub_pd_256:
10104   case Intrinsic::x86_ssse3_phadd_w_128:
10105   case Intrinsic::x86_ssse3_phadd_d_128:
10106   case Intrinsic::x86_avx2_phadd_w:
10107   case Intrinsic::x86_avx2_phadd_d:
10108   case Intrinsic::x86_ssse3_phsub_w_128:
10109   case Intrinsic::x86_ssse3_phsub_d_128:
10110   case Intrinsic::x86_avx2_phsub_w:
10111   case Intrinsic::x86_avx2_phsub_d: {
10112     unsigned Opcode;
10113     switch (IntNo) {
10114     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10115     case Intrinsic::x86_sse3_hadd_ps:
10116     case Intrinsic::x86_sse3_hadd_pd:
10117     case Intrinsic::x86_avx_hadd_ps_256:
10118     case Intrinsic::x86_avx_hadd_pd_256:
10119       Opcode = X86ISD::FHADD;
10120       break;
10121     case Intrinsic::x86_sse3_hsub_ps:
10122     case Intrinsic::x86_sse3_hsub_pd:
10123     case Intrinsic::x86_avx_hsub_ps_256:
10124     case Intrinsic::x86_avx_hsub_pd_256:
10125       Opcode = X86ISD::FHSUB;
10126       break;
10127     case Intrinsic::x86_ssse3_phadd_w_128:
10128     case Intrinsic::x86_ssse3_phadd_d_128:
10129     case Intrinsic::x86_avx2_phadd_w:
10130     case Intrinsic::x86_avx2_phadd_d:
10131       Opcode = X86ISD::HADD;
10132       break;
10133     case Intrinsic::x86_ssse3_phsub_w_128:
10134     case Intrinsic::x86_ssse3_phsub_d_128:
10135     case Intrinsic::x86_avx2_phsub_w:
10136     case Intrinsic::x86_avx2_phsub_d:
10137       Opcode = X86ISD::HSUB;
10138       break;
10139     }
10140     return DAG.getNode(Opcode, dl, Op.getValueType(),
10141                        Op.getOperand(1), Op.getOperand(2));
10142   }
10143
10144   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10145   case Intrinsic::x86_sse2_pmaxu_b:
10146   case Intrinsic::x86_sse41_pmaxuw:
10147   case Intrinsic::x86_sse41_pmaxud:
10148   case Intrinsic::x86_avx2_pmaxu_b:
10149   case Intrinsic::x86_avx2_pmaxu_w:
10150   case Intrinsic::x86_avx2_pmaxu_d:
10151     return DAG.getNode(X86ISD::UMAX, dl, Op.getValueType(),
10152                        Op.getOperand(1), Op.getOperand(2));
10153   case Intrinsic::x86_sse2_pminu_b:
10154   case Intrinsic::x86_sse41_pminuw:
10155   case Intrinsic::x86_sse41_pminud:
10156   case Intrinsic::x86_avx2_pminu_b:
10157   case Intrinsic::x86_avx2_pminu_w:
10158   case Intrinsic::x86_avx2_pminu_d:
10159     return DAG.getNode(X86ISD::UMIN, dl, Op.getValueType(),
10160                        Op.getOperand(1), Op.getOperand(2));
10161   case Intrinsic::x86_sse41_pmaxsb:
10162   case Intrinsic::x86_sse2_pmaxs_w:
10163   case Intrinsic::x86_sse41_pmaxsd:
10164   case Intrinsic::x86_avx2_pmaxs_b:
10165   case Intrinsic::x86_avx2_pmaxs_w:
10166   case Intrinsic::x86_avx2_pmaxs_d:
10167     return DAG.getNode(X86ISD::SMAX, dl, Op.getValueType(),
10168                        Op.getOperand(1), Op.getOperand(2));
10169   case Intrinsic::x86_sse41_pminsb:
10170   case Intrinsic::x86_sse2_pmins_w:
10171   case Intrinsic::x86_sse41_pminsd:
10172   case Intrinsic::x86_avx2_pmins_b:
10173   case Intrinsic::x86_avx2_pmins_w:
10174   case Intrinsic::x86_avx2_pmins_d:
10175     return DAG.getNode(X86ISD::SMIN, dl, Op.getValueType(),
10176                        Op.getOperand(1), Op.getOperand(2));
10177
10178   // AVX2 variable shift intrinsics
10179   case Intrinsic::x86_avx2_psllv_d:
10180   case Intrinsic::x86_avx2_psllv_q:
10181   case Intrinsic::x86_avx2_psllv_d_256:
10182   case Intrinsic::x86_avx2_psllv_q_256:
10183   case Intrinsic::x86_avx2_psrlv_d:
10184   case Intrinsic::x86_avx2_psrlv_q:
10185   case Intrinsic::x86_avx2_psrlv_d_256:
10186   case Intrinsic::x86_avx2_psrlv_q_256:
10187   case Intrinsic::x86_avx2_psrav_d:
10188   case Intrinsic::x86_avx2_psrav_d_256: {
10189     unsigned Opcode;
10190     switch (IntNo) {
10191     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10192     case Intrinsic::x86_avx2_psllv_d:
10193     case Intrinsic::x86_avx2_psllv_q:
10194     case Intrinsic::x86_avx2_psllv_d_256:
10195     case Intrinsic::x86_avx2_psllv_q_256:
10196       Opcode = ISD::SHL;
10197       break;
10198     case Intrinsic::x86_avx2_psrlv_d:
10199     case Intrinsic::x86_avx2_psrlv_q:
10200     case Intrinsic::x86_avx2_psrlv_d_256:
10201     case Intrinsic::x86_avx2_psrlv_q_256:
10202       Opcode = ISD::SRL;
10203       break;
10204     case Intrinsic::x86_avx2_psrav_d:
10205     case Intrinsic::x86_avx2_psrav_d_256:
10206       Opcode = ISD::SRA;
10207       break;
10208     }
10209     return DAG.getNode(Opcode, dl, Op.getValueType(),
10210                        Op.getOperand(1), Op.getOperand(2));
10211   }
10212
10213   case Intrinsic::x86_ssse3_pshuf_b_128:
10214   case Intrinsic::x86_avx2_pshuf_b:
10215     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10216                        Op.getOperand(1), Op.getOperand(2));
10217
10218   case Intrinsic::x86_ssse3_psign_b_128:
10219   case Intrinsic::x86_ssse3_psign_w_128:
10220   case Intrinsic::x86_ssse3_psign_d_128:
10221   case Intrinsic::x86_avx2_psign_b:
10222   case Intrinsic::x86_avx2_psign_w:
10223   case Intrinsic::x86_avx2_psign_d:
10224     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10225                        Op.getOperand(1), Op.getOperand(2));
10226
10227   case Intrinsic::x86_sse41_insertps:
10228     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10229                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10230
10231   case Intrinsic::x86_avx_vperm2f128_ps_256:
10232   case Intrinsic::x86_avx_vperm2f128_pd_256:
10233   case Intrinsic::x86_avx_vperm2f128_si_256:
10234   case Intrinsic::x86_avx2_vperm2i128:
10235     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10236                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10237
10238   case Intrinsic::x86_avx2_permd:
10239   case Intrinsic::x86_avx2_permps:
10240     // Operands intentionally swapped. Mask is last operand to intrinsic,
10241     // but second operand for node/intruction.
10242     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10243                        Op.getOperand(2), Op.getOperand(1));
10244
10245   // ptest and testp intrinsics. The intrinsic these come from are designed to
10246   // return an integer value, not just an instruction so lower it to the ptest
10247   // or testp pattern and a setcc for the result.
10248   case Intrinsic::x86_sse41_ptestz:
10249   case Intrinsic::x86_sse41_ptestc:
10250   case Intrinsic::x86_sse41_ptestnzc:
10251   case Intrinsic::x86_avx_ptestz_256:
10252   case Intrinsic::x86_avx_ptestc_256:
10253   case Intrinsic::x86_avx_ptestnzc_256:
10254   case Intrinsic::x86_avx_vtestz_ps:
10255   case Intrinsic::x86_avx_vtestc_ps:
10256   case Intrinsic::x86_avx_vtestnzc_ps:
10257   case Intrinsic::x86_avx_vtestz_pd:
10258   case Intrinsic::x86_avx_vtestc_pd:
10259   case Intrinsic::x86_avx_vtestnzc_pd:
10260   case Intrinsic::x86_avx_vtestz_ps_256:
10261   case Intrinsic::x86_avx_vtestc_ps_256:
10262   case Intrinsic::x86_avx_vtestnzc_ps_256:
10263   case Intrinsic::x86_avx_vtestz_pd_256:
10264   case Intrinsic::x86_avx_vtestc_pd_256:
10265   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10266     bool IsTestPacked = false;
10267     unsigned X86CC;
10268     switch (IntNo) {
10269     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10270     case Intrinsic::x86_avx_vtestz_ps:
10271     case Intrinsic::x86_avx_vtestz_pd:
10272     case Intrinsic::x86_avx_vtestz_ps_256:
10273     case Intrinsic::x86_avx_vtestz_pd_256:
10274       IsTestPacked = true; // Fallthrough
10275     case Intrinsic::x86_sse41_ptestz:
10276     case Intrinsic::x86_avx_ptestz_256:
10277       // ZF = 1
10278       X86CC = X86::COND_E;
10279       break;
10280     case Intrinsic::x86_avx_vtestc_ps:
10281     case Intrinsic::x86_avx_vtestc_pd:
10282     case Intrinsic::x86_avx_vtestc_ps_256:
10283     case Intrinsic::x86_avx_vtestc_pd_256:
10284       IsTestPacked = true; // Fallthrough
10285     case Intrinsic::x86_sse41_ptestc:
10286     case Intrinsic::x86_avx_ptestc_256:
10287       // CF = 1
10288       X86CC = X86::COND_B;
10289       break;
10290     case Intrinsic::x86_avx_vtestnzc_ps:
10291     case Intrinsic::x86_avx_vtestnzc_pd:
10292     case Intrinsic::x86_avx_vtestnzc_ps_256:
10293     case Intrinsic::x86_avx_vtestnzc_pd_256:
10294       IsTestPacked = true; // Fallthrough
10295     case Intrinsic::x86_sse41_ptestnzc:
10296     case Intrinsic::x86_avx_ptestnzc_256:
10297       // ZF and CF = 0
10298       X86CC = X86::COND_A;
10299       break;
10300     }
10301
10302     SDValue LHS = Op.getOperand(1);
10303     SDValue RHS = Op.getOperand(2);
10304     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10305     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10306     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10307     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10308     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10309   }
10310
10311   // SSE/AVX shift intrinsics
10312   case Intrinsic::x86_sse2_psll_w:
10313   case Intrinsic::x86_sse2_psll_d:
10314   case Intrinsic::x86_sse2_psll_q:
10315   case Intrinsic::x86_avx2_psll_w:
10316   case Intrinsic::x86_avx2_psll_d:
10317   case Intrinsic::x86_avx2_psll_q:
10318   case Intrinsic::x86_sse2_psrl_w:
10319   case Intrinsic::x86_sse2_psrl_d:
10320   case Intrinsic::x86_sse2_psrl_q:
10321   case Intrinsic::x86_avx2_psrl_w:
10322   case Intrinsic::x86_avx2_psrl_d:
10323   case Intrinsic::x86_avx2_psrl_q:
10324   case Intrinsic::x86_sse2_psra_w:
10325   case Intrinsic::x86_sse2_psra_d:
10326   case Intrinsic::x86_avx2_psra_w:
10327   case Intrinsic::x86_avx2_psra_d: {
10328     unsigned Opcode;
10329     switch (IntNo) {
10330     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10331     case Intrinsic::x86_sse2_psll_w:
10332     case Intrinsic::x86_sse2_psll_d:
10333     case Intrinsic::x86_sse2_psll_q:
10334     case Intrinsic::x86_avx2_psll_w:
10335     case Intrinsic::x86_avx2_psll_d:
10336     case Intrinsic::x86_avx2_psll_q:
10337       Opcode = X86ISD::VSHL;
10338       break;
10339     case Intrinsic::x86_sse2_psrl_w:
10340     case Intrinsic::x86_sse2_psrl_d:
10341     case Intrinsic::x86_sse2_psrl_q:
10342     case Intrinsic::x86_avx2_psrl_w:
10343     case Intrinsic::x86_avx2_psrl_d:
10344     case Intrinsic::x86_avx2_psrl_q:
10345       Opcode = X86ISD::VSRL;
10346       break;
10347     case Intrinsic::x86_sse2_psra_w:
10348     case Intrinsic::x86_sse2_psra_d:
10349     case Intrinsic::x86_avx2_psra_w:
10350     case Intrinsic::x86_avx2_psra_d:
10351       Opcode = X86ISD::VSRA;
10352       break;
10353     }
10354     return DAG.getNode(Opcode, dl, Op.getValueType(),
10355                        Op.getOperand(1), Op.getOperand(2));
10356   }
10357
10358   // SSE/AVX immediate shift intrinsics
10359   case Intrinsic::x86_sse2_pslli_w:
10360   case Intrinsic::x86_sse2_pslli_d:
10361   case Intrinsic::x86_sse2_pslli_q:
10362   case Intrinsic::x86_avx2_pslli_w:
10363   case Intrinsic::x86_avx2_pslli_d:
10364   case Intrinsic::x86_avx2_pslli_q:
10365   case Intrinsic::x86_sse2_psrli_w:
10366   case Intrinsic::x86_sse2_psrli_d:
10367   case Intrinsic::x86_sse2_psrli_q:
10368   case Intrinsic::x86_avx2_psrli_w:
10369   case Intrinsic::x86_avx2_psrli_d:
10370   case Intrinsic::x86_avx2_psrli_q:
10371   case Intrinsic::x86_sse2_psrai_w:
10372   case Intrinsic::x86_sse2_psrai_d:
10373   case Intrinsic::x86_avx2_psrai_w:
10374   case Intrinsic::x86_avx2_psrai_d: {
10375     unsigned Opcode;
10376     switch (IntNo) {
10377     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10378     case Intrinsic::x86_sse2_pslli_w:
10379     case Intrinsic::x86_sse2_pslli_d:
10380     case Intrinsic::x86_sse2_pslli_q:
10381     case Intrinsic::x86_avx2_pslli_w:
10382     case Intrinsic::x86_avx2_pslli_d:
10383     case Intrinsic::x86_avx2_pslli_q:
10384       Opcode = X86ISD::VSHLI;
10385       break;
10386     case Intrinsic::x86_sse2_psrli_w:
10387     case Intrinsic::x86_sse2_psrli_d:
10388     case Intrinsic::x86_sse2_psrli_q:
10389     case Intrinsic::x86_avx2_psrli_w:
10390     case Intrinsic::x86_avx2_psrli_d:
10391     case Intrinsic::x86_avx2_psrli_q:
10392       Opcode = X86ISD::VSRLI;
10393       break;
10394     case Intrinsic::x86_sse2_psrai_w:
10395     case Intrinsic::x86_sse2_psrai_d:
10396     case Intrinsic::x86_avx2_psrai_w:
10397     case Intrinsic::x86_avx2_psrai_d:
10398       Opcode = X86ISD::VSRAI;
10399       break;
10400     }
10401     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10402                                Op.getOperand(1), Op.getOperand(2), DAG);
10403   }
10404
10405   case Intrinsic::x86_sse42_pcmpistria128:
10406   case Intrinsic::x86_sse42_pcmpestria128:
10407   case Intrinsic::x86_sse42_pcmpistric128:
10408   case Intrinsic::x86_sse42_pcmpestric128:
10409   case Intrinsic::x86_sse42_pcmpistrio128:
10410   case Intrinsic::x86_sse42_pcmpestrio128:
10411   case Intrinsic::x86_sse42_pcmpistris128:
10412   case Intrinsic::x86_sse42_pcmpestris128:
10413   case Intrinsic::x86_sse42_pcmpistriz128:
10414   case Intrinsic::x86_sse42_pcmpestriz128: {
10415     unsigned Opcode;
10416     unsigned X86CC;
10417     switch (IntNo) {
10418     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10419     case Intrinsic::x86_sse42_pcmpistria128:
10420       Opcode = X86ISD::PCMPISTRI;
10421       X86CC = X86::COND_A;
10422       break;
10423     case Intrinsic::x86_sse42_pcmpestria128:
10424       Opcode = X86ISD::PCMPESTRI;
10425       X86CC = X86::COND_A;
10426       break;
10427     case Intrinsic::x86_sse42_pcmpistric128:
10428       Opcode = X86ISD::PCMPISTRI;
10429       X86CC = X86::COND_B;
10430       break;
10431     case Intrinsic::x86_sse42_pcmpestric128:
10432       Opcode = X86ISD::PCMPESTRI;
10433       X86CC = X86::COND_B;
10434       break;
10435     case Intrinsic::x86_sse42_pcmpistrio128:
10436       Opcode = X86ISD::PCMPISTRI;
10437       X86CC = X86::COND_O;
10438       break;
10439     case Intrinsic::x86_sse42_pcmpestrio128:
10440       Opcode = X86ISD::PCMPESTRI;
10441       X86CC = X86::COND_O;
10442       break;
10443     case Intrinsic::x86_sse42_pcmpistris128:
10444       Opcode = X86ISD::PCMPISTRI;
10445       X86CC = X86::COND_S;
10446       break;
10447     case Intrinsic::x86_sse42_pcmpestris128:
10448       Opcode = X86ISD::PCMPESTRI;
10449       X86CC = X86::COND_S;
10450       break;
10451     case Intrinsic::x86_sse42_pcmpistriz128:
10452       Opcode = X86ISD::PCMPISTRI;
10453       X86CC = X86::COND_E;
10454       break;
10455     case Intrinsic::x86_sse42_pcmpestriz128:
10456       Opcode = X86ISD::PCMPESTRI;
10457       X86CC = X86::COND_E;
10458       break;
10459     }
10460     SmallVector<SDValue, 5> NewOps;
10461     NewOps.append(Op->op_begin()+1, Op->op_end());
10462     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10463     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10464     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10465                                 DAG.getConstant(X86CC, MVT::i8),
10466                                 SDValue(PCMP.getNode(), 1));
10467     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10468   }
10469
10470   case Intrinsic::x86_sse42_pcmpistri128:
10471   case Intrinsic::x86_sse42_pcmpestri128: {
10472     unsigned Opcode;
10473     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10474       Opcode = X86ISD::PCMPISTRI;
10475     else
10476       Opcode = X86ISD::PCMPESTRI;
10477
10478     SmallVector<SDValue, 5> NewOps;
10479     NewOps.append(Op->op_begin()+1, Op->op_end());
10480     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10481     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10482   }
10483   case Intrinsic::x86_fma_vfmadd_ps:
10484   case Intrinsic::x86_fma_vfmadd_pd:
10485   case Intrinsic::x86_fma_vfmsub_ps:
10486   case Intrinsic::x86_fma_vfmsub_pd:
10487   case Intrinsic::x86_fma_vfnmadd_ps:
10488   case Intrinsic::x86_fma_vfnmadd_pd:
10489   case Intrinsic::x86_fma_vfnmsub_ps:
10490   case Intrinsic::x86_fma_vfnmsub_pd:
10491   case Intrinsic::x86_fma_vfmaddsub_ps:
10492   case Intrinsic::x86_fma_vfmaddsub_pd:
10493   case Intrinsic::x86_fma_vfmsubadd_ps:
10494   case Intrinsic::x86_fma_vfmsubadd_pd:
10495   case Intrinsic::x86_fma_vfmadd_ps_256:
10496   case Intrinsic::x86_fma_vfmadd_pd_256:
10497   case Intrinsic::x86_fma_vfmsub_ps_256:
10498   case Intrinsic::x86_fma_vfmsub_pd_256:
10499   case Intrinsic::x86_fma_vfnmadd_ps_256:
10500   case Intrinsic::x86_fma_vfnmadd_pd_256:
10501   case Intrinsic::x86_fma_vfnmsub_ps_256:
10502   case Intrinsic::x86_fma_vfnmsub_pd_256:
10503   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10504   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10505   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10506   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10507     unsigned Opc;
10508     switch (IntNo) {
10509     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10510     case Intrinsic::x86_fma_vfmadd_ps:
10511     case Intrinsic::x86_fma_vfmadd_pd:
10512     case Intrinsic::x86_fma_vfmadd_ps_256:
10513     case Intrinsic::x86_fma_vfmadd_pd_256:
10514       Opc = X86ISD::FMADD;
10515       break;
10516     case Intrinsic::x86_fma_vfmsub_ps:
10517     case Intrinsic::x86_fma_vfmsub_pd:
10518     case Intrinsic::x86_fma_vfmsub_ps_256:
10519     case Intrinsic::x86_fma_vfmsub_pd_256:
10520       Opc = X86ISD::FMSUB;
10521       break;
10522     case Intrinsic::x86_fma_vfnmadd_ps:
10523     case Intrinsic::x86_fma_vfnmadd_pd:
10524     case Intrinsic::x86_fma_vfnmadd_ps_256:
10525     case Intrinsic::x86_fma_vfnmadd_pd_256:
10526       Opc = X86ISD::FNMADD;
10527       break;
10528     case Intrinsic::x86_fma_vfnmsub_ps:
10529     case Intrinsic::x86_fma_vfnmsub_pd:
10530     case Intrinsic::x86_fma_vfnmsub_ps_256:
10531     case Intrinsic::x86_fma_vfnmsub_pd_256:
10532       Opc = X86ISD::FNMSUB;
10533       break;
10534     case Intrinsic::x86_fma_vfmaddsub_ps:
10535     case Intrinsic::x86_fma_vfmaddsub_pd:
10536     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10537     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10538       Opc = X86ISD::FMADDSUB;
10539       break;
10540     case Intrinsic::x86_fma_vfmsubadd_ps:
10541     case Intrinsic::x86_fma_vfmsubadd_pd:
10542     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10543     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10544       Opc = X86ISD::FMSUBADD;
10545       break;
10546     }
10547
10548     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10549                        Op.getOperand(2), Op.getOperand(3));
10550   }
10551   }
10552 }
10553
10554 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10555   DebugLoc dl = Op.getDebugLoc();
10556   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10557   switch (IntNo) {
10558   default: return SDValue();    // Don't custom lower most intrinsics.
10559
10560   // RDRAND intrinsics.
10561   case Intrinsic::x86_rdrand_16:
10562   case Intrinsic::x86_rdrand_32:
10563   case Intrinsic::x86_rdrand_64: {
10564     // Emit the node with the right value type.
10565     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10566     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10567
10568     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10569     // return the value from Rand, which is always 0, casted to i32.
10570     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10571                       DAG.getConstant(1, Op->getValueType(1)),
10572                       DAG.getConstant(X86::COND_B, MVT::i32),
10573                       SDValue(Result.getNode(), 1) };
10574     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10575                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10576                                   Ops, 4);
10577
10578     // Return { result, isValid, chain }.
10579     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10580                        SDValue(Result.getNode(), 2));
10581   }
10582   }
10583 }
10584
10585 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10586                                            SelectionDAG &DAG) const {
10587   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10588   MFI->setReturnAddressIsTaken(true);
10589
10590   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10591   DebugLoc dl = Op.getDebugLoc();
10592   EVT PtrVT = getPointerTy();
10593
10594   if (Depth > 0) {
10595     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10596     SDValue Offset =
10597       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10598     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10599                        DAG.getNode(ISD::ADD, dl, PtrVT,
10600                                    FrameAddr, Offset),
10601                        MachinePointerInfo(), false, false, false, 0);
10602   }
10603
10604   // Just load the return address.
10605   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10606   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10607                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10608 }
10609
10610 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10611   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10612   MFI->setFrameAddressIsTaken(true);
10613
10614   EVT VT = Op.getValueType();
10615   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10616   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10617   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10618   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10619   while (Depth--)
10620     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10621                             MachinePointerInfo(),
10622                             false, false, false, 0);
10623   return FrameAddr;
10624 }
10625
10626 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10627                                                      SelectionDAG &DAG) const {
10628   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10629 }
10630
10631 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10632   SDValue Chain     = Op.getOperand(0);
10633   SDValue Offset    = Op.getOperand(1);
10634   SDValue Handler   = Op.getOperand(2);
10635   DebugLoc dl       = Op.getDebugLoc();
10636
10637   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10638                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10639                                      getPointerTy());
10640   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10641
10642   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10643                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10644   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10645   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10646                        false, false, 0);
10647   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10648
10649   return DAG.getNode(X86ISD::EH_RETURN, dl,
10650                      MVT::Other,
10651                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10652 }
10653
10654 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10655                                                SelectionDAG &DAG) const {
10656   DebugLoc DL = Op.getDebugLoc();
10657   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10658                      DAG.getVTList(MVT::i32, MVT::Other),
10659                      Op.getOperand(0), Op.getOperand(1));
10660 }
10661
10662 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10663                                                 SelectionDAG &DAG) const {
10664   DebugLoc DL = Op.getDebugLoc();
10665   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10666                      Op.getOperand(0), Op.getOperand(1));
10667 }
10668
10669 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10670   return Op.getOperand(0);
10671 }
10672
10673 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10674                                                 SelectionDAG &DAG) const {
10675   SDValue Root = Op.getOperand(0);
10676   SDValue Trmp = Op.getOperand(1); // trampoline
10677   SDValue FPtr = Op.getOperand(2); // nested function
10678   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10679   DebugLoc dl  = Op.getDebugLoc();
10680
10681   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10682   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10683
10684   if (Subtarget->is64Bit()) {
10685     SDValue OutChains[6];
10686
10687     // Large code-model.
10688     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10689     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10690
10691     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10692     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10693
10694     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10695
10696     // Load the pointer to the nested function into R11.
10697     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10698     SDValue Addr = Trmp;
10699     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10700                                 Addr, MachinePointerInfo(TrmpAddr),
10701                                 false, false, 0);
10702
10703     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10704                        DAG.getConstant(2, MVT::i64));
10705     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10706                                 MachinePointerInfo(TrmpAddr, 2),
10707                                 false, false, 2);
10708
10709     // Load the 'nest' parameter value into R10.
10710     // R10 is specified in X86CallingConv.td
10711     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10712     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10713                        DAG.getConstant(10, MVT::i64));
10714     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10715                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10716                                 false, false, 0);
10717
10718     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10719                        DAG.getConstant(12, MVT::i64));
10720     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10721                                 MachinePointerInfo(TrmpAddr, 12),
10722                                 false, false, 2);
10723
10724     // Jump to the nested function.
10725     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10726     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10727                        DAG.getConstant(20, MVT::i64));
10728     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10729                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10730                                 false, false, 0);
10731
10732     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10733     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10734                        DAG.getConstant(22, MVT::i64));
10735     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10736                                 MachinePointerInfo(TrmpAddr, 22),
10737                                 false, false, 0);
10738
10739     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10740   } else {
10741     const Function *Func =
10742       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10743     CallingConv::ID CC = Func->getCallingConv();
10744     unsigned NestReg;
10745
10746     switch (CC) {
10747     default:
10748       llvm_unreachable("Unsupported calling convention");
10749     case CallingConv::C:
10750     case CallingConv::X86_StdCall: {
10751       // Pass 'nest' parameter in ECX.
10752       // Must be kept in sync with X86CallingConv.td
10753       NestReg = X86::ECX;
10754
10755       // Check that ECX wasn't needed by an 'inreg' parameter.
10756       FunctionType *FTy = Func->getFunctionType();
10757       const AttributeSet &Attrs = Func->getAttributes();
10758
10759       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10760         unsigned InRegCount = 0;
10761         unsigned Idx = 1;
10762
10763         for (FunctionType::param_iterator I = FTy->param_begin(),
10764              E = FTy->param_end(); I != E; ++I, ++Idx)
10765           if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
10766             // FIXME: should only count parameters that are lowered to integers.
10767             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10768
10769         if (InRegCount > 2) {
10770           report_fatal_error("Nest register in use - reduce number of inreg"
10771                              " parameters!");
10772         }
10773       }
10774       break;
10775     }
10776     case CallingConv::X86_FastCall:
10777     case CallingConv::X86_ThisCall:
10778     case CallingConv::Fast:
10779       // Pass 'nest' parameter in EAX.
10780       // Must be kept in sync with X86CallingConv.td
10781       NestReg = X86::EAX;
10782       break;
10783     }
10784
10785     SDValue OutChains[4];
10786     SDValue Addr, Disp;
10787
10788     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10789                        DAG.getConstant(10, MVT::i32));
10790     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10791
10792     // This is storing the opcode for MOV32ri.
10793     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10794     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10795     OutChains[0] = DAG.getStore(Root, dl,
10796                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10797                                 Trmp, MachinePointerInfo(TrmpAddr),
10798                                 false, false, 0);
10799
10800     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10801                        DAG.getConstant(1, MVT::i32));
10802     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10803                                 MachinePointerInfo(TrmpAddr, 1),
10804                                 false, false, 1);
10805
10806     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10807     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10808                        DAG.getConstant(5, MVT::i32));
10809     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10810                                 MachinePointerInfo(TrmpAddr, 5),
10811                                 false, false, 1);
10812
10813     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10814                        DAG.getConstant(6, MVT::i32));
10815     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10816                                 MachinePointerInfo(TrmpAddr, 6),
10817                                 false, false, 1);
10818
10819     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10820   }
10821 }
10822
10823 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10824                                             SelectionDAG &DAG) const {
10825   /*
10826    The rounding mode is in bits 11:10 of FPSR, and has the following
10827    settings:
10828      00 Round to nearest
10829      01 Round to -inf
10830      10 Round to +inf
10831      11 Round to 0
10832
10833   FLT_ROUNDS, on the other hand, expects the following:
10834     -1 Undefined
10835      0 Round to 0
10836      1 Round to nearest
10837      2 Round to +inf
10838      3 Round to -inf
10839
10840   To perform the conversion, we do:
10841     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10842   */
10843
10844   MachineFunction &MF = DAG.getMachineFunction();
10845   const TargetMachine &TM = MF.getTarget();
10846   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10847   unsigned StackAlignment = TFI.getStackAlignment();
10848   EVT VT = Op.getValueType();
10849   DebugLoc DL = Op.getDebugLoc();
10850
10851   // Save FP Control Word to stack slot
10852   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10853   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10854
10855   MachineMemOperand *MMO =
10856    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10857                            MachineMemOperand::MOStore, 2, 2);
10858
10859   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10860   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10861                                           DAG.getVTList(MVT::Other),
10862                                           Ops, 2, MVT::i16, MMO);
10863
10864   // Load FP Control Word from stack slot
10865   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10866                             MachinePointerInfo(), false, false, false, 0);
10867
10868   // Transform as necessary
10869   SDValue CWD1 =
10870     DAG.getNode(ISD::SRL, DL, MVT::i16,
10871                 DAG.getNode(ISD::AND, DL, MVT::i16,
10872                             CWD, DAG.getConstant(0x800, MVT::i16)),
10873                 DAG.getConstant(11, MVT::i8));
10874   SDValue CWD2 =
10875     DAG.getNode(ISD::SRL, DL, MVT::i16,
10876                 DAG.getNode(ISD::AND, DL, MVT::i16,
10877                             CWD, DAG.getConstant(0x400, MVT::i16)),
10878                 DAG.getConstant(9, MVT::i8));
10879
10880   SDValue RetVal =
10881     DAG.getNode(ISD::AND, DL, MVT::i16,
10882                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10883                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10884                             DAG.getConstant(1, MVT::i16)),
10885                 DAG.getConstant(3, MVT::i16));
10886
10887   return DAG.getNode((VT.getSizeInBits() < 16 ?
10888                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10889 }
10890
10891 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10892   EVT VT = Op.getValueType();
10893   EVT OpVT = VT;
10894   unsigned NumBits = VT.getSizeInBits();
10895   DebugLoc dl = Op.getDebugLoc();
10896
10897   Op = Op.getOperand(0);
10898   if (VT == MVT::i8) {
10899     // Zero extend to i32 since there is not an i8 bsr.
10900     OpVT = MVT::i32;
10901     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10902   }
10903
10904   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10905   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10906   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10907
10908   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10909   SDValue Ops[] = {
10910     Op,
10911     DAG.getConstant(NumBits+NumBits-1, OpVT),
10912     DAG.getConstant(X86::COND_E, MVT::i8),
10913     Op.getValue(1)
10914   };
10915   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10916
10917   // Finally xor with NumBits-1.
10918   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10919
10920   if (VT == MVT::i8)
10921     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10922   return Op;
10923 }
10924
10925 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10926   EVT VT = Op.getValueType();
10927   EVT OpVT = VT;
10928   unsigned NumBits = VT.getSizeInBits();
10929   DebugLoc dl = Op.getDebugLoc();
10930
10931   Op = Op.getOperand(0);
10932   if (VT == MVT::i8) {
10933     // Zero extend to i32 since there is not an i8 bsr.
10934     OpVT = MVT::i32;
10935     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10936   }
10937
10938   // Issue a bsr (scan bits in reverse).
10939   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10940   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10941
10942   // And xor with NumBits-1.
10943   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10944
10945   if (VT == MVT::i8)
10946     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10947   return Op;
10948 }
10949
10950 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10951   EVT VT = Op.getValueType();
10952   unsigned NumBits = VT.getSizeInBits();
10953   DebugLoc dl = Op.getDebugLoc();
10954   Op = Op.getOperand(0);
10955
10956   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10957   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10958   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10959
10960   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10961   SDValue Ops[] = {
10962     Op,
10963     DAG.getConstant(NumBits, VT),
10964     DAG.getConstant(X86::COND_E, MVT::i8),
10965     Op.getValue(1)
10966   };
10967   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10968 }
10969
10970 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10971 // ones, and then concatenate the result back.
10972 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10973   EVT VT = Op.getValueType();
10974
10975   assert(VT.is256BitVector() && VT.isInteger() &&
10976          "Unsupported value type for operation");
10977
10978   unsigned NumElems = VT.getVectorNumElements();
10979   DebugLoc dl = Op.getDebugLoc();
10980
10981   // Extract the LHS vectors
10982   SDValue LHS = Op.getOperand(0);
10983   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10984   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10985
10986   // Extract the RHS vectors
10987   SDValue RHS = Op.getOperand(1);
10988   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10989   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10990
10991   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10992   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10993
10994   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10995                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10996                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10997 }
10998
10999 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11000   assert(Op.getValueType().is256BitVector() &&
11001          Op.getValueType().isInteger() &&
11002          "Only handle AVX 256-bit vector integer operation");
11003   return Lower256IntArith(Op, DAG);
11004 }
11005
11006 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11007   assert(Op.getValueType().is256BitVector() &&
11008          Op.getValueType().isInteger() &&
11009          "Only handle AVX 256-bit vector integer operation");
11010   return Lower256IntArith(Op, DAG);
11011 }
11012
11013 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11014                         SelectionDAG &DAG) {
11015   DebugLoc dl = Op.getDebugLoc();
11016   EVT VT = Op.getValueType();
11017
11018   // Decompose 256-bit ops into smaller 128-bit ops.
11019   if (VT.is256BitVector() && !Subtarget->hasInt256())
11020     return Lower256IntArith(Op, DAG);
11021
11022   SDValue A = Op.getOperand(0);
11023   SDValue B = Op.getOperand(1);
11024
11025   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11026   if (VT == MVT::v4i32) {
11027     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11028            "Should not custom lower when pmuldq is available!");
11029
11030     // Extract the odd parts.
11031     const int UnpackMask[] = { 1, -1, 3, -1 };
11032     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11033     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11034
11035     // Multiply the even parts.
11036     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11037     // Now multiply odd parts.
11038     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11039
11040     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11041     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11042
11043     // Merge the two vectors back together with a shuffle. This expands into 2
11044     // shuffles.
11045     const int ShufMask[] = { 0, 4, 2, 6 };
11046     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11047   }
11048
11049   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11050          "Only know how to lower V2I64/V4I64 multiply");
11051
11052   //  Ahi = psrlqi(a, 32);
11053   //  Bhi = psrlqi(b, 32);
11054   //
11055   //  AloBlo = pmuludq(a, b);
11056   //  AloBhi = pmuludq(a, Bhi);
11057   //  AhiBlo = pmuludq(Ahi, b);
11058
11059   //  AloBhi = psllqi(AloBhi, 32);
11060   //  AhiBlo = psllqi(AhiBlo, 32);
11061   //  return AloBlo + AloBhi + AhiBlo;
11062
11063   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11064
11065   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11066   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11067
11068   // Bit cast to 32-bit vectors for MULUDQ
11069   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11070   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11071   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11072   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11073   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11074
11075   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11076   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11077   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11078
11079   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11080   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11081
11082   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11083   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11084 }
11085
11086 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11087
11088   EVT VT = Op.getValueType();
11089   DebugLoc dl = Op.getDebugLoc();
11090   SDValue R = Op.getOperand(0);
11091   SDValue Amt = Op.getOperand(1);
11092   LLVMContext *Context = DAG.getContext();
11093
11094   if (!Subtarget->hasSSE2())
11095     return SDValue();
11096
11097   // Optimize shl/srl/sra with constant shift amount.
11098   if (isSplatVector(Amt.getNode())) {
11099     SDValue SclrAmt = Amt->getOperand(0);
11100     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11101       uint64_t ShiftAmt = C->getZExtValue();
11102
11103       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11104           (Subtarget->hasInt256() &&
11105            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11106         if (Op.getOpcode() == ISD::SHL)
11107           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11108                              DAG.getConstant(ShiftAmt, MVT::i32));
11109         if (Op.getOpcode() == ISD::SRL)
11110           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11111                              DAG.getConstant(ShiftAmt, MVT::i32));
11112         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11113           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11114                              DAG.getConstant(ShiftAmt, MVT::i32));
11115       }
11116
11117       if (VT == MVT::v16i8) {
11118         if (Op.getOpcode() == ISD::SHL) {
11119           // Make a large shift.
11120           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11121                                     DAG.getConstant(ShiftAmt, MVT::i32));
11122           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11123           // Zero out the rightmost bits.
11124           SmallVector<SDValue, 16> V(16,
11125                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11126                                                      MVT::i8));
11127           return DAG.getNode(ISD::AND, dl, VT, SHL,
11128                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11129         }
11130         if (Op.getOpcode() == ISD::SRL) {
11131           // Make a large shift.
11132           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11133                                     DAG.getConstant(ShiftAmt, MVT::i32));
11134           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11135           // Zero out the leftmost bits.
11136           SmallVector<SDValue, 16> V(16,
11137                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11138                                                      MVT::i8));
11139           return DAG.getNode(ISD::AND, dl, VT, SRL,
11140                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11141         }
11142         if (Op.getOpcode() == ISD::SRA) {
11143           if (ShiftAmt == 7) {
11144             // R s>> 7  ===  R s< 0
11145             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11146             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11147           }
11148
11149           // R s>> a === ((R u>> a) ^ m) - m
11150           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11151           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11152                                                          MVT::i8));
11153           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11154           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11155           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11156           return Res;
11157         }
11158         llvm_unreachable("Unknown shift opcode.");
11159       }
11160
11161       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11162         if (Op.getOpcode() == ISD::SHL) {
11163           // Make a large shift.
11164           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11165                                     DAG.getConstant(ShiftAmt, MVT::i32));
11166           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11167           // Zero out the rightmost bits.
11168           SmallVector<SDValue, 32> V(32,
11169                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11170                                                      MVT::i8));
11171           return DAG.getNode(ISD::AND, dl, VT, SHL,
11172                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11173         }
11174         if (Op.getOpcode() == ISD::SRL) {
11175           // Make a large shift.
11176           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11177                                     DAG.getConstant(ShiftAmt, MVT::i32));
11178           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11179           // Zero out the leftmost bits.
11180           SmallVector<SDValue, 32> V(32,
11181                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11182                                                      MVT::i8));
11183           return DAG.getNode(ISD::AND, dl, VT, SRL,
11184                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11185         }
11186         if (Op.getOpcode() == ISD::SRA) {
11187           if (ShiftAmt == 7) {
11188             // R s>> 7  ===  R s< 0
11189             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11190             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11191           }
11192
11193           // R s>> a === ((R u>> a) ^ m) - m
11194           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11195           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11196                                                          MVT::i8));
11197           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11198           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11199           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11200           return Res;
11201         }
11202         llvm_unreachable("Unknown shift opcode.");
11203       }
11204     }
11205   }
11206
11207   // Lower SHL with variable shift amount.
11208   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11209     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11210                      DAG.getConstant(23, MVT::i32));
11211
11212     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11213     Constant *C = ConstantDataVector::get(*Context, CV);
11214     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11215     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11216                                  MachinePointerInfo::getConstantPool(),
11217                                  false, false, false, 16);
11218
11219     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11220     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11221     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11222     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11223   }
11224   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11225     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11226
11227     // a = a << 5;
11228     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11229                      DAG.getConstant(5, MVT::i32));
11230     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11231
11232     // Turn 'a' into a mask suitable for VSELECT
11233     SDValue VSelM = DAG.getConstant(0x80, VT);
11234     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11235     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11236
11237     SDValue CM1 = DAG.getConstant(0x0f, VT);
11238     SDValue CM2 = DAG.getConstant(0x3f, VT);
11239
11240     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11241     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11242     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11243                             DAG.getConstant(4, MVT::i32), DAG);
11244     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11245     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11246
11247     // a += a
11248     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11249     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11250     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11251
11252     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11253     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11254     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11255                             DAG.getConstant(2, MVT::i32), DAG);
11256     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11257     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11258
11259     // a += a
11260     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11261     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11262     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11263
11264     // return VSELECT(r, r+r, a);
11265     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11266                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11267     return R;
11268   }
11269
11270   // Decompose 256-bit shifts into smaller 128-bit shifts.
11271   if (VT.is256BitVector()) {
11272     unsigned NumElems = VT.getVectorNumElements();
11273     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11274     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11275
11276     // Extract the two vectors
11277     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11278     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11279
11280     // Recreate the shift amount vectors
11281     SDValue Amt1, Amt2;
11282     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11283       // Constant shift amount
11284       SmallVector<SDValue, 4> Amt1Csts;
11285       SmallVector<SDValue, 4> Amt2Csts;
11286       for (unsigned i = 0; i != NumElems/2; ++i)
11287         Amt1Csts.push_back(Amt->getOperand(i));
11288       for (unsigned i = NumElems/2; i != NumElems; ++i)
11289         Amt2Csts.push_back(Amt->getOperand(i));
11290
11291       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11292                                  &Amt1Csts[0], NumElems/2);
11293       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11294                                  &Amt2Csts[0], NumElems/2);
11295     } else {
11296       // Variable shift amount
11297       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11298       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11299     }
11300
11301     // Issue new vector shifts for the smaller types
11302     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11303     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11304
11305     // Concatenate the result back
11306     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11307   }
11308
11309   return SDValue();
11310 }
11311
11312 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11313   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11314   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11315   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11316   // has only one use.
11317   SDNode *N = Op.getNode();
11318   SDValue LHS = N->getOperand(0);
11319   SDValue RHS = N->getOperand(1);
11320   unsigned BaseOp = 0;
11321   unsigned Cond = 0;
11322   DebugLoc DL = Op.getDebugLoc();
11323   switch (Op.getOpcode()) {
11324   default: llvm_unreachable("Unknown ovf instruction!");
11325   case ISD::SADDO:
11326     // A subtract of one will be selected as a INC. Note that INC doesn't
11327     // set CF, so we can't do this for UADDO.
11328     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11329       if (C->isOne()) {
11330         BaseOp = X86ISD::INC;
11331         Cond = X86::COND_O;
11332         break;
11333       }
11334     BaseOp = X86ISD::ADD;
11335     Cond = X86::COND_O;
11336     break;
11337   case ISD::UADDO:
11338     BaseOp = X86ISD::ADD;
11339     Cond = X86::COND_B;
11340     break;
11341   case ISD::SSUBO:
11342     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11343     // set CF, so we can't do this for USUBO.
11344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11345       if (C->isOne()) {
11346         BaseOp = X86ISD::DEC;
11347         Cond = X86::COND_O;
11348         break;
11349       }
11350     BaseOp = X86ISD::SUB;
11351     Cond = X86::COND_O;
11352     break;
11353   case ISD::USUBO:
11354     BaseOp = X86ISD::SUB;
11355     Cond = X86::COND_B;
11356     break;
11357   case ISD::SMULO:
11358     BaseOp = X86ISD::SMUL;
11359     Cond = X86::COND_O;
11360     break;
11361   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11362     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11363                                  MVT::i32);
11364     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11365
11366     SDValue SetCC =
11367       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11368                   DAG.getConstant(X86::COND_O, MVT::i32),
11369                   SDValue(Sum.getNode(), 2));
11370
11371     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11372   }
11373   }
11374
11375   // Also sets EFLAGS.
11376   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11377   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11378
11379   SDValue SetCC =
11380     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11381                 DAG.getConstant(Cond, MVT::i32),
11382                 SDValue(Sum.getNode(), 1));
11383
11384   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11385 }
11386
11387 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11388                                                   SelectionDAG &DAG) const {
11389   DebugLoc dl = Op.getDebugLoc();
11390   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11391   EVT VT = Op.getValueType();
11392
11393   if (!Subtarget->hasSSE2() || !VT.isVector())
11394     return SDValue();
11395
11396   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11397                       ExtraVT.getScalarType().getSizeInBits();
11398   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11399
11400   switch (VT.getSimpleVT().SimpleTy) {
11401     default: return SDValue();
11402     case MVT::v8i32:
11403     case MVT::v16i16:
11404       if (!Subtarget->hasFp256())
11405         return SDValue();
11406       if (!Subtarget->hasInt256()) {
11407         // needs to be split
11408         unsigned NumElems = VT.getVectorNumElements();
11409
11410         // Extract the LHS vectors
11411         SDValue LHS = Op.getOperand(0);
11412         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11413         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11414
11415         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11416         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11417
11418         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11419         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11420         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11421                                    ExtraNumElems/2);
11422         SDValue Extra = DAG.getValueType(ExtraVT);
11423
11424         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11425         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11426
11427         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11428       }
11429       // fall through
11430     case MVT::v4i32:
11431     case MVT::v8i16: {
11432       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11433                                          Op.getOperand(0), ShAmt, DAG);
11434       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11435     }
11436   }
11437 }
11438
11439 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11440                               SelectionDAG &DAG) {
11441   DebugLoc dl = Op.getDebugLoc();
11442
11443   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11444   // There isn't any reason to disable it if the target processor supports it.
11445   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11446     SDValue Chain = Op.getOperand(0);
11447     SDValue Zero = DAG.getConstant(0, MVT::i32);
11448     SDValue Ops[] = {
11449       DAG.getRegister(X86::ESP, MVT::i32), // Base
11450       DAG.getTargetConstant(1, MVT::i8),   // Scale
11451       DAG.getRegister(0, MVT::i32),        // Index
11452       DAG.getTargetConstant(0, MVT::i32),  // Disp
11453       DAG.getRegister(0, MVT::i32),        // Segment.
11454       Zero,
11455       Chain
11456     };
11457     SDNode *Res =
11458       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11459                           array_lengthof(Ops));
11460     return SDValue(Res, 0);
11461   }
11462
11463   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11464   if (!isDev)
11465     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11466
11467   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11468   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11469   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11470   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11471
11472   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11473   if (!Op1 && !Op2 && !Op3 && Op4)
11474     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11475
11476   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11477   if (Op1 && !Op2 && !Op3 && !Op4)
11478     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11479
11480   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11481   //           (MFENCE)>;
11482   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11483 }
11484
11485 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11486                                  SelectionDAG &DAG) {
11487   DebugLoc dl = Op.getDebugLoc();
11488   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11489     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11490   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11491     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11492
11493   // The only fence that needs an instruction is a sequentially-consistent
11494   // cross-thread fence.
11495   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11496     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11497     // no-sse2). There isn't any reason to disable it if the target processor
11498     // supports it.
11499     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11500       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11501
11502     SDValue Chain = Op.getOperand(0);
11503     SDValue Zero = DAG.getConstant(0, MVT::i32);
11504     SDValue Ops[] = {
11505       DAG.getRegister(X86::ESP, MVT::i32), // Base
11506       DAG.getTargetConstant(1, MVT::i8),   // Scale
11507       DAG.getRegister(0, MVT::i32),        // Index
11508       DAG.getTargetConstant(0, MVT::i32),  // Disp
11509       DAG.getRegister(0, MVT::i32),        // Segment.
11510       Zero,
11511       Chain
11512     };
11513     SDNode *Res =
11514       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11515                          array_lengthof(Ops));
11516     return SDValue(Res, 0);
11517   }
11518
11519   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11520   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11521 }
11522
11523 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11524                              SelectionDAG &DAG) {
11525   EVT T = Op.getValueType();
11526   DebugLoc DL = Op.getDebugLoc();
11527   unsigned Reg = 0;
11528   unsigned size = 0;
11529   switch(T.getSimpleVT().SimpleTy) {
11530   default: llvm_unreachable("Invalid value type!");
11531   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11532   case MVT::i16: Reg = X86::AX;  size = 2; break;
11533   case MVT::i32: Reg = X86::EAX; size = 4; break;
11534   case MVT::i64:
11535     assert(Subtarget->is64Bit() && "Node not type legal!");
11536     Reg = X86::RAX; size = 8;
11537     break;
11538   }
11539   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11540                                     Op.getOperand(2), SDValue());
11541   SDValue Ops[] = { cpIn.getValue(0),
11542                     Op.getOperand(1),
11543                     Op.getOperand(3),
11544                     DAG.getTargetConstant(size, MVT::i8),
11545                     cpIn.getValue(1) };
11546   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11547   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11548   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11549                                            Ops, 5, T, MMO);
11550   SDValue cpOut =
11551     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11552   return cpOut;
11553 }
11554
11555 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11556                                      SelectionDAG &DAG) {
11557   assert(Subtarget->is64Bit() && "Result not type legalized?");
11558   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11559   SDValue TheChain = Op.getOperand(0);
11560   DebugLoc dl = Op.getDebugLoc();
11561   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11562   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11563   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11564                                    rax.getValue(2));
11565   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11566                             DAG.getConstant(32, MVT::i8));
11567   SDValue Ops[] = {
11568     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11569     rdx.getValue(1)
11570   };
11571   return DAG.getMergeValues(Ops, 2, dl);
11572 }
11573
11574 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11575   EVT SrcVT = Op.getOperand(0).getValueType();
11576   EVT DstVT = Op.getValueType();
11577   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11578          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11579   assert((DstVT == MVT::i64 ||
11580           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11581          "Unexpected custom BITCAST");
11582   // i64 <=> MMX conversions are Legal.
11583   if (SrcVT==MVT::i64 && DstVT.isVector())
11584     return Op;
11585   if (DstVT==MVT::i64 && SrcVT.isVector())
11586     return Op;
11587   // MMX <=> MMX conversions are Legal.
11588   if (SrcVT.isVector() && DstVT.isVector())
11589     return Op;
11590   // All other conversions need to be expanded.
11591   return SDValue();
11592 }
11593
11594 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11595   SDNode *Node = Op.getNode();
11596   DebugLoc dl = Node->getDebugLoc();
11597   EVT T = Node->getValueType(0);
11598   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11599                               DAG.getConstant(0, T), Node->getOperand(2));
11600   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11601                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11602                        Node->getOperand(0),
11603                        Node->getOperand(1), negOp,
11604                        cast<AtomicSDNode>(Node)->getSrcValue(),
11605                        cast<AtomicSDNode>(Node)->getAlignment(),
11606                        cast<AtomicSDNode>(Node)->getOrdering(),
11607                        cast<AtomicSDNode>(Node)->getSynchScope());
11608 }
11609
11610 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11611   SDNode *Node = Op.getNode();
11612   DebugLoc dl = Node->getDebugLoc();
11613   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11614
11615   // Convert seq_cst store -> xchg
11616   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11617   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11618   //        (The only way to get a 16-byte store is cmpxchg16b)
11619   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11620   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11621       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11622     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11623                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11624                                  Node->getOperand(0),
11625                                  Node->getOperand(1), Node->getOperand(2),
11626                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11627                                  cast<AtomicSDNode>(Node)->getOrdering(),
11628                                  cast<AtomicSDNode>(Node)->getSynchScope());
11629     return Swap.getValue(1);
11630   }
11631   // Other atomic stores have a simple pattern.
11632   return Op;
11633 }
11634
11635 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11636   EVT VT = Op.getNode()->getValueType(0);
11637
11638   // Let legalize expand this if it isn't a legal type yet.
11639   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11640     return SDValue();
11641
11642   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11643
11644   unsigned Opc;
11645   bool ExtraOp = false;
11646   switch (Op.getOpcode()) {
11647   default: llvm_unreachable("Invalid code");
11648   case ISD::ADDC: Opc = X86ISD::ADD; break;
11649   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11650   case ISD::SUBC: Opc = X86ISD::SUB; break;
11651   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11652   }
11653
11654   if (!ExtraOp)
11655     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11656                        Op.getOperand(1));
11657   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11658                      Op.getOperand(1), Op.getOperand(2));
11659 }
11660
11661 /// LowerOperation - Provide custom lowering hooks for some operations.
11662 ///
11663 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11664   switch (Op.getOpcode()) {
11665   default: llvm_unreachable("Should not custom lower this!");
11666   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11667   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11668   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11669   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11670   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11671   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11672   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11673   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11674   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11675   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11676   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11677   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11678   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11679   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11680   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11681   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11682   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11683   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11684   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11685   case ISD::SHL_PARTS:
11686   case ISD::SRA_PARTS:
11687   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11688   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11689   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11690   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11691   case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11692   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11693   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11694   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11695   case ISD::FABS:               return LowerFABS(Op, DAG);
11696   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11697   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11698   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11699   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11700   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11701   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11702   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11703   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11704   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11705   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11706   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11707   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11708   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11709   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11710   case ISD::FRAME_TO_ARGS_OFFSET:
11711                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11712   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11713   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11714   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11715   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11716   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11717   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11718   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11719   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11720   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11721   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11722   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11723   case ISD::SRA:
11724   case ISD::SRL:
11725   case ISD::SHL:                return LowerShift(Op, DAG);
11726   case ISD::SADDO:
11727   case ISD::UADDO:
11728   case ISD::SSUBO:
11729   case ISD::USUBO:
11730   case ISD::SMULO:
11731   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11732   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11733   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11734   case ISD::ADDC:
11735   case ISD::ADDE:
11736   case ISD::SUBC:
11737   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11738   case ISD::ADD:                return LowerADD(Op, DAG);
11739   case ISD::SUB:                return LowerSUB(Op, DAG);
11740   }
11741 }
11742
11743 static void ReplaceATOMIC_LOAD(SDNode *Node,
11744                                   SmallVectorImpl<SDValue> &Results,
11745                                   SelectionDAG &DAG) {
11746   DebugLoc dl = Node->getDebugLoc();
11747   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11748
11749   // Convert wide load -> cmpxchg8b/cmpxchg16b
11750   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11751   //        (The only way to get a 16-byte load is cmpxchg16b)
11752   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11753   SDValue Zero = DAG.getConstant(0, VT);
11754   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11755                                Node->getOperand(0),
11756                                Node->getOperand(1), Zero, Zero,
11757                                cast<AtomicSDNode>(Node)->getMemOperand(),
11758                                cast<AtomicSDNode>(Node)->getOrdering(),
11759                                cast<AtomicSDNode>(Node)->getSynchScope());
11760   Results.push_back(Swap.getValue(0));
11761   Results.push_back(Swap.getValue(1));
11762 }
11763
11764 static void
11765 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11766                         SelectionDAG &DAG, unsigned NewOp) {
11767   DebugLoc dl = Node->getDebugLoc();
11768   assert (Node->getValueType(0) == MVT::i64 &&
11769           "Only know how to expand i64 atomics");
11770
11771   SDValue Chain = Node->getOperand(0);
11772   SDValue In1 = Node->getOperand(1);
11773   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11774                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11775   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11776                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11777   SDValue Ops[] = { Chain, In1, In2L, In2H };
11778   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11779   SDValue Result =
11780     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11781                             cast<MemSDNode>(Node)->getMemOperand());
11782   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11783   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11784   Results.push_back(Result.getValue(2));
11785 }
11786
11787 /// ReplaceNodeResults - Replace a node with an illegal result type
11788 /// with a new node built out of custom code.
11789 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11790                                            SmallVectorImpl<SDValue>&Results,
11791                                            SelectionDAG &DAG) const {
11792   DebugLoc dl = N->getDebugLoc();
11793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11794   switch (N->getOpcode()) {
11795   default:
11796     llvm_unreachable("Do not know how to custom type legalize this operation!");
11797   case ISD::SIGN_EXTEND_INREG:
11798   case ISD::ADDC:
11799   case ISD::ADDE:
11800   case ISD::SUBC:
11801   case ISD::SUBE:
11802     // We don't want to expand or promote these.
11803     return;
11804   case ISD::FP_TO_SINT:
11805   case ISD::FP_TO_UINT: {
11806     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11807
11808     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11809       return;
11810
11811     std::pair<SDValue,SDValue> Vals =
11812         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11813     SDValue FIST = Vals.first, StackSlot = Vals.second;
11814     if (FIST.getNode() != 0) {
11815       EVT VT = N->getValueType(0);
11816       // Return a load from the stack slot.
11817       if (StackSlot.getNode() != 0)
11818         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11819                                       MachinePointerInfo(),
11820                                       false, false, false, 0));
11821       else
11822         Results.push_back(FIST);
11823     }
11824     return;
11825   }
11826   case ISD::UINT_TO_FP: {
11827     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11828         N->getValueType(0) != MVT::v2f32)
11829       return;
11830     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11831                                  N->getOperand(0));
11832     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11833                                      MVT::f64);
11834     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11835     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11836                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11837     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11838     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11839     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11840     return;
11841   }
11842   case ISD::FP_ROUND: {
11843     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
11844         return;
11845     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11846     Results.push_back(V);
11847     return;
11848   }
11849   case ISD::READCYCLECOUNTER: {
11850     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11851     SDValue TheChain = N->getOperand(0);
11852     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11853     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11854                                      rd.getValue(1));
11855     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11856                                      eax.getValue(2));
11857     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11858     SDValue Ops[] = { eax, edx };
11859     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11860     Results.push_back(edx.getValue(1));
11861     return;
11862   }
11863   case ISD::ATOMIC_CMP_SWAP: {
11864     EVT T = N->getValueType(0);
11865     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11866     bool Regs64bit = T == MVT::i128;
11867     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11868     SDValue cpInL, cpInH;
11869     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11870                         DAG.getConstant(0, HalfT));
11871     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11872                         DAG.getConstant(1, HalfT));
11873     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11874                              Regs64bit ? X86::RAX : X86::EAX,
11875                              cpInL, SDValue());
11876     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11877                              Regs64bit ? X86::RDX : X86::EDX,
11878                              cpInH, cpInL.getValue(1));
11879     SDValue swapInL, swapInH;
11880     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11881                           DAG.getConstant(0, HalfT));
11882     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11883                           DAG.getConstant(1, HalfT));
11884     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11885                                Regs64bit ? X86::RBX : X86::EBX,
11886                                swapInL, cpInH.getValue(1));
11887     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11888                                Regs64bit ? X86::RCX : X86::ECX,
11889                                swapInH, swapInL.getValue(1));
11890     SDValue Ops[] = { swapInH.getValue(0),
11891                       N->getOperand(1),
11892                       swapInH.getValue(1) };
11893     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11894     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11895     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11896                                   X86ISD::LCMPXCHG8_DAG;
11897     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11898                                              Ops, 3, T, MMO);
11899     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11900                                         Regs64bit ? X86::RAX : X86::EAX,
11901                                         HalfT, Result.getValue(1));
11902     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11903                                         Regs64bit ? X86::RDX : X86::EDX,
11904                                         HalfT, cpOutL.getValue(2));
11905     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11906     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11907     Results.push_back(cpOutH.getValue(1));
11908     return;
11909   }
11910   case ISD::ATOMIC_LOAD_ADD:
11911   case ISD::ATOMIC_LOAD_AND:
11912   case ISD::ATOMIC_LOAD_NAND:
11913   case ISD::ATOMIC_LOAD_OR:
11914   case ISD::ATOMIC_LOAD_SUB:
11915   case ISD::ATOMIC_LOAD_XOR:
11916   case ISD::ATOMIC_LOAD_MAX:
11917   case ISD::ATOMIC_LOAD_MIN:
11918   case ISD::ATOMIC_LOAD_UMAX:
11919   case ISD::ATOMIC_LOAD_UMIN:
11920   case ISD::ATOMIC_SWAP: {
11921     unsigned Opc;
11922     switch (N->getOpcode()) {
11923     default: llvm_unreachable("Unexpected opcode");
11924     case ISD::ATOMIC_LOAD_ADD:
11925       Opc = X86ISD::ATOMADD64_DAG;
11926       break;
11927     case ISD::ATOMIC_LOAD_AND:
11928       Opc = X86ISD::ATOMAND64_DAG;
11929       break;
11930     case ISD::ATOMIC_LOAD_NAND:
11931       Opc = X86ISD::ATOMNAND64_DAG;
11932       break;
11933     case ISD::ATOMIC_LOAD_OR:
11934       Opc = X86ISD::ATOMOR64_DAG;
11935       break;
11936     case ISD::ATOMIC_LOAD_SUB:
11937       Opc = X86ISD::ATOMSUB64_DAG;
11938       break;
11939     case ISD::ATOMIC_LOAD_XOR:
11940       Opc = X86ISD::ATOMXOR64_DAG;
11941       break;
11942     case ISD::ATOMIC_LOAD_MAX:
11943       Opc = X86ISD::ATOMMAX64_DAG;
11944       break;
11945     case ISD::ATOMIC_LOAD_MIN:
11946       Opc = X86ISD::ATOMMIN64_DAG;
11947       break;
11948     case ISD::ATOMIC_LOAD_UMAX:
11949       Opc = X86ISD::ATOMUMAX64_DAG;
11950       break;
11951     case ISD::ATOMIC_LOAD_UMIN:
11952       Opc = X86ISD::ATOMUMIN64_DAG;
11953       break;
11954     case ISD::ATOMIC_SWAP:
11955       Opc = X86ISD::ATOMSWAP64_DAG;
11956       break;
11957     }
11958     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11959     return;
11960   }
11961   case ISD::ATOMIC_LOAD:
11962     ReplaceATOMIC_LOAD(N, Results, DAG);
11963   }
11964 }
11965
11966 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11967   switch (Opcode) {
11968   default: return NULL;
11969   case X86ISD::BSF:                return "X86ISD::BSF";
11970   case X86ISD::BSR:                return "X86ISD::BSR";
11971   case X86ISD::SHLD:               return "X86ISD::SHLD";
11972   case X86ISD::SHRD:               return "X86ISD::SHRD";
11973   case X86ISD::FAND:               return "X86ISD::FAND";
11974   case X86ISD::FOR:                return "X86ISD::FOR";
11975   case X86ISD::FXOR:               return "X86ISD::FXOR";
11976   case X86ISD::FSRL:               return "X86ISD::FSRL";
11977   case X86ISD::FILD:               return "X86ISD::FILD";
11978   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11979   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11980   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11981   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11982   case X86ISD::FLD:                return "X86ISD::FLD";
11983   case X86ISD::FST:                return "X86ISD::FST";
11984   case X86ISD::CALL:               return "X86ISD::CALL";
11985   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11986   case X86ISD::BT:                 return "X86ISD::BT";
11987   case X86ISD::CMP:                return "X86ISD::CMP";
11988   case X86ISD::COMI:               return "X86ISD::COMI";
11989   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11990   case X86ISD::SETCC:              return "X86ISD::SETCC";
11991   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11992   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11993   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11994   case X86ISD::CMOV:               return "X86ISD::CMOV";
11995   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11996   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11997   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11998   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11999   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12000   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12001   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12002   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12003   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12004   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12005   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12006   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12007   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12008   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12009   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12010   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12011   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12012   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12013   case X86ISD::HADD:               return "X86ISD::HADD";
12014   case X86ISD::HSUB:               return "X86ISD::HSUB";
12015   case X86ISD::FHADD:              return "X86ISD::FHADD";
12016   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12017   case X86ISD::UMAX:               return "X86ISD::UMAX";
12018   case X86ISD::UMIN:               return "X86ISD::UMIN";
12019   case X86ISD::SMAX:               return "X86ISD::SMAX";
12020   case X86ISD::SMIN:               return "X86ISD::SMIN";
12021   case X86ISD::FMAX:               return "X86ISD::FMAX";
12022   case X86ISD::FMIN:               return "X86ISD::FMIN";
12023   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12024   case X86ISD::FMINC:              return "X86ISD::FMINC";
12025   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12026   case X86ISD::FRCP:               return "X86ISD::FRCP";
12027   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12028   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12029   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12030   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12031   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12032   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12033   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12034   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12035   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12036   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12037   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12038   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12039   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12040   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12041   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12042   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12043   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12044   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12045   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12046   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12047   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12048   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12049   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12050   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12051   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12052   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12053   case X86ISD::VSHL:               return "X86ISD::VSHL";
12054   case X86ISD::VSRL:               return "X86ISD::VSRL";
12055   case X86ISD::VSRA:               return "X86ISD::VSRA";
12056   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12057   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12058   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12059   case X86ISD::CMPP:               return "X86ISD::CMPP";
12060   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12061   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12062   case X86ISD::ADD:                return "X86ISD::ADD";
12063   case X86ISD::SUB:                return "X86ISD::SUB";
12064   case X86ISD::ADC:                return "X86ISD::ADC";
12065   case X86ISD::SBB:                return "X86ISD::SBB";
12066   case X86ISD::SMUL:               return "X86ISD::SMUL";
12067   case X86ISD::UMUL:               return "X86ISD::UMUL";
12068   case X86ISD::INC:                return "X86ISD::INC";
12069   case X86ISD::DEC:                return "X86ISD::DEC";
12070   case X86ISD::OR:                 return "X86ISD::OR";
12071   case X86ISD::XOR:                return "X86ISD::XOR";
12072   case X86ISD::AND:                return "X86ISD::AND";
12073   case X86ISD::BLSI:               return "X86ISD::BLSI";
12074   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12075   case X86ISD::BLSR:               return "X86ISD::BLSR";
12076   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12077   case X86ISD::PTEST:              return "X86ISD::PTEST";
12078   case X86ISD::TESTP:              return "X86ISD::TESTP";
12079   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12080   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12081   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12082   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12083   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12084   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12085   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12086   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12087   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12088   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12089   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12090   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12091   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12092   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12093   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12094   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12095   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12096   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12097   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12098   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12099   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12100   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12101   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12102   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12103   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12104   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12105   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12106   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12107   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12108   case X86ISD::SAHF:               return "X86ISD::SAHF";
12109   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12110   case X86ISD::FMADD:              return "X86ISD::FMADD";
12111   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12112   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12113   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12114   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12115   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12116   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12117   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12118   }
12119 }
12120
12121 // isLegalAddressingMode - Return true if the addressing mode represented
12122 // by AM is legal for this target, for a load/store of the specified type.
12123 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12124                                               Type *Ty) const {
12125   // X86 supports extremely general addressing modes.
12126   CodeModel::Model M = getTargetMachine().getCodeModel();
12127   Reloc::Model R = getTargetMachine().getRelocationModel();
12128
12129   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12130   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12131     return false;
12132
12133   if (AM.BaseGV) {
12134     unsigned GVFlags =
12135       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12136
12137     // If a reference to this global requires an extra load, we can't fold it.
12138     if (isGlobalStubReference(GVFlags))
12139       return false;
12140
12141     // If BaseGV requires a register for the PIC base, we cannot also have a
12142     // BaseReg specified.
12143     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12144       return false;
12145
12146     // If lower 4G is not available, then we must use rip-relative addressing.
12147     if ((M != CodeModel::Small || R != Reloc::Static) &&
12148         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12149       return false;
12150   }
12151
12152   switch (AM.Scale) {
12153   case 0:
12154   case 1:
12155   case 2:
12156   case 4:
12157   case 8:
12158     // These scales always work.
12159     break;
12160   case 3:
12161   case 5:
12162   case 9:
12163     // These scales are formed with basereg+scalereg.  Only accept if there is
12164     // no basereg yet.
12165     if (AM.HasBaseReg)
12166       return false;
12167     break;
12168   default:  // Other stuff never works.
12169     return false;
12170   }
12171
12172   return true;
12173 }
12174
12175 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12176   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12177     return false;
12178   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12179   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12180   if (NumBits1 <= NumBits2)
12181     return false;
12182   return true;
12183 }
12184
12185 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12186   return Imm == (int32_t)Imm;
12187 }
12188
12189 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12190   // Can also use sub to handle negated immediates.
12191   return Imm == (int32_t)Imm;
12192 }
12193
12194 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12195   if (!VT1.isInteger() || !VT2.isInteger())
12196     return false;
12197   unsigned NumBits1 = VT1.getSizeInBits();
12198   unsigned NumBits2 = VT2.getSizeInBits();
12199   if (NumBits1 <= NumBits2)
12200     return false;
12201   return true;
12202 }
12203
12204 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12205   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12206   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12207 }
12208
12209 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12210   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12211   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12212 }
12213
12214 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12215   EVT VT1 = Val.getValueType();
12216   if (isZExtFree(VT1, VT2))
12217     return true;
12218
12219   if (Val.getOpcode() != ISD::LOAD)
12220     return false;
12221
12222   if (!VT1.isSimple() || !VT1.isInteger() ||
12223       !VT2.isSimple() || !VT2.isInteger())
12224     return false;
12225
12226   switch (VT1.getSimpleVT().SimpleTy) {
12227   default: break;
12228   case MVT::i8:
12229   case MVT::i16:
12230   case MVT::i32:
12231     // X86 has 8, 16, and 32-bit zero-extending loads.
12232     return true;
12233   }
12234
12235   return false;
12236 }
12237
12238 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12239   // i16 instructions are longer (0x66 prefix) and potentially slower.
12240   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12241 }
12242
12243 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12244 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12245 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12246 /// are assumed to be legal.
12247 bool
12248 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12249                                       EVT VT) const {
12250   // Very little shuffling can be done for 64-bit vectors right now.
12251   if (VT.getSizeInBits() == 64)
12252     return false;
12253
12254   // FIXME: pshufb, blends, shifts.
12255   return (VT.getVectorNumElements() == 2 ||
12256           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12257           isMOVLMask(M, VT) ||
12258           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12259           isPSHUFDMask(M, VT) ||
12260           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12261           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12262           isPALIGNRMask(M, VT, Subtarget) ||
12263           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12264           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12265           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12266           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12267 }
12268
12269 bool
12270 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12271                                           EVT VT) const {
12272   unsigned NumElts = VT.getVectorNumElements();
12273   // FIXME: This collection of masks seems suspect.
12274   if (NumElts == 2)
12275     return true;
12276   if (NumElts == 4 && VT.is128BitVector()) {
12277     return (isMOVLMask(Mask, VT)  ||
12278             isCommutedMOVLMask(Mask, VT, true) ||
12279             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12280             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12281   }
12282   return false;
12283 }
12284
12285 //===----------------------------------------------------------------------===//
12286 //                           X86 Scheduler Hooks
12287 //===----------------------------------------------------------------------===//
12288
12289 /// Utility function to emit xbegin specifying the start of an RTM region.
12290 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12291                                      const TargetInstrInfo *TII) {
12292   DebugLoc DL = MI->getDebugLoc();
12293
12294   const BasicBlock *BB = MBB->getBasicBlock();
12295   MachineFunction::iterator I = MBB;
12296   ++I;
12297
12298   // For the v = xbegin(), we generate
12299   //
12300   // thisMBB:
12301   //  xbegin sinkMBB
12302   //
12303   // mainMBB:
12304   //  eax = -1
12305   //
12306   // sinkMBB:
12307   //  v = eax
12308
12309   MachineBasicBlock *thisMBB = MBB;
12310   MachineFunction *MF = MBB->getParent();
12311   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12312   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12313   MF->insert(I, mainMBB);
12314   MF->insert(I, sinkMBB);
12315
12316   // Transfer the remainder of BB and its successor edges to sinkMBB.
12317   sinkMBB->splice(sinkMBB->begin(), MBB,
12318                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12319   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12320
12321   // thisMBB:
12322   //  xbegin sinkMBB
12323   //  # fallthrough to mainMBB
12324   //  # abortion to sinkMBB
12325   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12326   thisMBB->addSuccessor(mainMBB);
12327   thisMBB->addSuccessor(sinkMBB);
12328
12329   // mainMBB:
12330   //  EAX = -1
12331   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12332   mainMBB->addSuccessor(sinkMBB);
12333
12334   // sinkMBB:
12335   // EAX is live into the sinkMBB
12336   sinkMBB->addLiveIn(X86::EAX);
12337   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12338           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12339     .addReg(X86::EAX);
12340
12341   MI->eraseFromParent();
12342   return sinkMBB;
12343 }
12344
12345 // Get CMPXCHG opcode for the specified data type.
12346 static unsigned getCmpXChgOpcode(EVT VT) {
12347   switch (VT.getSimpleVT().SimpleTy) {
12348   case MVT::i8:  return X86::LCMPXCHG8;
12349   case MVT::i16: return X86::LCMPXCHG16;
12350   case MVT::i32: return X86::LCMPXCHG32;
12351   case MVT::i64: return X86::LCMPXCHG64;
12352   default:
12353     break;
12354   }
12355   llvm_unreachable("Invalid operand size!");
12356 }
12357
12358 // Get LOAD opcode for the specified data type.
12359 static unsigned getLoadOpcode(EVT VT) {
12360   switch (VT.getSimpleVT().SimpleTy) {
12361   case MVT::i8:  return X86::MOV8rm;
12362   case MVT::i16: return X86::MOV16rm;
12363   case MVT::i32: return X86::MOV32rm;
12364   case MVT::i64: return X86::MOV64rm;
12365   default:
12366     break;
12367   }
12368   llvm_unreachable("Invalid operand size!");
12369 }
12370
12371 // Get opcode of the non-atomic one from the specified atomic instruction.
12372 static unsigned getNonAtomicOpcode(unsigned Opc) {
12373   switch (Opc) {
12374   case X86::ATOMAND8:  return X86::AND8rr;
12375   case X86::ATOMAND16: return X86::AND16rr;
12376   case X86::ATOMAND32: return X86::AND32rr;
12377   case X86::ATOMAND64: return X86::AND64rr;
12378   case X86::ATOMOR8:   return X86::OR8rr;
12379   case X86::ATOMOR16:  return X86::OR16rr;
12380   case X86::ATOMOR32:  return X86::OR32rr;
12381   case X86::ATOMOR64:  return X86::OR64rr;
12382   case X86::ATOMXOR8:  return X86::XOR8rr;
12383   case X86::ATOMXOR16: return X86::XOR16rr;
12384   case X86::ATOMXOR32: return X86::XOR32rr;
12385   case X86::ATOMXOR64: return X86::XOR64rr;
12386   }
12387   llvm_unreachable("Unhandled atomic-load-op opcode!");
12388 }
12389
12390 // Get opcode of the non-atomic one from the specified atomic instruction with
12391 // extra opcode.
12392 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12393                                                unsigned &ExtraOpc) {
12394   switch (Opc) {
12395   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12396   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12397   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12398   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12399   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12400   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12401   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12402   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12403   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12404   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12405   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12406   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12407   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12408   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12409   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12410   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12411   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12412   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12413   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12414   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12415   }
12416   llvm_unreachable("Unhandled atomic-load-op opcode!");
12417 }
12418
12419 // Get opcode of the non-atomic one from the specified atomic instruction for
12420 // 64-bit data type on 32-bit target.
12421 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12422   switch (Opc) {
12423   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12424   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12425   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12426   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12427   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12428   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12429   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12430   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12431   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12432   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12433   }
12434   llvm_unreachable("Unhandled atomic-load-op opcode!");
12435 }
12436
12437 // Get opcode of the non-atomic one from the specified atomic instruction for
12438 // 64-bit data type on 32-bit target with extra opcode.
12439 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12440                                                    unsigned &HiOpc,
12441                                                    unsigned &ExtraOpc) {
12442   switch (Opc) {
12443   case X86::ATOMNAND6432:
12444     ExtraOpc = X86::NOT32r;
12445     HiOpc = X86::AND32rr;
12446     return X86::AND32rr;
12447   }
12448   llvm_unreachable("Unhandled atomic-load-op opcode!");
12449 }
12450
12451 // Get pseudo CMOV opcode from the specified data type.
12452 static unsigned getPseudoCMOVOpc(EVT VT) {
12453   switch (VT.getSimpleVT().SimpleTy) {
12454   case MVT::i8:  return X86::CMOV_GR8;
12455   case MVT::i16: return X86::CMOV_GR16;
12456   case MVT::i32: return X86::CMOV_GR32;
12457   default:
12458     break;
12459   }
12460   llvm_unreachable("Unknown CMOV opcode!");
12461 }
12462
12463 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12464 // They will be translated into a spin-loop or compare-exchange loop from
12465 //
12466 //    ...
12467 //    dst = atomic-fetch-op MI.addr, MI.val
12468 //    ...
12469 //
12470 // to
12471 //
12472 //    ...
12473 //    EAX = LOAD MI.addr
12474 // loop:
12475 //    t1 = OP MI.val, EAX
12476 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12477 //    JNE loop
12478 // sink:
12479 //    dst = EAX
12480 //    ...
12481 MachineBasicBlock *
12482 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12483                                        MachineBasicBlock *MBB) const {
12484   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12485   DebugLoc DL = MI->getDebugLoc();
12486
12487   MachineFunction *MF = MBB->getParent();
12488   MachineRegisterInfo &MRI = MF->getRegInfo();
12489
12490   const BasicBlock *BB = MBB->getBasicBlock();
12491   MachineFunction::iterator I = MBB;
12492   ++I;
12493
12494   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12495          "Unexpected number of operands");
12496
12497   assert(MI->hasOneMemOperand() &&
12498          "Expected atomic-load-op to have one memoperand");
12499
12500   // Memory Reference
12501   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12502   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12503
12504   unsigned DstReg, SrcReg;
12505   unsigned MemOpndSlot;
12506
12507   unsigned CurOp = 0;
12508
12509   DstReg = MI->getOperand(CurOp++).getReg();
12510   MemOpndSlot = CurOp;
12511   CurOp += X86::AddrNumOperands;
12512   SrcReg = MI->getOperand(CurOp++).getReg();
12513
12514   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12515   MVT::SimpleValueType VT = *RC->vt_begin();
12516   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12517
12518   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12519   unsigned LOADOpc = getLoadOpcode(VT);
12520
12521   // For the atomic load-arith operator, we generate
12522   //
12523   //  thisMBB:
12524   //    EAX = LOAD [MI.addr]
12525   //  mainMBB:
12526   //    t1 = OP MI.val, EAX
12527   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12528   //    JNE mainMBB
12529   //  sinkMBB:
12530
12531   MachineBasicBlock *thisMBB = MBB;
12532   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12533   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12534   MF->insert(I, mainMBB);
12535   MF->insert(I, sinkMBB);
12536
12537   MachineInstrBuilder MIB;
12538
12539   // Transfer the remainder of BB and its successor edges to sinkMBB.
12540   sinkMBB->splice(sinkMBB->begin(), MBB,
12541                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12542   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12543
12544   // thisMBB:
12545   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12546   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12547     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12548   MIB.setMemRefs(MMOBegin, MMOEnd);
12549
12550   thisMBB->addSuccessor(mainMBB);
12551
12552   // mainMBB:
12553   MachineBasicBlock *origMainMBB = mainMBB;
12554   mainMBB->addLiveIn(AccPhyReg);
12555
12556   // Copy AccPhyReg as it is used more than once.
12557   unsigned AccReg = MRI.createVirtualRegister(RC);
12558   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12559     .addReg(AccPhyReg);
12560
12561   unsigned t1 = MRI.createVirtualRegister(RC);
12562   unsigned Opc = MI->getOpcode();
12563   switch (Opc) {
12564   default:
12565     llvm_unreachable("Unhandled atomic-load-op opcode!");
12566   case X86::ATOMAND8:
12567   case X86::ATOMAND16:
12568   case X86::ATOMAND32:
12569   case X86::ATOMAND64:
12570   case X86::ATOMOR8:
12571   case X86::ATOMOR16:
12572   case X86::ATOMOR32:
12573   case X86::ATOMOR64:
12574   case X86::ATOMXOR8:
12575   case X86::ATOMXOR16:
12576   case X86::ATOMXOR32:
12577   case X86::ATOMXOR64: {
12578     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12579     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12580       .addReg(AccReg);
12581     break;
12582   }
12583   case X86::ATOMNAND8:
12584   case X86::ATOMNAND16:
12585   case X86::ATOMNAND32:
12586   case X86::ATOMNAND64: {
12587     unsigned t2 = MRI.createVirtualRegister(RC);
12588     unsigned NOTOpc;
12589     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12590     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12591       .addReg(AccReg);
12592     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12593     break;
12594   }
12595   case X86::ATOMMAX8:
12596   case X86::ATOMMAX16:
12597   case X86::ATOMMAX32:
12598   case X86::ATOMMAX64:
12599   case X86::ATOMMIN8:
12600   case X86::ATOMMIN16:
12601   case X86::ATOMMIN32:
12602   case X86::ATOMMIN64:
12603   case X86::ATOMUMAX8:
12604   case X86::ATOMUMAX16:
12605   case X86::ATOMUMAX32:
12606   case X86::ATOMUMAX64:
12607   case X86::ATOMUMIN8:
12608   case X86::ATOMUMIN16:
12609   case X86::ATOMUMIN32:
12610   case X86::ATOMUMIN64: {
12611     unsigned CMPOpc;
12612     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12613
12614     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12615       .addReg(SrcReg)
12616       .addReg(AccReg);
12617
12618     if (Subtarget->hasCMov()) {
12619       if (VT != MVT::i8) {
12620         // Native support
12621         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12622           .addReg(SrcReg)
12623           .addReg(AccReg);
12624       } else {
12625         // Promote i8 to i32 to use CMOV32
12626         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12627         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12628         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12629         unsigned t2 = MRI.createVirtualRegister(RC32);
12630
12631         unsigned Undef = MRI.createVirtualRegister(RC32);
12632         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12633
12634         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12635           .addReg(Undef)
12636           .addReg(SrcReg)
12637           .addImm(X86::sub_8bit);
12638         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12639           .addReg(Undef)
12640           .addReg(AccReg)
12641           .addImm(X86::sub_8bit);
12642
12643         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12644           .addReg(SrcReg32)
12645           .addReg(AccReg32);
12646
12647         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12648           .addReg(t2, 0, X86::sub_8bit);
12649       }
12650     } else {
12651       // Use pseudo select and lower them.
12652       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12653              "Invalid atomic-load-op transformation!");
12654       unsigned SelOpc = getPseudoCMOVOpc(VT);
12655       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12656       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12657       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12658               .addReg(SrcReg).addReg(AccReg)
12659               .addImm(CC);
12660       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12661     }
12662     break;
12663   }
12664   }
12665
12666   // Copy AccPhyReg back from virtual register.
12667   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12668     .addReg(AccReg);
12669
12670   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12671   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12672     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12673   MIB.addReg(t1);
12674   MIB.setMemRefs(MMOBegin, MMOEnd);
12675
12676   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12677
12678   mainMBB->addSuccessor(origMainMBB);
12679   mainMBB->addSuccessor(sinkMBB);
12680
12681   // sinkMBB:
12682   sinkMBB->addLiveIn(AccPhyReg);
12683
12684   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12685           TII->get(TargetOpcode::COPY), DstReg)
12686     .addReg(AccPhyReg);
12687
12688   MI->eraseFromParent();
12689   return sinkMBB;
12690 }
12691
12692 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12693 // instructions. They will be translated into a spin-loop or compare-exchange
12694 // loop from
12695 //
12696 //    ...
12697 //    dst = atomic-fetch-op MI.addr, MI.val
12698 //    ...
12699 //
12700 // to
12701 //
12702 //    ...
12703 //    EAX = LOAD [MI.addr + 0]
12704 //    EDX = LOAD [MI.addr + 4]
12705 // loop:
12706 //    EBX = OP MI.val.lo, EAX
12707 //    ECX = OP MI.val.hi, EDX
12708 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12709 //    JNE loop
12710 // sink:
12711 //    dst = EDX:EAX
12712 //    ...
12713 MachineBasicBlock *
12714 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12715                                            MachineBasicBlock *MBB) const {
12716   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12717   DebugLoc DL = MI->getDebugLoc();
12718
12719   MachineFunction *MF = MBB->getParent();
12720   MachineRegisterInfo &MRI = MF->getRegInfo();
12721
12722   const BasicBlock *BB = MBB->getBasicBlock();
12723   MachineFunction::iterator I = MBB;
12724   ++I;
12725
12726   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12727          "Unexpected number of operands");
12728
12729   assert(MI->hasOneMemOperand() &&
12730          "Expected atomic-load-op32 to have one memoperand");
12731
12732   // Memory Reference
12733   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12734   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12735
12736   unsigned DstLoReg, DstHiReg;
12737   unsigned SrcLoReg, SrcHiReg;
12738   unsigned MemOpndSlot;
12739
12740   unsigned CurOp = 0;
12741
12742   DstLoReg = MI->getOperand(CurOp++).getReg();
12743   DstHiReg = MI->getOperand(CurOp++).getReg();
12744   MemOpndSlot = CurOp;
12745   CurOp += X86::AddrNumOperands;
12746   SrcLoReg = MI->getOperand(CurOp++).getReg();
12747   SrcHiReg = MI->getOperand(CurOp++).getReg();
12748
12749   const TargetRegisterClass *RC = &X86::GR32RegClass;
12750   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12751
12752   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12753   unsigned LOADOpc = X86::MOV32rm;
12754
12755   // For the atomic load-arith operator, we generate
12756   //
12757   //  thisMBB:
12758   //    EAX = LOAD [MI.addr + 0]
12759   //    EDX = LOAD [MI.addr + 4]
12760   //  mainMBB:
12761   //    EBX = OP MI.vallo, EAX
12762   //    ECX = OP MI.valhi, EDX
12763   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12764   //    JNE mainMBB
12765   //  sinkMBB:
12766
12767   MachineBasicBlock *thisMBB = MBB;
12768   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12769   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12770   MF->insert(I, mainMBB);
12771   MF->insert(I, sinkMBB);
12772
12773   MachineInstrBuilder MIB;
12774
12775   // Transfer the remainder of BB and its successor edges to sinkMBB.
12776   sinkMBB->splice(sinkMBB->begin(), MBB,
12777                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12778   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12779
12780   // thisMBB:
12781   // Lo
12782   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12783   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12784     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12785   MIB.setMemRefs(MMOBegin, MMOEnd);
12786   // Hi
12787   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12788   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12789     if (i == X86::AddrDisp)
12790       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12791     else
12792       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12793   }
12794   MIB.setMemRefs(MMOBegin, MMOEnd);
12795
12796   thisMBB->addSuccessor(mainMBB);
12797
12798   // mainMBB:
12799   MachineBasicBlock *origMainMBB = mainMBB;
12800   mainMBB->addLiveIn(X86::EAX);
12801   mainMBB->addLiveIn(X86::EDX);
12802
12803   // Copy EDX:EAX as they are used more than once.
12804   unsigned LoReg = MRI.createVirtualRegister(RC);
12805   unsigned HiReg = MRI.createVirtualRegister(RC);
12806   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12807   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12808
12809   unsigned t1L = MRI.createVirtualRegister(RC);
12810   unsigned t1H = MRI.createVirtualRegister(RC);
12811
12812   unsigned Opc = MI->getOpcode();
12813   switch (Opc) {
12814   default:
12815     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12816   case X86::ATOMAND6432:
12817   case X86::ATOMOR6432:
12818   case X86::ATOMXOR6432:
12819   case X86::ATOMADD6432:
12820   case X86::ATOMSUB6432: {
12821     unsigned HiOpc;
12822     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12823     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
12824     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
12825     break;
12826   }
12827   case X86::ATOMNAND6432: {
12828     unsigned HiOpc, NOTOpc;
12829     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12830     unsigned t2L = MRI.createVirtualRegister(RC);
12831     unsigned t2H = MRI.createVirtualRegister(RC);
12832     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12833     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12834     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12835     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12836     break;
12837   }
12838   case X86::ATOMMAX6432:
12839   case X86::ATOMMIN6432:
12840   case X86::ATOMUMAX6432:
12841   case X86::ATOMUMIN6432: {
12842     unsigned HiOpc;
12843     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12844     unsigned cL = MRI.createVirtualRegister(RC8);
12845     unsigned cH = MRI.createVirtualRegister(RC8);
12846     unsigned cL32 = MRI.createVirtualRegister(RC);
12847     unsigned cH32 = MRI.createVirtualRegister(RC);
12848     unsigned cc = MRI.createVirtualRegister(RC);
12849     // cl := cmp src_lo, lo
12850     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12851       .addReg(SrcLoReg).addReg(LoReg);
12852     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12853     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12854     // ch := cmp src_hi, hi
12855     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12856       .addReg(SrcHiReg).addReg(HiReg);
12857     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12858     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12859     // cc := if (src_hi == hi) ? cl : ch;
12860     if (Subtarget->hasCMov()) {
12861       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12862         .addReg(cH32).addReg(cL32);
12863     } else {
12864       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12865               .addReg(cH32).addReg(cL32)
12866               .addImm(X86::COND_E);
12867       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12868     }
12869     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12870     if (Subtarget->hasCMov()) {
12871       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12872         .addReg(SrcLoReg).addReg(LoReg);
12873       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12874         .addReg(SrcHiReg).addReg(HiReg);
12875     } else {
12876       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12877               .addReg(SrcLoReg).addReg(LoReg)
12878               .addImm(X86::COND_NE);
12879       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12880       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12881               .addReg(SrcHiReg).addReg(HiReg)
12882               .addImm(X86::COND_NE);
12883       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12884     }
12885     break;
12886   }
12887   case X86::ATOMSWAP6432: {
12888     unsigned HiOpc;
12889     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12890     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12891     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12892     break;
12893   }
12894   }
12895
12896   // Copy EDX:EAX back from HiReg:LoReg
12897   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12898   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12899   // Copy ECX:EBX from t1H:t1L
12900   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12901   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12902
12903   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12904   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12905     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12906   MIB.setMemRefs(MMOBegin, MMOEnd);
12907
12908   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12909
12910   mainMBB->addSuccessor(origMainMBB);
12911   mainMBB->addSuccessor(sinkMBB);
12912
12913   // sinkMBB:
12914   sinkMBB->addLiveIn(X86::EAX);
12915   sinkMBB->addLiveIn(X86::EDX);
12916
12917   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12918           TII->get(TargetOpcode::COPY), DstLoReg)
12919     .addReg(X86::EAX);
12920   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12921           TII->get(TargetOpcode::COPY), DstHiReg)
12922     .addReg(X86::EDX);
12923
12924   MI->eraseFromParent();
12925   return sinkMBB;
12926 }
12927
12928 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12929 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12930 // in the .td file.
12931 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
12932                                        const TargetInstrInfo *TII) {
12933   unsigned Opc;
12934   switch (MI->getOpcode()) {
12935   default: llvm_unreachable("illegal opcode!");
12936   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
12937   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
12938   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
12939   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
12940   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
12941   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
12942   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
12943   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
12944   }
12945
12946   DebugLoc dl = MI->getDebugLoc();
12947   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12948
12949   unsigned NumArgs = MI->getNumOperands();
12950   for (unsigned i = 1; i < NumArgs; ++i) {
12951     MachineOperand &Op = MI->getOperand(i);
12952     if (!(Op.isReg() && Op.isImplicit()))
12953       MIB.addOperand(Op);
12954   }
12955   if (MI->hasOneMemOperand())
12956     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12957
12958   BuildMI(*BB, MI, dl,
12959     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12960     .addReg(X86::XMM0);
12961
12962   MI->eraseFromParent();
12963   return BB;
12964 }
12965
12966 // FIXME: Custom handling because TableGen doesn't support multiple implicit
12967 // defs in an instruction pattern
12968 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
12969                                        const TargetInstrInfo *TII) {
12970   unsigned Opc;
12971   switch (MI->getOpcode()) {
12972   default: llvm_unreachable("illegal opcode!");
12973   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
12974   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
12975   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
12976   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
12977   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
12978   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
12979   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
12980   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
12981   }
12982
12983   DebugLoc dl = MI->getDebugLoc();
12984   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12985
12986   unsigned NumArgs = MI->getNumOperands(); // remove the results
12987   for (unsigned i = 1; i < NumArgs; ++i) {
12988     MachineOperand &Op = MI->getOperand(i);
12989     if (!(Op.isReg() && Op.isImplicit()))
12990       MIB.addOperand(Op);
12991   }
12992   if (MI->hasOneMemOperand())
12993     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12994
12995   BuildMI(*BB, MI, dl,
12996     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12997     .addReg(X86::ECX);
12998
12999   MI->eraseFromParent();
13000   return BB;
13001 }
13002
13003 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13004                                        const TargetInstrInfo *TII,
13005                                        const X86Subtarget* Subtarget) {
13006   DebugLoc dl = MI->getDebugLoc();
13007
13008   // Address into RAX/EAX, other two args into ECX, EDX.
13009   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13010   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13011   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13012   for (int i = 0; i < X86::AddrNumOperands; ++i)
13013     MIB.addOperand(MI->getOperand(i));
13014
13015   unsigned ValOps = X86::AddrNumOperands;
13016   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13017     .addReg(MI->getOperand(ValOps).getReg());
13018   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13019     .addReg(MI->getOperand(ValOps+1).getReg());
13020
13021   // The instruction doesn't actually take any operands though.
13022   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13023
13024   MI->eraseFromParent(); // The pseudo is gone now.
13025   return BB;
13026 }
13027
13028 MachineBasicBlock *
13029 X86TargetLowering::EmitVAARG64WithCustomInserter(
13030                    MachineInstr *MI,
13031                    MachineBasicBlock *MBB) const {
13032   // Emit va_arg instruction on X86-64.
13033
13034   // Operands to this pseudo-instruction:
13035   // 0  ) Output        : destination address (reg)
13036   // 1-5) Input         : va_list address (addr, i64mem)
13037   // 6  ) ArgSize       : Size (in bytes) of vararg type
13038   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13039   // 8  ) Align         : Alignment of type
13040   // 9  ) EFLAGS (implicit-def)
13041
13042   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13043   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13044
13045   unsigned DestReg = MI->getOperand(0).getReg();
13046   MachineOperand &Base = MI->getOperand(1);
13047   MachineOperand &Scale = MI->getOperand(2);
13048   MachineOperand &Index = MI->getOperand(3);
13049   MachineOperand &Disp = MI->getOperand(4);
13050   MachineOperand &Segment = MI->getOperand(5);
13051   unsigned ArgSize = MI->getOperand(6).getImm();
13052   unsigned ArgMode = MI->getOperand(7).getImm();
13053   unsigned Align = MI->getOperand(8).getImm();
13054
13055   // Memory Reference
13056   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13057   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13058   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13059
13060   // Machine Information
13061   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13062   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13063   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13064   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13065   DebugLoc DL = MI->getDebugLoc();
13066
13067   // struct va_list {
13068   //   i32   gp_offset
13069   //   i32   fp_offset
13070   //   i64   overflow_area (address)
13071   //   i64   reg_save_area (address)
13072   // }
13073   // sizeof(va_list) = 24
13074   // alignment(va_list) = 8
13075
13076   unsigned TotalNumIntRegs = 6;
13077   unsigned TotalNumXMMRegs = 8;
13078   bool UseGPOffset = (ArgMode == 1);
13079   bool UseFPOffset = (ArgMode == 2);
13080   unsigned MaxOffset = TotalNumIntRegs * 8 +
13081                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13082
13083   /* Align ArgSize to a multiple of 8 */
13084   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13085   bool NeedsAlign = (Align > 8);
13086
13087   MachineBasicBlock *thisMBB = MBB;
13088   MachineBasicBlock *overflowMBB;
13089   MachineBasicBlock *offsetMBB;
13090   MachineBasicBlock *endMBB;
13091
13092   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13093   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13094   unsigned OffsetReg = 0;
13095
13096   if (!UseGPOffset && !UseFPOffset) {
13097     // If we only pull from the overflow region, we don't create a branch.
13098     // We don't need to alter control flow.
13099     OffsetDestReg = 0; // unused
13100     OverflowDestReg = DestReg;
13101
13102     offsetMBB = NULL;
13103     overflowMBB = thisMBB;
13104     endMBB = thisMBB;
13105   } else {
13106     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13107     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13108     // If not, pull from overflow_area. (branch to overflowMBB)
13109     //
13110     //       thisMBB
13111     //         |     .
13112     //         |        .
13113     //     offsetMBB   overflowMBB
13114     //         |        .
13115     //         |     .
13116     //        endMBB
13117
13118     // Registers for the PHI in endMBB
13119     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13120     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13121
13122     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13123     MachineFunction *MF = MBB->getParent();
13124     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13125     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13126     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13127
13128     MachineFunction::iterator MBBIter = MBB;
13129     ++MBBIter;
13130
13131     // Insert the new basic blocks
13132     MF->insert(MBBIter, offsetMBB);
13133     MF->insert(MBBIter, overflowMBB);
13134     MF->insert(MBBIter, endMBB);
13135
13136     // Transfer the remainder of MBB and its successor edges to endMBB.
13137     endMBB->splice(endMBB->begin(), thisMBB,
13138                     llvm::next(MachineBasicBlock::iterator(MI)),
13139                     thisMBB->end());
13140     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13141
13142     // Make offsetMBB and overflowMBB successors of thisMBB
13143     thisMBB->addSuccessor(offsetMBB);
13144     thisMBB->addSuccessor(overflowMBB);
13145
13146     // endMBB is a successor of both offsetMBB and overflowMBB
13147     offsetMBB->addSuccessor(endMBB);
13148     overflowMBB->addSuccessor(endMBB);
13149
13150     // Load the offset value into a register
13151     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13152     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13153       .addOperand(Base)
13154       .addOperand(Scale)
13155       .addOperand(Index)
13156       .addDisp(Disp, UseFPOffset ? 4 : 0)
13157       .addOperand(Segment)
13158       .setMemRefs(MMOBegin, MMOEnd);
13159
13160     // Check if there is enough room left to pull this argument.
13161     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13162       .addReg(OffsetReg)
13163       .addImm(MaxOffset + 8 - ArgSizeA8);
13164
13165     // Branch to "overflowMBB" if offset >= max
13166     // Fall through to "offsetMBB" otherwise
13167     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13168       .addMBB(overflowMBB);
13169   }
13170
13171   // In offsetMBB, emit code to use the reg_save_area.
13172   if (offsetMBB) {
13173     assert(OffsetReg != 0);
13174
13175     // Read the reg_save_area address.
13176     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13177     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13178       .addOperand(Base)
13179       .addOperand(Scale)
13180       .addOperand(Index)
13181       .addDisp(Disp, 16)
13182       .addOperand(Segment)
13183       .setMemRefs(MMOBegin, MMOEnd);
13184
13185     // Zero-extend the offset
13186     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13187       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13188         .addImm(0)
13189         .addReg(OffsetReg)
13190         .addImm(X86::sub_32bit);
13191
13192     // Add the offset to the reg_save_area to get the final address.
13193     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13194       .addReg(OffsetReg64)
13195       .addReg(RegSaveReg);
13196
13197     // Compute the offset for the next argument
13198     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13199     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13200       .addReg(OffsetReg)
13201       .addImm(UseFPOffset ? 16 : 8);
13202
13203     // Store it back into the va_list.
13204     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13205       .addOperand(Base)
13206       .addOperand(Scale)
13207       .addOperand(Index)
13208       .addDisp(Disp, UseFPOffset ? 4 : 0)
13209       .addOperand(Segment)
13210       .addReg(NextOffsetReg)
13211       .setMemRefs(MMOBegin, MMOEnd);
13212
13213     // Jump to endMBB
13214     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13215       .addMBB(endMBB);
13216   }
13217
13218   //
13219   // Emit code to use overflow area
13220   //
13221
13222   // Load the overflow_area address into a register.
13223   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13224   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13225     .addOperand(Base)
13226     .addOperand(Scale)
13227     .addOperand(Index)
13228     .addDisp(Disp, 8)
13229     .addOperand(Segment)
13230     .setMemRefs(MMOBegin, MMOEnd);
13231
13232   // If we need to align it, do so. Otherwise, just copy the address
13233   // to OverflowDestReg.
13234   if (NeedsAlign) {
13235     // Align the overflow address
13236     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13237     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13238
13239     // aligned_addr = (addr + (align-1)) & ~(align-1)
13240     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13241       .addReg(OverflowAddrReg)
13242       .addImm(Align-1);
13243
13244     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13245       .addReg(TmpReg)
13246       .addImm(~(uint64_t)(Align-1));
13247   } else {
13248     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13249       .addReg(OverflowAddrReg);
13250   }
13251
13252   // Compute the next overflow address after this argument.
13253   // (the overflow address should be kept 8-byte aligned)
13254   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13255   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13256     .addReg(OverflowDestReg)
13257     .addImm(ArgSizeA8);
13258
13259   // Store the new overflow address.
13260   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13261     .addOperand(Base)
13262     .addOperand(Scale)
13263     .addOperand(Index)
13264     .addDisp(Disp, 8)
13265     .addOperand(Segment)
13266     .addReg(NextAddrReg)
13267     .setMemRefs(MMOBegin, MMOEnd);
13268
13269   // If we branched, emit the PHI to the front of endMBB.
13270   if (offsetMBB) {
13271     BuildMI(*endMBB, endMBB->begin(), DL,
13272             TII->get(X86::PHI), DestReg)
13273       .addReg(OffsetDestReg).addMBB(offsetMBB)
13274       .addReg(OverflowDestReg).addMBB(overflowMBB);
13275   }
13276
13277   // Erase the pseudo instruction
13278   MI->eraseFromParent();
13279
13280   return endMBB;
13281 }
13282
13283 MachineBasicBlock *
13284 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13285                                                  MachineInstr *MI,
13286                                                  MachineBasicBlock *MBB) const {
13287   // Emit code to save XMM registers to the stack. The ABI says that the
13288   // number of registers to save is given in %al, so it's theoretically
13289   // possible to do an indirect jump trick to avoid saving all of them,
13290   // however this code takes a simpler approach and just executes all
13291   // of the stores if %al is non-zero. It's less code, and it's probably
13292   // easier on the hardware branch predictor, and stores aren't all that
13293   // expensive anyway.
13294
13295   // Create the new basic blocks. One block contains all the XMM stores,
13296   // and one block is the final destination regardless of whether any
13297   // stores were performed.
13298   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13299   MachineFunction *F = MBB->getParent();
13300   MachineFunction::iterator MBBIter = MBB;
13301   ++MBBIter;
13302   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13303   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13304   F->insert(MBBIter, XMMSaveMBB);
13305   F->insert(MBBIter, EndMBB);
13306
13307   // Transfer the remainder of MBB and its successor edges to EndMBB.
13308   EndMBB->splice(EndMBB->begin(), MBB,
13309                  llvm::next(MachineBasicBlock::iterator(MI)),
13310                  MBB->end());
13311   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13312
13313   // The original block will now fall through to the XMM save block.
13314   MBB->addSuccessor(XMMSaveMBB);
13315   // The XMMSaveMBB will fall through to the end block.
13316   XMMSaveMBB->addSuccessor(EndMBB);
13317
13318   // Now add the instructions.
13319   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13320   DebugLoc DL = MI->getDebugLoc();
13321
13322   unsigned CountReg = MI->getOperand(0).getReg();
13323   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13324   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13325
13326   if (!Subtarget->isTargetWin64()) {
13327     // If %al is 0, branch around the XMM save block.
13328     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13329     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13330     MBB->addSuccessor(EndMBB);
13331   }
13332
13333   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13334   // In the XMM save block, save all the XMM argument registers.
13335   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13336     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13337     MachineMemOperand *MMO =
13338       F->getMachineMemOperand(
13339           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13340         MachineMemOperand::MOStore,
13341         /*Size=*/16, /*Align=*/16);
13342     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13343       .addFrameIndex(RegSaveFrameIndex)
13344       .addImm(/*Scale=*/1)
13345       .addReg(/*IndexReg=*/0)
13346       .addImm(/*Disp=*/Offset)
13347       .addReg(/*Segment=*/0)
13348       .addReg(MI->getOperand(i).getReg())
13349       .addMemOperand(MMO);
13350   }
13351
13352   MI->eraseFromParent();   // The pseudo instruction is gone now.
13353
13354   return EndMBB;
13355 }
13356
13357 // The EFLAGS operand of SelectItr might be missing a kill marker
13358 // because there were multiple uses of EFLAGS, and ISel didn't know
13359 // which to mark. Figure out whether SelectItr should have had a
13360 // kill marker, and set it if it should. Returns the correct kill
13361 // marker value.
13362 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13363                                      MachineBasicBlock* BB,
13364                                      const TargetRegisterInfo* TRI) {
13365   // Scan forward through BB for a use/def of EFLAGS.
13366   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13367   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13368     const MachineInstr& mi = *miI;
13369     if (mi.readsRegister(X86::EFLAGS))
13370       return false;
13371     if (mi.definesRegister(X86::EFLAGS))
13372       break; // Should have kill-flag - update below.
13373   }
13374
13375   // If we hit the end of the block, check whether EFLAGS is live into a
13376   // successor.
13377   if (miI == BB->end()) {
13378     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13379                                           sEnd = BB->succ_end();
13380          sItr != sEnd; ++sItr) {
13381       MachineBasicBlock* succ = *sItr;
13382       if (succ->isLiveIn(X86::EFLAGS))
13383         return false;
13384     }
13385   }
13386
13387   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13388   // out. SelectMI should have a kill flag on EFLAGS.
13389   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13390   return true;
13391 }
13392
13393 MachineBasicBlock *
13394 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13395                                      MachineBasicBlock *BB) const {
13396   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13397   DebugLoc DL = MI->getDebugLoc();
13398
13399   // To "insert" a SELECT_CC instruction, we actually have to insert the
13400   // diamond control-flow pattern.  The incoming instruction knows the
13401   // destination vreg to set, the condition code register to branch on, the
13402   // true/false values to select between, and a branch opcode to use.
13403   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13404   MachineFunction::iterator It = BB;
13405   ++It;
13406
13407   //  thisMBB:
13408   //  ...
13409   //   TrueVal = ...
13410   //   cmpTY ccX, r1, r2
13411   //   bCC copy1MBB
13412   //   fallthrough --> copy0MBB
13413   MachineBasicBlock *thisMBB = BB;
13414   MachineFunction *F = BB->getParent();
13415   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13416   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13417   F->insert(It, copy0MBB);
13418   F->insert(It, sinkMBB);
13419
13420   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13421   // live into the sink and copy blocks.
13422   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13423   if (!MI->killsRegister(X86::EFLAGS) &&
13424       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13425     copy0MBB->addLiveIn(X86::EFLAGS);
13426     sinkMBB->addLiveIn(X86::EFLAGS);
13427   }
13428
13429   // Transfer the remainder of BB and its successor edges to sinkMBB.
13430   sinkMBB->splice(sinkMBB->begin(), BB,
13431                   llvm::next(MachineBasicBlock::iterator(MI)),
13432                   BB->end());
13433   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13434
13435   // Add the true and fallthrough blocks as its successors.
13436   BB->addSuccessor(copy0MBB);
13437   BB->addSuccessor(sinkMBB);
13438
13439   // Create the conditional branch instruction.
13440   unsigned Opc =
13441     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13442   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13443
13444   //  copy0MBB:
13445   //   %FalseValue = ...
13446   //   # fallthrough to sinkMBB
13447   copy0MBB->addSuccessor(sinkMBB);
13448
13449   //  sinkMBB:
13450   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13451   //  ...
13452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13453           TII->get(X86::PHI), MI->getOperand(0).getReg())
13454     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13455     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13456
13457   MI->eraseFromParent();   // The pseudo instruction is gone now.
13458   return sinkMBB;
13459 }
13460
13461 MachineBasicBlock *
13462 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13463                                         bool Is64Bit) const {
13464   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13465   DebugLoc DL = MI->getDebugLoc();
13466   MachineFunction *MF = BB->getParent();
13467   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13468
13469   assert(getTargetMachine().Options.EnableSegmentedStacks);
13470
13471   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13472   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13473
13474   // BB:
13475   //  ... [Till the alloca]
13476   // If stacklet is not large enough, jump to mallocMBB
13477   //
13478   // bumpMBB:
13479   //  Allocate by subtracting from RSP
13480   //  Jump to continueMBB
13481   //
13482   // mallocMBB:
13483   //  Allocate by call to runtime
13484   //
13485   // continueMBB:
13486   //  ...
13487   //  [rest of original BB]
13488   //
13489
13490   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13491   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13492   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13493
13494   MachineRegisterInfo &MRI = MF->getRegInfo();
13495   const TargetRegisterClass *AddrRegClass =
13496     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13497
13498   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13499     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13500     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13501     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13502     sizeVReg = MI->getOperand(1).getReg(),
13503     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13504
13505   MachineFunction::iterator MBBIter = BB;
13506   ++MBBIter;
13507
13508   MF->insert(MBBIter, bumpMBB);
13509   MF->insert(MBBIter, mallocMBB);
13510   MF->insert(MBBIter, continueMBB);
13511
13512   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13513                       (MachineBasicBlock::iterator(MI)), BB->end());
13514   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13515
13516   // Add code to the main basic block to check if the stack limit has been hit,
13517   // and if so, jump to mallocMBB otherwise to bumpMBB.
13518   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13519   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13520     .addReg(tmpSPVReg).addReg(sizeVReg);
13521   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13522     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13523     .addReg(SPLimitVReg);
13524   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13525
13526   // bumpMBB simply decreases the stack pointer, since we know the current
13527   // stacklet has enough space.
13528   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13529     .addReg(SPLimitVReg);
13530   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13531     .addReg(SPLimitVReg);
13532   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13533
13534   // Calls into a routine in libgcc to allocate more space from the heap.
13535   const uint32_t *RegMask =
13536     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13537   if (Is64Bit) {
13538     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13539       .addReg(sizeVReg);
13540     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13541       .addExternalSymbol("__morestack_allocate_stack_space")
13542       .addRegMask(RegMask)
13543       .addReg(X86::RDI, RegState::Implicit)
13544       .addReg(X86::RAX, RegState::ImplicitDefine);
13545   } else {
13546     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13547       .addImm(12);
13548     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13549     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13550       .addExternalSymbol("__morestack_allocate_stack_space")
13551       .addRegMask(RegMask)
13552       .addReg(X86::EAX, RegState::ImplicitDefine);
13553   }
13554
13555   if (!Is64Bit)
13556     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13557       .addImm(16);
13558
13559   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13560     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13561   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13562
13563   // Set up the CFG correctly.
13564   BB->addSuccessor(bumpMBB);
13565   BB->addSuccessor(mallocMBB);
13566   mallocMBB->addSuccessor(continueMBB);
13567   bumpMBB->addSuccessor(continueMBB);
13568
13569   // Take care of the PHI nodes.
13570   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13571           MI->getOperand(0).getReg())
13572     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13573     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13574
13575   // Delete the original pseudo instruction.
13576   MI->eraseFromParent();
13577
13578   // And we're done.
13579   return continueMBB;
13580 }
13581
13582 MachineBasicBlock *
13583 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13584                                           MachineBasicBlock *BB) const {
13585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13586   DebugLoc DL = MI->getDebugLoc();
13587
13588   assert(!Subtarget->isTargetEnvMacho());
13589
13590   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13591   // non-trivial part is impdef of ESP.
13592
13593   if (Subtarget->isTargetWin64()) {
13594     if (Subtarget->isTargetCygMing()) {
13595       // ___chkstk(Mingw64):
13596       // Clobbers R10, R11, RAX and EFLAGS.
13597       // Updates RSP.
13598       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13599         .addExternalSymbol("___chkstk")
13600         .addReg(X86::RAX, RegState::Implicit)
13601         .addReg(X86::RSP, RegState::Implicit)
13602         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13603         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13604         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13605     } else {
13606       // __chkstk(MSVCRT): does not update stack pointer.
13607       // Clobbers R10, R11 and EFLAGS.
13608       // FIXME: RAX(allocated size) might be reused and not killed.
13609       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13610         .addExternalSymbol("__chkstk")
13611         .addReg(X86::RAX, RegState::Implicit)
13612         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13613       // RAX has the offset to subtracted from RSP.
13614       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13615         .addReg(X86::RSP)
13616         .addReg(X86::RAX);
13617     }
13618   } else {
13619     const char *StackProbeSymbol =
13620       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13621
13622     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13623       .addExternalSymbol(StackProbeSymbol)
13624       .addReg(X86::EAX, RegState::Implicit)
13625       .addReg(X86::ESP, RegState::Implicit)
13626       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13627       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13628       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13629   }
13630
13631   MI->eraseFromParent();   // The pseudo instruction is gone now.
13632   return BB;
13633 }
13634
13635 MachineBasicBlock *
13636 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13637                                       MachineBasicBlock *BB) const {
13638   // This is pretty easy.  We're taking the value that we received from
13639   // our load from the relocation, sticking it in either RDI (x86-64)
13640   // or EAX and doing an indirect call.  The return value will then
13641   // be in the normal return register.
13642   const X86InstrInfo *TII
13643     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13644   DebugLoc DL = MI->getDebugLoc();
13645   MachineFunction *F = BB->getParent();
13646
13647   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13648   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13649
13650   // Get a register mask for the lowered call.
13651   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13652   // proper register mask.
13653   const uint32_t *RegMask =
13654     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13655   if (Subtarget->is64Bit()) {
13656     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13657                                       TII->get(X86::MOV64rm), X86::RDI)
13658     .addReg(X86::RIP)
13659     .addImm(0).addReg(0)
13660     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13661                       MI->getOperand(3).getTargetFlags())
13662     .addReg(0);
13663     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13664     addDirectMem(MIB, X86::RDI);
13665     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13666   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13667     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13668                                       TII->get(X86::MOV32rm), X86::EAX)
13669     .addReg(0)
13670     .addImm(0).addReg(0)
13671     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13672                       MI->getOperand(3).getTargetFlags())
13673     .addReg(0);
13674     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13675     addDirectMem(MIB, X86::EAX);
13676     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13677   } else {
13678     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13679                                       TII->get(X86::MOV32rm), X86::EAX)
13680     .addReg(TII->getGlobalBaseReg(F))
13681     .addImm(0).addReg(0)
13682     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13683                       MI->getOperand(3).getTargetFlags())
13684     .addReg(0);
13685     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13686     addDirectMem(MIB, X86::EAX);
13687     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13688   }
13689
13690   MI->eraseFromParent(); // The pseudo instruction is gone now.
13691   return BB;
13692 }
13693
13694 MachineBasicBlock *
13695 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13696                                     MachineBasicBlock *MBB) const {
13697   DebugLoc DL = MI->getDebugLoc();
13698   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13699
13700   MachineFunction *MF = MBB->getParent();
13701   MachineRegisterInfo &MRI = MF->getRegInfo();
13702
13703   const BasicBlock *BB = MBB->getBasicBlock();
13704   MachineFunction::iterator I = MBB;
13705   ++I;
13706
13707   // Memory Reference
13708   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13709   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13710
13711   unsigned DstReg;
13712   unsigned MemOpndSlot = 0;
13713
13714   unsigned CurOp = 0;
13715
13716   DstReg = MI->getOperand(CurOp++).getReg();
13717   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13718   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13719   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13720   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13721
13722   MemOpndSlot = CurOp;
13723
13724   MVT PVT = getPointerTy();
13725   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13726          "Invalid Pointer Size!");
13727
13728   // For v = setjmp(buf), we generate
13729   //
13730   // thisMBB:
13731   //  buf[LabelOffset] = restoreMBB
13732   //  SjLjSetup restoreMBB
13733   //
13734   // mainMBB:
13735   //  v_main = 0
13736   //
13737   // sinkMBB:
13738   //  v = phi(main, restore)
13739   //
13740   // restoreMBB:
13741   //  v_restore = 1
13742
13743   MachineBasicBlock *thisMBB = MBB;
13744   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13745   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13746   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13747   MF->insert(I, mainMBB);
13748   MF->insert(I, sinkMBB);
13749   MF->push_back(restoreMBB);
13750
13751   MachineInstrBuilder MIB;
13752
13753   // Transfer the remainder of BB and its successor edges to sinkMBB.
13754   sinkMBB->splice(sinkMBB->begin(), MBB,
13755                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13756   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13757
13758   // thisMBB:
13759   unsigned PtrStoreOpc = 0;
13760   unsigned LabelReg = 0;
13761   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13762   Reloc::Model RM = getTargetMachine().getRelocationModel();
13763   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13764                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13765
13766   // Prepare IP either in reg or imm.
13767   if (!UseImmLabel) {
13768     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13769     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13770     LabelReg = MRI.createVirtualRegister(PtrRC);
13771     if (Subtarget->is64Bit()) {
13772       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13773               .addReg(X86::RIP)
13774               .addImm(0)
13775               .addReg(0)
13776               .addMBB(restoreMBB)
13777               .addReg(0);
13778     } else {
13779       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13780       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13781               .addReg(XII->getGlobalBaseReg(MF))
13782               .addImm(0)
13783               .addReg(0)
13784               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13785               .addReg(0);
13786     }
13787   } else
13788     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13789   // Store IP
13790   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13791   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13792     if (i == X86::AddrDisp)
13793       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13794     else
13795       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13796   }
13797   if (!UseImmLabel)
13798     MIB.addReg(LabelReg);
13799   else
13800     MIB.addMBB(restoreMBB);
13801   MIB.setMemRefs(MMOBegin, MMOEnd);
13802   // Setup
13803   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13804           .addMBB(restoreMBB);
13805   MIB.addRegMask(RegInfo->getNoPreservedMask());
13806   thisMBB->addSuccessor(mainMBB);
13807   thisMBB->addSuccessor(restoreMBB);
13808
13809   // mainMBB:
13810   //  EAX = 0
13811   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13812   mainMBB->addSuccessor(sinkMBB);
13813
13814   // sinkMBB:
13815   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13816           TII->get(X86::PHI), DstReg)
13817     .addReg(mainDstReg).addMBB(mainMBB)
13818     .addReg(restoreDstReg).addMBB(restoreMBB);
13819
13820   // restoreMBB:
13821   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13822   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13823   restoreMBB->addSuccessor(sinkMBB);
13824
13825   MI->eraseFromParent();
13826   return sinkMBB;
13827 }
13828
13829 MachineBasicBlock *
13830 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13831                                      MachineBasicBlock *MBB) const {
13832   DebugLoc DL = MI->getDebugLoc();
13833   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13834
13835   MachineFunction *MF = MBB->getParent();
13836   MachineRegisterInfo &MRI = MF->getRegInfo();
13837
13838   // Memory Reference
13839   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13840   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13841
13842   MVT PVT = getPointerTy();
13843   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13844          "Invalid Pointer Size!");
13845
13846   const TargetRegisterClass *RC =
13847     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13848   unsigned Tmp = MRI.createVirtualRegister(RC);
13849   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13850   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13851   unsigned SP = RegInfo->getStackRegister();
13852
13853   MachineInstrBuilder MIB;
13854
13855   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13856   const int64_t SPOffset = 2 * PVT.getStoreSize();
13857
13858   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13859   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13860
13861   // Reload FP
13862   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13863   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13864     MIB.addOperand(MI->getOperand(i));
13865   MIB.setMemRefs(MMOBegin, MMOEnd);
13866   // Reload IP
13867   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13868   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13869     if (i == X86::AddrDisp)
13870       MIB.addDisp(MI->getOperand(i), LabelOffset);
13871     else
13872       MIB.addOperand(MI->getOperand(i));
13873   }
13874   MIB.setMemRefs(MMOBegin, MMOEnd);
13875   // Reload SP
13876   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13877   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13878     if (i == X86::AddrDisp)
13879       MIB.addDisp(MI->getOperand(i), SPOffset);
13880     else
13881       MIB.addOperand(MI->getOperand(i));
13882   }
13883   MIB.setMemRefs(MMOBegin, MMOEnd);
13884   // Jump
13885   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13886
13887   MI->eraseFromParent();
13888   return MBB;
13889 }
13890
13891 MachineBasicBlock *
13892 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13893                                                MachineBasicBlock *BB) const {
13894   switch (MI->getOpcode()) {
13895   default: llvm_unreachable("Unexpected instr type to insert");
13896   case X86::TAILJMPd64:
13897   case X86::TAILJMPr64:
13898   case X86::TAILJMPm64:
13899     llvm_unreachable("TAILJMP64 would not be touched here.");
13900   case X86::TCRETURNdi64:
13901   case X86::TCRETURNri64:
13902   case X86::TCRETURNmi64:
13903     return BB;
13904   case X86::WIN_ALLOCA:
13905     return EmitLoweredWinAlloca(MI, BB);
13906   case X86::SEG_ALLOCA_32:
13907     return EmitLoweredSegAlloca(MI, BB, false);
13908   case X86::SEG_ALLOCA_64:
13909     return EmitLoweredSegAlloca(MI, BB, true);
13910   case X86::TLSCall_32:
13911   case X86::TLSCall_64:
13912     return EmitLoweredTLSCall(MI, BB);
13913   case X86::CMOV_GR8:
13914   case X86::CMOV_FR32:
13915   case X86::CMOV_FR64:
13916   case X86::CMOV_V4F32:
13917   case X86::CMOV_V2F64:
13918   case X86::CMOV_V2I64:
13919   case X86::CMOV_V8F32:
13920   case X86::CMOV_V4F64:
13921   case X86::CMOV_V4I64:
13922   case X86::CMOV_GR16:
13923   case X86::CMOV_GR32:
13924   case X86::CMOV_RFP32:
13925   case X86::CMOV_RFP64:
13926   case X86::CMOV_RFP80:
13927     return EmitLoweredSelect(MI, BB);
13928
13929   case X86::FP32_TO_INT16_IN_MEM:
13930   case X86::FP32_TO_INT32_IN_MEM:
13931   case X86::FP32_TO_INT64_IN_MEM:
13932   case X86::FP64_TO_INT16_IN_MEM:
13933   case X86::FP64_TO_INT32_IN_MEM:
13934   case X86::FP64_TO_INT64_IN_MEM:
13935   case X86::FP80_TO_INT16_IN_MEM:
13936   case X86::FP80_TO_INT32_IN_MEM:
13937   case X86::FP80_TO_INT64_IN_MEM: {
13938     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13939     DebugLoc DL = MI->getDebugLoc();
13940
13941     // Change the floating point control register to use "round towards zero"
13942     // mode when truncating to an integer value.
13943     MachineFunction *F = BB->getParent();
13944     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13945     addFrameReference(BuildMI(*BB, MI, DL,
13946                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13947
13948     // Load the old value of the high byte of the control word...
13949     unsigned OldCW =
13950       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13951     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13952                       CWFrameIdx);
13953
13954     // Set the high part to be round to zero...
13955     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13956       .addImm(0xC7F);
13957
13958     // Reload the modified control word now...
13959     addFrameReference(BuildMI(*BB, MI, DL,
13960                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13961
13962     // Restore the memory image of control word to original value
13963     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13964       .addReg(OldCW);
13965
13966     // Get the X86 opcode to use.
13967     unsigned Opc;
13968     switch (MI->getOpcode()) {
13969     default: llvm_unreachable("illegal opcode!");
13970     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13971     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13972     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13973     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13974     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13975     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13976     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13977     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13978     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13979     }
13980
13981     X86AddressMode AM;
13982     MachineOperand &Op = MI->getOperand(0);
13983     if (Op.isReg()) {
13984       AM.BaseType = X86AddressMode::RegBase;
13985       AM.Base.Reg = Op.getReg();
13986     } else {
13987       AM.BaseType = X86AddressMode::FrameIndexBase;
13988       AM.Base.FrameIndex = Op.getIndex();
13989     }
13990     Op = MI->getOperand(1);
13991     if (Op.isImm())
13992       AM.Scale = Op.getImm();
13993     Op = MI->getOperand(2);
13994     if (Op.isImm())
13995       AM.IndexReg = Op.getImm();
13996     Op = MI->getOperand(3);
13997     if (Op.isGlobal()) {
13998       AM.GV = Op.getGlobal();
13999     } else {
14000       AM.Disp = Op.getImm();
14001     }
14002     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14003                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14004
14005     // Reload the original control word now.
14006     addFrameReference(BuildMI(*BB, MI, DL,
14007                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14008
14009     MI->eraseFromParent();   // The pseudo instruction is gone now.
14010     return BB;
14011   }
14012     // String/text processing lowering.
14013   case X86::PCMPISTRM128REG:
14014   case X86::VPCMPISTRM128REG:
14015   case X86::PCMPISTRM128MEM:
14016   case X86::VPCMPISTRM128MEM:
14017   case X86::PCMPESTRM128REG:
14018   case X86::VPCMPESTRM128REG:
14019   case X86::PCMPESTRM128MEM:
14020   case X86::VPCMPESTRM128MEM:
14021     assert(Subtarget->hasSSE42() &&
14022            "Target must have SSE4.2 or AVX features enabled");
14023     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14024
14025   // String/text processing lowering.
14026   case X86::PCMPISTRIREG:
14027   case X86::VPCMPISTRIREG:
14028   case X86::PCMPISTRIMEM:
14029   case X86::VPCMPISTRIMEM:
14030   case X86::PCMPESTRIREG:
14031   case X86::VPCMPESTRIREG:
14032   case X86::PCMPESTRIMEM:
14033   case X86::VPCMPESTRIMEM:
14034     assert(Subtarget->hasSSE42() &&
14035            "Target must have SSE4.2 or AVX features enabled");
14036     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14037
14038   // Thread synchronization.
14039   case X86::MONITOR:
14040     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14041
14042   // xbegin
14043   case X86::XBEGIN:
14044     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14045
14046   // Atomic Lowering.
14047   case X86::ATOMAND8:
14048   case X86::ATOMAND16:
14049   case X86::ATOMAND32:
14050   case X86::ATOMAND64:
14051     // Fall through
14052   case X86::ATOMOR8:
14053   case X86::ATOMOR16:
14054   case X86::ATOMOR32:
14055   case X86::ATOMOR64:
14056     // Fall through
14057   case X86::ATOMXOR16:
14058   case X86::ATOMXOR8:
14059   case X86::ATOMXOR32:
14060   case X86::ATOMXOR64:
14061     // Fall through
14062   case X86::ATOMNAND8:
14063   case X86::ATOMNAND16:
14064   case X86::ATOMNAND32:
14065   case X86::ATOMNAND64:
14066     // Fall through
14067   case X86::ATOMMAX8:
14068   case X86::ATOMMAX16:
14069   case X86::ATOMMAX32:
14070   case X86::ATOMMAX64:
14071     // Fall through
14072   case X86::ATOMMIN8:
14073   case X86::ATOMMIN16:
14074   case X86::ATOMMIN32:
14075   case X86::ATOMMIN64:
14076     // Fall through
14077   case X86::ATOMUMAX8:
14078   case X86::ATOMUMAX16:
14079   case X86::ATOMUMAX32:
14080   case X86::ATOMUMAX64:
14081     // Fall through
14082   case X86::ATOMUMIN8:
14083   case X86::ATOMUMIN16:
14084   case X86::ATOMUMIN32:
14085   case X86::ATOMUMIN64:
14086     return EmitAtomicLoadArith(MI, BB);
14087
14088   // This group does 64-bit operations on a 32-bit host.
14089   case X86::ATOMAND6432:
14090   case X86::ATOMOR6432:
14091   case X86::ATOMXOR6432:
14092   case X86::ATOMNAND6432:
14093   case X86::ATOMADD6432:
14094   case X86::ATOMSUB6432:
14095   case X86::ATOMMAX6432:
14096   case X86::ATOMMIN6432:
14097   case X86::ATOMUMAX6432:
14098   case X86::ATOMUMIN6432:
14099   case X86::ATOMSWAP6432:
14100     return EmitAtomicLoadArith6432(MI, BB);
14101
14102   case X86::VASTART_SAVE_XMM_REGS:
14103     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14104
14105   case X86::VAARG_64:
14106     return EmitVAARG64WithCustomInserter(MI, BB);
14107
14108   case X86::EH_SjLj_SetJmp32:
14109   case X86::EH_SjLj_SetJmp64:
14110     return emitEHSjLjSetJmp(MI, BB);
14111
14112   case X86::EH_SjLj_LongJmp32:
14113   case X86::EH_SjLj_LongJmp64:
14114     return emitEHSjLjLongJmp(MI, BB);
14115   }
14116 }
14117
14118 //===----------------------------------------------------------------------===//
14119 //                           X86 Optimization Hooks
14120 //===----------------------------------------------------------------------===//
14121
14122 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14123                                                        APInt &KnownZero,
14124                                                        APInt &KnownOne,
14125                                                        const SelectionDAG &DAG,
14126                                                        unsigned Depth) const {
14127   unsigned BitWidth = KnownZero.getBitWidth();
14128   unsigned Opc = Op.getOpcode();
14129   assert((Opc >= ISD::BUILTIN_OP_END ||
14130           Opc == ISD::INTRINSIC_WO_CHAIN ||
14131           Opc == ISD::INTRINSIC_W_CHAIN ||
14132           Opc == ISD::INTRINSIC_VOID) &&
14133          "Should use MaskedValueIsZero if you don't know whether Op"
14134          " is a target node!");
14135
14136   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14137   switch (Opc) {
14138   default: break;
14139   case X86ISD::ADD:
14140   case X86ISD::SUB:
14141   case X86ISD::ADC:
14142   case X86ISD::SBB:
14143   case X86ISD::SMUL:
14144   case X86ISD::UMUL:
14145   case X86ISD::INC:
14146   case X86ISD::DEC:
14147   case X86ISD::OR:
14148   case X86ISD::XOR:
14149   case X86ISD::AND:
14150     // These nodes' second result is a boolean.
14151     if (Op.getResNo() == 0)
14152       break;
14153     // Fallthrough
14154   case X86ISD::SETCC:
14155     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14156     break;
14157   case ISD::INTRINSIC_WO_CHAIN: {
14158     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14159     unsigned NumLoBits = 0;
14160     switch (IntId) {
14161     default: break;
14162     case Intrinsic::x86_sse_movmsk_ps:
14163     case Intrinsic::x86_avx_movmsk_ps_256:
14164     case Intrinsic::x86_sse2_movmsk_pd:
14165     case Intrinsic::x86_avx_movmsk_pd_256:
14166     case Intrinsic::x86_mmx_pmovmskb:
14167     case Intrinsic::x86_sse2_pmovmskb_128:
14168     case Intrinsic::x86_avx2_pmovmskb: {
14169       // High bits of movmskp{s|d}, pmovmskb are known zero.
14170       switch (IntId) {
14171         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14172         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14173         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14174         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14175         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14176         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14177         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14178         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14179       }
14180       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14181       break;
14182     }
14183     }
14184     break;
14185   }
14186   }
14187 }
14188
14189 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14190                                                          unsigned Depth) const {
14191   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14192   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14193     return Op.getValueType().getScalarType().getSizeInBits();
14194
14195   // Fallback case.
14196   return 1;
14197 }
14198
14199 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14200 /// node is a GlobalAddress + offset.
14201 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14202                                        const GlobalValue* &GA,
14203                                        int64_t &Offset) const {
14204   if (N->getOpcode() == X86ISD::Wrapper) {
14205     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14206       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14207       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14208       return true;
14209     }
14210   }
14211   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14212 }
14213
14214 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14215 /// same as extracting the high 128-bit part of 256-bit vector and then
14216 /// inserting the result into the low part of a new 256-bit vector
14217 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14218   EVT VT = SVOp->getValueType(0);
14219   unsigned NumElems = VT.getVectorNumElements();
14220
14221   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14222   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14223     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14224         SVOp->getMaskElt(j) >= 0)
14225       return false;
14226
14227   return true;
14228 }
14229
14230 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14231 /// same as extracting the low 128-bit part of 256-bit vector and then
14232 /// inserting the result into the high part of a new 256-bit vector
14233 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14234   EVT VT = SVOp->getValueType(0);
14235   unsigned NumElems = VT.getVectorNumElements();
14236
14237   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14238   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14239     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14240         SVOp->getMaskElt(j) >= 0)
14241       return false;
14242
14243   return true;
14244 }
14245
14246 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14247 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14248                                         TargetLowering::DAGCombinerInfo &DCI,
14249                                         const X86Subtarget* Subtarget) {
14250   DebugLoc dl = N->getDebugLoc();
14251   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14252   SDValue V1 = SVOp->getOperand(0);
14253   SDValue V2 = SVOp->getOperand(1);
14254   EVT VT = SVOp->getValueType(0);
14255   unsigned NumElems = VT.getVectorNumElements();
14256
14257   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14258       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14259     //
14260     //                   0,0,0,...
14261     //                      |
14262     //    V      UNDEF    BUILD_VECTOR    UNDEF
14263     //     \      /           \           /
14264     //  CONCAT_VECTOR         CONCAT_VECTOR
14265     //         \                  /
14266     //          \                /
14267     //          RESULT: V + zero extended
14268     //
14269     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14270         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14271         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14272       return SDValue();
14273
14274     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14275       return SDValue();
14276
14277     // To match the shuffle mask, the first half of the mask should
14278     // be exactly the first vector, and all the rest a splat with the
14279     // first element of the second one.
14280     for (unsigned i = 0; i != NumElems/2; ++i)
14281       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14282           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14283         return SDValue();
14284
14285     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14286     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14287       if (Ld->hasNUsesOfValue(1, 0)) {
14288         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14289         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14290         SDValue ResNode =
14291           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14292                                   Ld->getMemoryVT(),
14293                                   Ld->getPointerInfo(),
14294                                   Ld->getAlignment(),
14295                                   false/*isVolatile*/, true/*ReadMem*/,
14296                                   false/*WriteMem*/);
14297
14298         // Make sure the newly-created LOAD is in the same position as Ld in
14299         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14300         // and update uses of Ld's output chain to use the TokenFactor.
14301         if (Ld->hasAnyUseOfValue(1)) {
14302           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14303                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14304           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14305           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14306                                  SDValue(ResNode.getNode(), 1));
14307         }
14308
14309         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14310       }
14311     }
14312
14313     // Emit a zeroed vector and insert the desired subvector on its
14314     // first half.
14315     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14316     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14317     return DCI.CombineTo(N, InsV);
14318   }
14319
14320   //===--------------------------------------------------------------------===//
14321   // Combine some shuffles into subvector extracts and inserts:
14322   //
14323
14324   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14325   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14326     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14327     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14328     return DCI.CombineTo(N, InsV);
14329   }
14330
14331   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14332   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14333     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14334     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14335     return DCI.CombineTo(N, InsV);
14336   }
14337
14338   return SDValue();
14339 }
14340
14341 /// PerformShuffleCombine - Performs several different shuffle combines.
14342 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14343                                      TargetLowering::DAGCombinerInfo &DCI,
14344                                      const X86Subtarget *Subtarget) {
14345   DebugLoc dl = N->getDebugLoc();
14346   EVT VT = N->getValueType(0);
14347
14348   // Don't create instructions with illegal types after legalize types has run.
14349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14350   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14351     return SDValue();
14352
14353   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14354   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14355       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14356     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14357
14358   // Only handle 128 wide vector from here on.
14359   if (!VT.is128BitVector())
14360     return SDValue();
14361
14362   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14363   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14364   // consecutive, non-overlapping, and in the right order.
14365   SmallVector<SDValue, 16> Elts;
14366   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14367     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14368
14369   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14370 }
14371
14372 /// PerformTruncateCombine - Converts truncate operation to
14373 /// a sequence of vector shuffle operations.
14374 /// It is possible when we truncate 256-bit vector to 128-bit vector
14375 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14376                                       TargetLowering::DAGCombinerInfo &DCI,
14377                                       const X86Subtarget *Subtarget)  {
14378   if (!DCI.isBeforeLegalizeOps())
14379     return SDValue();
14380
14381   if (!Subtarget->hasFp256())
14382     return SDValue();
14383
14384   EVT VT = N->getValueType(0);
14385   SDValue Op = N->getOperand(0);
14386   EVT OpVT = Op.getValueType();
14387   DebugLoc dl = N->getDebugLoc();
14388
14389   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14390
14391     if (Subtarget->hasInt256()) {
14392       // AVX2: v4i64 -> v4i32
14393
14394       // VPERMD
14395       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14396
14397       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14398       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14399                                 ShufMask);
14400
14401       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14402                          DAG.getIntPtrConstant(0));
14403     }
14404
14405     // AVX: v4i64 -> v4i32
14406     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14407                                DAG.getIntPtrConstant(0));
14408
14409     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14410                                DAG.getIntPtrConstant(2));
14411
14412     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14413     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14414
14415     // PSHUFD
14416     static const int ShufMask1[] = {0, 2, 0, 0};
14417
14418     SDValue Undef = DAG.getUNDEF(VT);
14419     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14420     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14421
14422     // MOVLHPS
14423     static const int ShufMask2[] = {0, 1, 4, 5};
14424
14425     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14426   }
14427
14428   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14429
14430     if (Subtarget->hasInt256()) {
14431       // AVX2: v8i32 -> v8i16
14432
14433       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14434
14435       // PSHUFB
14436       SmallVector<SDValue,32> pshufbMask;
14437       for (unsigned i = 0; i < 2; ++i) {
14438         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14439         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14440         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14441         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14442         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14443         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14444         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14445         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14446         for (unsigned j = 0; j < 8; ++j)
14447           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14448       }
14449       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14450                                &pshufbMask[0], 32);
14451       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14452
14453       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14454
14455       static const int ShufMask[] = {0,  2,  -1,  -1};
14456       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14457                                 &ShufMask[0]);
14458
14459       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14460                        DAG.getIntPtrConstant(0));
14461
14462       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14463     }
14464
14465     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14466                                DAG.getIntPtrConstant(0));
14467
14468     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14469                                DAG.getIntPtrConstant(4));
14470
14471     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14472     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14473
14474     // PSHUFB
14475     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14476                                    -1, -1, -1, -1, -1, -1, -1, -1};
14477
14478     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14479     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14480     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14481
14482     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14483     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14484
14485     // MOVLHPS
14486     static const int ShufMask2[] = {0, 1, 4, 5};
14487
14488     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14489     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14490   }
14491
14492   return SDValue();
14493 }
14494
14495 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14496 /// specific shuffle of a load can be folded into a single element load.
14497 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14498 /// shuffles have been customed lowered so we need to handle those here.
14499 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14500                                          TargetLowering::DAGCombinerInfo &DCI) {
14501   if (DCI.isBeforeLegalizeOps())
14502     return SDValue();
14503
14504   SDValue InVec = N->getOperand(0);
14505   SDValue EltNo = N->getOperand(1);
14506
14507   if (!isa<ConstantSDNode>(EltNo))
14508     return SDValue();
14509
14510   EVT VT = InVec.getValueType();
14511
14512   bool HasShuffleIntoBitcast = false;
14513   if (InVec.getOpcode() == ISD::BITCAST) {
14514     // Don't duplicate a load with other uses.
14515     if (!InVec.hasOneUse())
14516       return SDValue();
14517     EVT BCVT = InVec.getOperand(0).getValueType();
14518     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14519       return SDValue();
14520     InVec = InVec.getOperand(0);
14521     HasShuffleIntoBitcast = true;
14522   }
14523
14524   if (!isTargetShuffle(InVec.getOpcode()))
14525     return SDValue();
14526
14527   // Don't duplicate a load with other uses.
14528   if (!InVec.hasOneUse())
14529     return SDValue();
14530
14531   SmallVector<int, 16> ShuffleMask;
14532   bool UnaryShuffle;
14533   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14534                             UnaryShuffle))
14535     return SDValue();
14536
14537   // Select the input vector, guarding against out of range extract vector.
14538   unsigned NumElems = VT.getVectorNumElements();
14539   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14540   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14541   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14542                                          : InVec.getOperand(1);
14543
14544   // If inputs to shuffle are the same for both ops, then allow 2 uses
14545   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14546
14547   if (LdNode.getOpcode() == ISD::BITCAST) {
14548     // Don't duplicate a load with other uses.
14549     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14550       return SDValue();
14551
14552     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14553     LdNode = LdNode.getOperand(0);
14554   }
14555
14556   if (!ISD::isNormalLoad(LdNode.getNode()))
14557     return SDValue();
14558
14559   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14560
14561   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14562     return SDValue();
14563
14564   if (HasShuffleIntoBitcast) {
14565     // If there's a bitcast before the shuffle, check if the load type and
14566     // alignment is valid.
14567     unsigned Align = LN0->getAlignment();
14568     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14569     unsigned NewAlign = TLI.getDataLayout()->
14570       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14571
14572     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14573       return SDValue();
14574   }
14575
14576   // All checks match so transform back to vector_shuffle so that DAG combiner
14577   // can finish the job
14578   DebugLoc dl = N->getDebugLoc();
14579
14580   // Create shuffle node taking into account the case that its a unary shuffle
14581   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14582   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14583                                  InVec.getOperand(0), Shuffle,
14584                                  &ShuffleMask[0]);
14585   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14586   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14587                      EltNo);
14588 }
14589
14590 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14591 /// generation and convert it from being a bunch of shuffles and extracts
14592 /// to a simple store and scalar loads to extract the elements.
14593 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14594                                          TargetLowering::DAGCombinerInfo &DCI) {
14595   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14596   if (NewOp.getNode())
14597     return NewOp;
14598
14599   SDValue InputVector = N->getOperand(0);
14600   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14601   // from mmx to v2i32 has a single usage.
14602   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14603       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14604       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14605     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14606                        N->getValueType(0),
14607                        InputVector.getNode()->getOperand(0));
14608
14609   // Only operate on vectors of 4 elements, where the alternative shuffling
14610   // gets to be more expensive.
14611   if (InputVector.getValueType() != MVT::v4i32)
14612     return SDValue();
14613
14614   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14615   // single use which is a sign-extend or zero-extend, and all elements are
14616   // used.
14617   SmallVector<SDNode *, 4> Uses;
14618   unsigned ExtractedElements = 0;
14619   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14620        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14621     if (UI.getUse().getResNo() != InputVector.getResNo())
14622       return SDValue();
14623
14624     SDNode *Extract = *UI;
14625     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14626       return SDValue();
14627
14628     if (Extract->getValueType(0) != MVT::i32)
14629       return SDValue();
14630     if (!Extract->hasOneUse())
14631       return SDValue();
14632     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14633         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14634       return SDValue();
14635     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14636       return SDValue();
14637
14638     // Record which element was extracted.
14639     ExtractedElements |=
14640       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14641
14642     Uses.push_back(Extract);
14643   }
14644
14645   // If not all the elements were used, this may not be worthwhile.
14646   if (ExtractedElements != 15)
14647     return SDValue();
14648
14649   // Ok, we've now decided to do the transformation.
14650   DebugLoc dl = InputVector.getDebugLoc();
14651
14652   // Store the value to a temporary stack slot.
14653   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14654   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14655                             MachinePointerInfo(), false, false, 0);
14656
14657   // Replace each use (extract) with a load of the appropriate element.
14658   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14659        UE = Uses.end(); UI != UE; ++UI) {
14660     SDNode *Extract = *UI;
14661
14662     // cOMpute the element's address.
14663     SDValue Idx = Extract->getOperand(1);
14664     unsigned EltSize =
14665         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14666     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14667     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14668     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14669
14670     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14671                                      StackPtr, OffsetVal);
14672
14673     // Load the scalar.
14674     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14675                                      ScalarAddr, MachinePointerInfo(),
14676                                      false, false, false, 0);
14677
14678     // Replace the exact with the load.
14679     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14680   }
14681
14682   // The replacement was made in place; don't return anything.
14683   return SDValue();
14684 }
14685
14686 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14687 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14688                                    SDValue RHS, SelectionDAG &DAG,
14689                                    const X86Subtarget *Subtarget) {
14690   if (!VT.isVector())
14691     return 0;
14692
14693   switch (VT.getSimpleVT().SimpleTy) {
14694   default: return 0;
14695   case MVT::v32i8:
14696   case MVT::v16i16:
14697   case MVT::v8i32:
14698     if (!Subtarget->hasAVX2())
14699       return 0;
14700   case MVT::v16i8:
14701   case MVT::v8i16:
14702   case MVT::v4i32:
14703     if (!Subtarget->hasSSE2())
14704       return 0;
14705   }
14706
14707   // SSE2 has only a small subset of the operations.
14708   bool hasUnsigned = Subtarget->hasSSE41() ||
14709                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
14710   bool hasSigned = Subtarget->hasSSE41() ||
14711                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
14712
14713   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14714
14715   // Check for x CC y ? x : y.
14716   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14717       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14718     switch (CC) {
14719     default: break;
14720     case ISD::SETULT:
14721     case ISD::SETULE:
14722       return hasUnsigned ? X86ISD::UMIN : 0;
14723     case ISD::SETUGT:
14724     case ISD::SETUGE:
14725       return hasUnsigned ? X86ISD::UMAX : 0;
14726     case ISD::SETLT:
14727     case ISD::SETLE:
14728       return hasSigned ? X86ISD::SMIN : 0;
14729     case ISD::SETGT:
14730     case ISD::SETGE:
14731       return hasSigned ? X86ISD::SMAX : 0;
14732     }
14733   // Check for x CC y ? y : x -- a min/max with reversed arms.
14734   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14735              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14736     switch (CC) {
14737     default: break;
14738     case ISD::SETULT:
14739     case ISD::SETULE:
14740       return hasUnsigned ? X86ISD::UMAX : 0;
14741     case ISD::SETUGT:
14742     case ISD::SETUGE:
14743       return hasUnsigned ? X86ISD::UMIN : 0;
14744     case ISD::SETLT:
14745     case ISD::SETLE:
14746       return hasSigned ? X86ISD::SMAX : 0;
14747     case ISD::SETGT:
14748     case ISD::SETGE:
14749       return hasSigned ? X86ISD::SMIN : 0;
14750     }
14751   }
14752
14753   return 0;
14754 }
14755
14756 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14757 /// nodes.
14758 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14759                                     TargetLowering::DAGCombinerInfo &DCI,
14760                                     const X86Subtarget *Subtarget) {
14761   DebugLoc DL = N->getDebugLoc();
14762   SDValue Cond = N->getOperand(0);
14763   // Get the LHS/RHS of the select.
14764   SDValue LHS = N->getOperand(1);
14765   SDValue RHS = N->getOperand(2);
14766   EVT VT = LHS.getValueType();
14767
14768   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14769   // instructions match the semantics of the common C idiom x<y?x:y but not
14770   // x<=y?x:y, because of how they handle negative zero (which can be
14771   // ignored in unsafe-math mode).
14772   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14773       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14774       (Subtarget->hasSSE2() ||
14775        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14776     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14777
14778     unsigned Opcode = 0;
14779     // Check for x CC y ? x : y.
14780     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14781         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14782       switch (CC) {
14783       default: break;
14784       case ISD::SETULT:
14785         // Converting this to a min would handle NaNs incorrectly, and swapping
14786         // the operands would cause it to handle comparisons between positive
14787         // and negative zero incorrectly.
14788         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14789           if (!DAG.getTarget().Options.UnsafeFPMath &&
14790               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14791             break;
14792           std::swap(LHS, RHS);
14793         }
14794         Opcode = X86ISD::FMIN;
14795         break;
14796       case ISD::SETOLE:
14797         // Converting this to a min would handle comparisons between positive
14798         // and negative zero incorrectly.
14799         if (!DAG.getTarget().Options.UnsafeFPMath &&
14800             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14801           break;
14802         Opcode = X86ISD::FMIN;
14803         break;
14804       case ISD::SETULE:
14805         // Converting this to a min would handle both negative zeros and NaNs
14806         // incorrectly, but we can swap the operands to fix both.
14807         std::swap(LHS, RHS);
14808       case ISD::SETOLT:
14809       case ISD::SETLT:
14810       case ISD::SETLE:
14811         Opcode = X86ISD::FMIN;
14812         break;
14813
14814       case ISD::SETOGE:
14815         // Converting this to a max would handle comparisons between positive
14816         // and negative zero incorrectly.
14817         if (!DAG.getTarget().Options.UnsafeFPMath &&
14818             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14819           break;
14820         Opcode = X86ISD::FMAX;
14821         break;
14822       case ISD::SETUGT:
14823         // Converting this to a max would handle NaNs incorrectly, and swapping
14824         // the operands would cause it to handle comparisons between positive
14825         // and negative zero incorrectly.
14826         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14827           if (!DAG.getTarget().Options.UnsafeFPMath &&
14828               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14829             break;
14830           std::swap(LHS, RHS);
14831         }
14832         Opcode = X86ISD::FMAX;
14833         break;
14834       case ISD::SETUGE:
14835         // Converting this to a max would handle both negative zeros and NaNs
14836         // incorrectly, but we can swap the operands to fix both.
14837         std::swap(LHS, RHS);
14838       case ISD::SETOGT:
14839       case ISD::SETGT:
14840       case ISD::SETGE:
14841         Opcode = X86ISD::FMAX;
14842         break;
14843       }
14844     // Check for x CC y ? y : x -- a min/max with reversed arms.
14845     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14846                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14847       switch (CC) {
14848       default: break;
14849       case ISD::SETOGE:
14850         // Converting this to a min would handle comparisons between positive
14851         // and negative zero incorrectly, and swapping the operands would
14852         // cause it to handle NaNs incorrectly.
14853         if (!DAG.getTarget().Options.UnsafeFPMath &&
14854             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14855           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14856             break;
14857           std::swap(LHS, RHS);
14858         }
14859         Opcode = X86ISD::FMIN;
14860         break;
14861       case ISD::SETUGT:
14862         // Converting this to a min would handle NaNs incorrectly.
14863         if (!DAG.getTarget().Options.UnsafeFPMath &&
14864             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14865           break;
14866         Opcode = X86ISD::FMIN;
14867         break;
14868       case ISD::SETUGE:
14869         // Converting this to a min would handle both negative zeros and NaNs
14870         // incorrectly, but we can swap the operands to fix both.
14871         std::swap(LHS, RHS);
14872       case ISD::SETOGT:
14873       case ISD::SETGT:
14874       case ISD::SETGE:
14875         Opcode = X86ISD::FMIN;
14876         break;
14877
14878       case ISD::SETULT:
14879         // Converting this to a max would handle NaNs incorrectly.
14880         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14881           break;
14882         Opcode = X86ISD::FMAX;
14883         break;
14884       case ISD::SETOLE:
14885         // Converting this to a max would handle comparisons between positive
14886         // and negative zero incorrectly, and swapping the operands would
14887         // cause it to handle NaNs incorrectly.
14888         if (!DAG.getTarget().Options.UnsafeFPMath &&
14889             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14890           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14891             break;
14892           std::swap(LHS, RHS);
14893         }
14894         Opcode = X86ISD::FMAX;
14895         break;
14896       case ISD::SETULE:
14897         // Converting this to a max would handle both negative zeros and NaNs
14898         // incorrectly, but we can swap the operands to fix both.
14899         std::swap(LHS, RHS);
14900       case ISD::SETOLT:
14901       case ISD::SETLT:
14902       case ISD::SETLE:
14903         Opcode = X86ISD::FMAX;
14904         break;
14905       }
14906     }
14907
14908     if (Opcode)
14909       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14910   }
14911
14912   // If this is a select between two integer constants, try to do some
14913   // optimizations.
14914   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14915     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14916       // Don't do this for crazy integer types.
14917       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14918         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14919         // so that TrueC (the true value) is larger than FalseC.
14920         bool NeedsCondInvert = false;
14921
14922         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14923             // Efficiently invertible.
14924             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14925              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14926               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14927           NeedsCondInvert = true;
14928           std::swap(TrueC, FalseC);
14929         }
14930
14931         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14932         if (FalseC->getAPIntValue() == 0 &&
14933             TrueC->getAPIntValue().isPowerOf2()) {
14934           if (NeedsCondInvert) // Invert the condition if needed.
14935             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14936                                DAG.getConstant(1, Cond.getValueType()));
14937
14938           // Zero extend the condition if needed.
14939           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14940
14941           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14942           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14943                              DAG.getConstant(ShAmt, MVT::i8));
14944         }
14945
14946         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14947         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14948           if (NeedsCondInvert) // Invert the condition if needed.
14949             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14950                                DAG.getConstant(1, Cond.getValueType()));
14951
14952           // Zero extend the condition if needed.
14953           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14954                              FalseC->getValueType(0), Cond);
14955           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14956                              SDValue(FalseC, 0));
14957         }
14958
14959         // Optimize cases that will turn into an LEA instruction.  This requires
14960         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14961         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14962           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14963           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14964
14965           bool isFastMultiplier = false;
14966           if (Diff < 10) {
14967             switch ((unsigned char)Diff) {
14968               default: break;
14969               case 1:  // result = add base, cond
14970               case 2:  // result = lea base(    , cond*2)
14971               case 3:  // result = lea base(cond, cond*2)
14972               case 4:  // result = lea base(    , cond*4)
14973               case 5:  // result = lea base(cond, cond*4)
14974               case 8:  // result = lea base(    , cond*8)
14975               case 9:  // result = lea base(cond, cond*8)
14976                 isFastMultiplier = true;
14977                 break;
14978             }
14979           }
14980
14981           if (isFastMultiplier) {
14982             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14983             if (NeedsCondInvert) // Invert the condition if needed.
14984               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14985                                  DAG.getConstant(1, Cond.getValueType()));
14986
14987             // Zero extend the condition if needed.
14988             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14989                                Cond);
14990             // Scale the condition by the difference.
14991             if (Diff != 1)
14992               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14993                                  DAG.getConstant(Diff, Cond.getValueType()));
14994
14995             // Add the base if non-zero.
14996             if (FalseC->getAPIntValue() != 0)
14997               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14998                                  SDValue(FalseC, 0));
14999             return Cond;
15000           }
15001         }
15002       }
15003   }
15004
15005   // Canonicalize max and min:
15006   // (x > y) ? x : y -> (x >= y) ? x : y
15007   // (x < y) ? x : y -> (x <= y) ? x : y
15008   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15009   // the need for an extra compare
15010   // against zero. e.g.
15011   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15012   // subl   %esi, %edi
15013   // testl  %edi, %edi
15014   // movl   $0, %eax
15015   // cmovgl %edi, %eax
15016   // =>
15017   // xorl   %eax, %eax
15018   // subl   %esi, $edi
15019   // cmovsl %eax, %edi
15020   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15021       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15022       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15023     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15024     switch (CC) {
15025     default: break;
15026     case ISD::SETLT:
15027     case ISD::SETGT: {
15028       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15029       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15030                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15031       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15032     }
15033     }
15034   }
15035
15036   // Match VSELECTs into subs with unsigned saturation.
15037   if (!DCI.isBeforeLegalize() &&
15038       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15039       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15040       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15041        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15042     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15043
15044     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15045     // left side invert the predicate to simplify logic below.
15046     SDValue Other;
15047     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15048       Other = RHS;
15049       CC = ISD::getSetCCInverse(CC, true);
15050     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15051       Other = LHS;
15052     }
15053
15054     if (Other.getNode() && Other->getNumOperands() == 2 &&
15055         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15056       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15057       SDValue CondRHS = Cond->getOperand(1);
15058
15059       // Look for a general sub with unsigned saturation first.
15060       // x >= y ? x-y : 0 --> subus x, y
15061       // x >  y ? x-y : 0 --> subus x, y
15062       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15063           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15064         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15065
15066       // If the RHS is a constant we have to reverse the const canonicalization.
15067       // x > C-1 ? x+-C : 0 --> subus x, C
15068       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15069           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15070         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15071         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15072           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15073                                      DAG.getConstant(-A, VT.getScalarType()));
15074           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15075                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15076                                          V.data(), V.size()));
15077         }
15078       }
15079
15080       // Another special case: If C was a sign bit, the sub has been
15081       // canonicalized into a xor.
15082       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15083       //        it's safe to decanonicalize the xor?
15084       // x s< 0 ? x^C : 0 --> subus x, C
15085       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15086           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15087           isSplatVector(OpRHS.getNode())) {
15088         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15089         if (A.isSignBit())
15090           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15091       }
15092     }
15093   }
15094
15095   // Try to match a min/max vector operation.
15096   if (!DCI.isBeforeLegalize() &&
15097       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15098     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15099       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15100
15101   // If we know that this node is legal then we know that it is going to be
15102   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15103   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15104   // to simplify previous instructions.
15105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15106   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15107       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15108     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15109
15110     // Don't optimize vector selects that map to mask-registers.
15111     if (BitWidth == 1)
15112       return SDValue();
15113
15114     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15115     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15116
15117     APInt KnownZero, KnownOne;
15118     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15119                                           DCI.isBeforeLegalizeOps());
15120     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15121         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15122       DCI.CommitTargetLoweringOpt(TLO);
15123   }
15124
15125   return SDValue();
15126 }
15127
15128 // Check whether a boolean test is testing a boolean value generated by
15129 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15130 // code.
15131 //
15132 // Simplify the following patterns:
15133 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15134 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15135 // to (Op EFLAGS Cond)
15136 //
15137 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15138 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15139 // to (Op EFLAGS !Cond)
15140 //
15141 // where Op could be BRCOND or CMOV.
15142 //
15143 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15144   // Quit if not CMP and SUB with its value result used.
15145   if (Cmp.getOpcode() != X86ISD::CMP &&
15146       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15147       return SDValue();
15148
15149   // Quit if not used as a boolean value.
15150   if (CC != X86::COND_E && CC != X86::COND_NE)
15151     return SDValue();
15152
15153   // Check CMP operands. One of them should be 0 or 1 and the other should be
15154   // an SetCC or extended from it.
15155   SDValue Op1 = Cmp.getOperand(0);
15156   SDValue Op2 = Cmp.getOperand(1);
15157
15158   SDValue SetCC;
15159   const ConstantSDNode* C = 0;
15160   bool needOppositeCond = (CC == X86::COND_E);
15161
15162   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15163     SetCC = Op2;
15164   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15165     SetCC = Op1;
15166   else // Quit if all operands are not constants.
15167     return SDValue();
15168
15169   if (C->getZExtValue() == 1)
15170     needOppositeCond = !needOppositeCond;
15171   else if (C->getZExtValue() != 0)
15172     // Quit if the constant is neither 0 or 1.
15173     return SDValue();
15174
15175   // Skip 'zext' node.
15176   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15177     SetCC = SetCC.getOperand(0);
15178
15179   switch (SetCC.getOpcode()) {
15180   case X86ISD::SETCC:
15181     // Set the condition code or opposite one if necessary.
15182     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15183     if (needOppositeCond)
15184       CC = X86::GetOppositeBranchCondition(CC);
15185     return SetCC.getOperand(1);
15186   case X86ISD::CMOV: {
15187     // Check whether false/true value has canonical one, i.e. 0 or 1.
15188     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15189     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15190     // Quit if true value is not a constant.
15191     if (!TVal)
15192       return SDValue();
15193     // Quit if false value is not a constant.
15194     if (!FVal) {
15195       // A special case for rdrand, where 0 is set if false cond is found.
15196       SDValue Op = SetCC.getOperand(0);
15197       if (Op.getOpcode() != X86ISD::RDRAND)
15198         return SDValue();
15199     }
15200     // Quit if false value is not the constant 0 or 1.
15201     bool FValIsFalse = true;
15202     if (FVal && FVal->getZExtValue() != 0) {
15203       if (FVal->getZExtValue() != 1)
15204         return SDValue();
15205       // If FVal is 1, opposite cond is needed.
15206       needOppositeCond = !needOppositeCond;
15207       FValIsFalse = false;
15208     }
15209     // Quit if TVal is not the constant opposite of FVal.
15210     if (FValIsFalse && TVal->getZExtValue() != 1)
15211       return SDValue();
15212     if (!FValIsFalse && TVal->getZExtValue() != 0)
15213       return SDValue();
15214     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15215     if (needOppositeCond)
15216       CC = X86::GetOppositeBranchCondition(CC);
15217     return SetCC.getOperand(3);
15218   }
15219   }
15220
15221   return SDValue();
15222 }
15223
15224 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15225 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15226                                   TargetLowering::DAGCombinerInfo &DCI,
15227                                   const X86Subtarget *Subtarget) {
15228   DebugLoc DL = N->getDebugLoc();
15229
15230   // If the flag operand isn't dead, don't touch this CMOV.
15231   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15232     return SDValue();
15233
15234   SDValue FalseOp = N->getOperand(0);
15235   SDValue TrueOp = N->getOperand(1);
15236   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15237   SDValue Cond = N->getOperand(3);
15238
15239   if (CC == X86::COND_E || CC == X86::COND_NE) {
15240     switch (Cond.getOpcode()) {
15241     default: break;
15242     case X86ISD::BSR:
15243     case X86ISD::BSF:
15244       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15245       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15246         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15247     }
15248   }
15249
15250   SDValue Flags;
15251
15252   Flags = checkBoolTestSetCCCombine(Cond, CC);
15253   if (Flags.getNode() &&
15254       // Extra check as FCMOV only supports a subset of X86 cond.
15255       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15256     SDValue Ops[] = { FalseOp, TrueOp,
15257                       DAG.getConstant(CC, MVT::i8), Flags };
15258     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15259                        Ops, array_lengthof(Ops));
15260   }
15261
15262   // If this is a select between two integer constants, try to do some
15263   // optimizations.  Note that the operands are ordered the opposite of SELECT
15264   // operands.
15265   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15266     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15267       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15268       // larger than FalseC (the false value).
15269       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15270         CC = X86::GetOppositeBranchCondition(CC);
15271         std::swap(TrueC, FalseC);
15272         std::swap(TrueOp, FalseOp);
15273       }
15274
15275       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15276       // This is efficient for any integer data type (including i8/i16) and
15277       // shift amount.
15278       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15279         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15280                            DAG.getConstant(CC, MVT::i8), Cond);
15281
15282         // Zero extend the condition if needed.
15283         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15284
15285         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15286         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15287                            DAG.getConstant(ShAmt, MVT::i8));
15288         if (N->getNumValues() == 2)  // Dead flag value?
15289           return DCI.CombineTo(N, Cond, SDValue());
15290         return Cond;
15291       }
15292
15293       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15294       // for any integer data type, including i8/i16.
15295       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15296         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15297                            DAG.getConstant(CC, MVT::i8), Cond);
15298
15299         // Zero extend the condition if needed.
15300         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15301                            FalseC->getValueType(0), Cond);
15302         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15303                            SDValue(FalseC, 0));
15304
15305         if (N->getNumValues() == 2)  // Dead flag value?
15306           return DCI.CombineTo(N, Cond, SDValue());
15307         return Cond;
15308       }
15309
15310       // Optimize cases that will turn into an LEA instruction.  This requires
15311       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15312       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15313         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15314         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15315
15316         bool isFastMultiplier = false;
15317         if (Diff < 10) {
15318           switch ((unsigned char)Diff) {
15319           default: break;
15320           case 1:  // result = add base, cond
15321           case 2:  // result = lea base(    , cond*2)
15322           case 3:  // result = lea base(cond, cond*2)
15323           case 4:  // result = lea base(    , cond*4)
15324           case 5:  // result = lea base(cond, cond*4)
15325           case 8:  // result = lea base(    , cond*8)
15326           case 9:  // result = lea base(cond, cond*8)
15327             isFastMultiplier = true;
15328             break;
15329           }
15330         }
15331
15332         if (isFastMultiplier) {
15333           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15334           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15335                              DAG.getConstant(CC, MVT::i8), Cond);
15336           // Zero extend the condition if needed.
15337           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15338                              Cond);
15339           // Scale the condition by the difference.
15340           if (Diff != 1)
15341             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15342                                DAG.getConstant(Diff, Cond.getValueType()));
15343
15344           // Add the base if non-zero.
15345           if (FalseC->getAPIntValue() != 0)
15346             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15347                                SDValue(FalseC, 0));
15348           if (N->getNumValues() == 2)  // Dead flag value?
15349             return DCI.CombineTo(N, Cond, SDValue());
15350           return Cond;
15351         }
15352       }
15353     }
15354   }
15355
15356   // Handle these cases:
15357   //   (select (x != c), e, c) -> select (x != c), e, x),
15358   //   (select (x == c), c, e) -> select (x == c), x, e)
15359   // where the c is an integer constant, and the "select" is the combination
15360   // of CMOV and CMP.
15361   //
15362   // The rationale for this change is that the conditional-move from a constant
15363   // needs two instructions, however, conditional-move from a register needs
15364   // only one instruction.
15365   //
15366   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15367   //  some instruction-combining opportunities. This opt needs to be
15368   //  postponed as late as possible.
15369   //
15370   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15371     // the DCI.xxxx conditions are provided to postpone the optimization as
15372     // late as possible.
15373
15374     ConstantSDNode *CmpAgainst = 0;
15375     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15376         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15377         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15378
15379       if (CC == X86::COND_NE &&
15380           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15381         CC = X86::GetOppositeBranchCondition(CC);
15382         std::swap(TrueOp, FalseOp);
15383       }
15384
15385       if (CC == X86::COND_E &&
15386           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15387         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15388                           DAG.getConstant(CC, MVT::i8), Cond };
15389         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15390                            array_lengthof(Ops));
15391       }
15392     }
15393   }
15394
15395   return SDValue();
15396 }
15397
15398 /// PerformMulCombine - Optimize a single multiply with constant into two
15399 /// in order to implement it with two cheaper instructions, e.g.
15400 /// LEA + SHL, LEA + LEA.
15401 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15402                                  TargetLowering::DAGCombinerInfo &DCI) {
15403   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15404     return SDValue();
15405
15406   EVT VT = N->getValueType(0);
15407   if (VT != MVT::i64)
15408     return SDValue();
15409
15410   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15411   if (!C)
15412     return SDValue();
15413   uint64_t MulAmt = C->getZExtValue();
15414   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15415     return SDValue();
15416
15417   uint64_t MulAmt1 = 0;
15418   uint64_t MulAmt2 = 0;
15419   if ((MulAmt % 9) == 0) {
15420     MulAmt1 = 9;
15421     MulAmt2 = MulAmt / 9;
15422   } else if ((MulAmt % 5) == 0) {
15423     MulAmt1 = 5;
15424     MulAmt2 = MulAmt / 5;
15425   } else if ((MulAmt % 3) == 0) {
15426     MulAmt1 = 3;
15427     MulAmt2 = MulAmt / 3;
15428   }
15429   if (MulAmt2 &&
15430       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15431     DebugLoc DL = N->getDebugLoc();
15432
15433     if (isPowerOf2_64(MulAmt2) &&
15434         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15435       // If second multiplifer is pow2, issue it first. We want the multiply by
15436       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15437       // is an add.
15438       std::swap(MulAmt1, MulAmt2);
15439
15440     SDValue NewMul;
15441     if (isPowerOf2_64(MulAmt1))
15442       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15443                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15444     else
15445       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15446                            DAG.getConstant(MulAmt1, VT));
15447
15448     if (isPowerOf2_64(MulAmt2))
15449       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15450                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15451     else
15452       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15453                            DAG.getConstant(MulAmt2, VT));
15454
15455     // Do not add new nodes to DAG combiner worklist.
15456     DCI.CombineTo(N, NewMul, false);
15457   }
15458   return SDValue();
15459 }
15460
15461 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15462   SDValue N0 = N->getOperand(0);
15463   SDValue N1 = N->getOperand(1);
15464   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15465   EVT VT = N0.getValueType();
15466
15467   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15468   // since the result of setcc_c is all zero's or all ones.
15469   if (VT.isInteger() && !VT.isVector() &&
15470       N1C && N0.getOpcode() == ISD::AND &&
15471       N0.getOperand(1).getOpcode() == ISD::Constant) {
15472     SDValue N00 = N0.getOperand(0);
15473     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15474         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15475           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15476          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15477       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15478       APInt ShAmt = N1C->getAPIntValue();
15479       Mask = Mask.shl(ShAmt);
15480       if (Mask != 0)
15481         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15482                            N00, DAG.getConstant(Mask, VT));
15483     }
15484   }
15485
15486   // Hardware support for vector shifts is sparse which makes us scalarize the
15487   // vector operations in many cases. Also, on sandybridge ADD is faster than
15488   // shl.
15489   // (shl V, 1) -> add V,V
15490   if (isSplatVector(N1.getNode())) {
15491     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15492     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15493     // We shift all of the values by one. In many cases we do not have
15494     // hardware support for this operation. This is better expressed as an ADD
15495     // of two values.
15496     if (N1C && (1 == N1C->getZExtValue())) {
15497       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15498     }
15499   }
15500
15501   return SDValue();
15502 }
15503
15504 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15505 ///                       when possible.
15506 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15507                                    TargetLowering::DAGCombinerInfo &DCI,
15508                                    const X86Subtarget *Subtarget) {
15509   EVT VT = N->getValueType(0);
15510   if (N->getOpcode() == ISD::SHL) {
15511     SDValue V = PerformSHLCombine(N, DAG);
15512     if (V.getNode()) return V;
15513   }
15514
15515   // On X86 with SSE2 support, we can transform this to a vector shift if
15516   // all elements are shifted by the same amount.  We can't do this in legalize
15517   // because the a constant vector is typically transformed to a constant pool
15518   // so we have no knowledge of the shift amount.
15519   if (!Subtarget->hasSSE2())
15520     return SDValue();
15521
15522   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15523       (!Subtarget->hasInt256() ||
15524        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15525     return SDValue();
15526
15527   SDValue ShAmtOp = N->getOperand(1);
15528   EVT EltVT = VT.getVectorElementType();
15529   DebugLoc DL = N->getDebugLoc();
15530   SDValue BaseShAmt = SDValue();
15531   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15532     unsigned NumElts = VT.getVectorNumElements();
15533     unsigned i = 0;
15534     for (; i != NumElts; ++i) {
15535       SDValue Arg = ShAmtOp.getOperand(i);
15536       if (Arg.getOpcode() == ISD::UNDEF) continue;
15537       BaseShAmt = Arg;
15538       break;
15539     }
15540     // Handle the case where the build_vector is all undef
15541     // FIXME: Should DAG allow this?
15542     if (i == NumElts)
15543       return SDValue();
15544
15545     for (; i != NumElts; ++i) {
15546       SDValue Arg = ShAmtOp.getOperand(i);
15547       if (Arg.getOpcode() == ISD::UNDEF) continue;
15548       if (Arg != BaseShAmt) {
15549         return SDValue();
15550       }
15551     }
15552   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15553              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15554     SDValue InVec = ShAmtOp.getOperand(0);
15555     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15556       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15557       unsigned i = 0;
15558       for (; i != NumElts; ++i) {
15559         SDValue Arg = InVec.getOperand(i);
15560         if (Arg.getOpcode() == ISD::UNDEF) continue;
15561         BaseShAmt = Arg;
15562         break;
15563       }
15564     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15565        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15566          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15567          if (C->getZExtValue() == SplatIdx)
15568            BaseShAmt = InVec.getOperand(1);
15569        }
15570     }
15571     if (BaseShAmt.getNode() == 0) {
15572       // Don't create instructions with illegal types after legalize
15573       // types has run.
15574       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15575           !DCI.isBeforeLegalize())
15576         return SDValue();
15577
15578       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15579                               DAG.getIntPtrConstant(0));
15580     }
15581   } else
15582     return SDValue();
15583
15584   // The shift amount is an i32.
15585   if (EltVT.bitsGT(MVT::i32))
15586     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15587   else if (EltVT.bitsLT(MVT::i32))
15588     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15589
15590   // The shift amount is identical so we can do a vector shift.
15591   SDValue  ValOp = N->getOperand(0);
15592   switch (N->getOpcode()) {
15593   default:
15594     llvm_unreachable("Unknown shift opcode!");
15595   case ISD::SHL:
15596     switch (VT.getSimpleVT().SimpleTy) {
15597     default: return SDValue();
15598     case MVT::v2i64:
15599     case MVT::v4i32:
15600     case MVT::v8i16:
15601     case MVT::v4i64:
15602     case MVT::v8i32:
15603     case MVT::v16i16:
15604       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15605     }
15606   case ISD::SRA:
15607     switch (VT.getSimpleVT().SimpleTy) {
15608     default: return SDValue();
15609     case MVT::v4i32:
15610     case MVT::v8i16:
15611     case MVT::v8i32:
15612     case MVT::v16i16:
15613       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15614     }
15615   case ISD::SRL:
15616     switch (VT.getSimpleVT().SimpleTy) {
15617     default: return SDValue();
15618     case MVT::v2i64:
15619     case MVT::v4i32:
15620     case MVT::v8i16:
15621     case MVT::v4i64:
15622     case MVT::v8i32:
15623     case MVT::v16i16:
15624       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15625     }
15626   }
15627 }
15628
15629 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15630 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15631 // and friends.  Likewise for OR -> CMPNEQSS.
15632 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15633                             TargetLowering::DAGCombinerInfo &DCI,
15634                             const X86Subtarget *Subtarget) {
15635   unsigned opcode;
15636
15637   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15638   // we're requiring SSE2 for both.
15639   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15640     SDValue N0 = N->getOperand(0);
15641     SDValue N1 = N->getOperand(1);
15642     SDValue CMP0 = N0->getOperand(1);
15643     SDValue CMP1 = N1->getOperand(1);
15644     DebugLoc DL = N->getDebugLoc();
15645
15646     // The SETCCs should both refer to the same CMP.
15647     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15648       return SDValue();
15649
15650     SDValue CMP00 = CMP0->getOperand(0);
15651     SDValue CMP01 = CMP0->getOperand(1);
15652     EVT     VT    = CMP00.getValueType();
15653
15654     if (VT == MVT::f32 || VT == MVT::f64) {
15655       bool ExpectingFlags = false;
15656       // Check for any users that want flags:
15657       for (SDNode::use_iterator UI = N->use_begin(),
15658              UE = N->use_end();
15659            !ExpectingFlags && UI != UE; ++UI)
15660         switch (UI->getOpcode()) {
15661         default:
15662         case ISD::BR_CC:
15663         case ISD::BRCOND:
15664         case ISD::SELECT:
15665           ExpectingFlags = true;
15666           break;
15667         case ISD::CopyToReg:
15668         case ISD::SIGN_EXTEND:
15669         case ISD::ZERO_EXTEND:
15670         case ISD::ANY_EXTEND:
15671           break;
15672         }
15673
15674       if (!ExpectingFlags) {
15675         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15676         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15677
15678         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15679           X86::CondCode tmp = cc0;
15680           cc0 = cc1;
15681           cc1 = tmp;
15682         }
15683
15684         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15685             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15686           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15687           X86ISD::NodeType NTOperator = is64BitFP ?
15688             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15689           // FIXME: need symbolic constants for these magic numbers.
15690           // See X86ATTInstPrinter.cpp:printSSECC().
15691           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15692           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15693                                               DAG.getConstant(x86cc, MVT::i8));
15694           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15695                                               OnesOrZeroesF);
15696           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15697                                       DAG.getConstant(1, MVT::i32));
15698           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15699           return OneBitOfTruth;
15700         }
15701       }
15702     }
15703   }
15704   return SDValue();
15705 }
15706
15707 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15708 /// so it can be folded inside ANDNP.
15709 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15710   EVT VT = N->getValueType(0);
15711
15712   // Match direct AllOnes for 128 and 256-bit vectors
15713   if (ISD::isBuildVectorAllOnes(N))
15714     return true;
15715
15716   // Look through a bit convert.
15717   if (N->getOpcode() == ISD::BITCAST)
15718     N = N->getOperand(0).getNode();
15719
15720   // Sometimes the operand may come from a insert_subvector building a 256-bit
15721   // allones vector
15722   if (VT.is256BitVector() &&
15723       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15724     SDValue V1 = N->getOperand(0);
15725     SDValue V2 = N->getOperand(1);
15726
15727     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15728         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15729         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15730         ISD::isBuildVectorAllOnes(V2.getNode()))
15731       return true;
15732   }
15733
15734   return false;
15735 }
15736
15737 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15738                                  TargetLowering::DAGCombinerInfo &DCI,
15739                                  const X86Subtarget *Subtarget) {
15740   if (DCI.isBeforeLegalizeOps())
15741     return SDValue();
15742
15743   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15744   if (R.getNode())
15745     return R;
15746
15747   EVT VT = N->getValueType(0);
15748
15749   // Create BLSI, and BLSR instructions
15750   // BLSI is X & (-X)
15751   // BLSR is X & (X-1)
15752   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15753     SDValue N0 = N->getOperand(0);
15754     SDValue N1 = N->getOperand(1);
15755     DebugLoc DL = N->getDebugLoc();
15756
15757     // Check LHS for neg
15758     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15759         isZero(N0.getOperand(0)))
15760       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15761
15762     // Check RHS for neg
15763     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15764         isZero(N1.getOperand(0)))
15765       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15766
15767     // Check LHS for X-1
15768     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15769         isAllOnes(N0.getOperand(1)))
15770       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15771
15772     // Check RHS for X-1
15773     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15774         isAllOnes(N1.getOperand(1)))
15775       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15776
15777     return SDValue();
15778   }
15779
15780   // Want to form ANDNP nodes:
15781   // 1) In the hopes of then easily combining them with OR and AND nodes
15782   //    to form PBLEND/PSIGN.
15783   // 2) To match ANDN packed intrinsics
15784   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15785     return SDValue();
15786
15787   SDValue N0 = N->getOperand(0);
15788   SDValue N1 = N->getOperand(1);
15789   DebugLoc DL = N->getDebugLoc();
15790
15791   // Check LHS for vnot
15792   if (N0.getOpcode() == ISD::XOR &&
15793       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15794       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15795     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15796
15797   // Check RHS for vnot
15798   if (N1.getOpcode() == ISD::XOR &&
15799       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15800       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15801     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15802
15803   return SDValue();
15804 }
15805
15806 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15807                                 TargetLowering::DAGCombinerInfo &DCI,
15808                                 const X86Subtarget *Subtarget) {
15809   if (DCI.isBeforeLegalizeOps())
15810     return SDValue();
15811
15812   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15813   if (R.getNode())
15814     return R;
15815
15816   EVT VT = N->getValueType(0);
15817
15818   SDValue N0 = N->getOperand(0);
15819   SDValue N1 = N->getOperand(1);
15820
15821   // look for psign/blend
15822   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15823     if (!Subtarget->hasSSSE3() ||
15824         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
15825       return SDValue();
15826
15827     // Canonicalize pandn to RHS
15828     if (N0.getOpcode() == X86ISD::ANDNP)
15829       std::swap(N0, N1);
15830     // or (and (m, y), (pandn m, x))
15831     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15832       SDValue Mask = N1.getOperand(0);
15833       SDValue X    = N1.getOperand(1);
15834       SDValue Y;
15835       if (N0.getOperand(0) == Mask)
15836         Y = N0.getOperand(1);
15837       if (N0.getOperand(1) == Mask)
15838         Y = N0.getOperand(0);
15839
15840       // Check to see if the mask appeared in both the AND and ANDNP and
15841       if (!Y.getNode())
15842         return SDValue();
15843
15844       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15845       // Look through mask bitcast.
15846       if (Mask.getOpcode() == ISD::BITCAST)
15847         Mask = Mask.getOperand(0);
15848       if (X.getOpcode() == ISD::BITCAST)
15849         X = X.getOperand(0);
15850       if (Y.getOpcode() == ISD::BITCAST)
15851         Y = Y.getOperand(0);
15852
15853       EVT MaskVT = Mask.getValueType();
15854
15855       // Validate that the Mask operand is a vector sra node.
15856       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15857       // there is no psrai.b
15858       if (Mask.getOpcode() != X86ISD::VSRAI)
15859         return SDValue();
15860
15861       // Check that the SRA is all signbits.
15862       SDValue SraC = Mask.getOperand(1);
15863       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15864       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15865       if ((SraAmt + 1) != EltBits)
15866         return SDValue();
15867
15868       DebugLoc DL = N->getDebugLoc();
15869
15870       // We are going to replace the AND, OR, NAND with either BLEND
15871       // or PSIGN, which only look at the MSB. The VSRAI instruction
15872       // does not affect the highest bit, so we can get rid of it.
15873       Mask = Mask.getOperand(0);
15874
15875       // Now we know we at least have a plendvb with the mask val.  See if
15876       // we can form a psignb/w/d.
15877       // psign = x.type == y.type == mask.type && y = sub(0, x);
15878       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15879           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15880           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15881         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15882                "Unsupported VT for PSIGN");
15883         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
15884         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15885       }
15886       // PBLENDVB only available on SSE 4.1
15887       if (!Subtarget->hasSSE41())
15888         return SDValue();
15889
15890       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15891
15892       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15893       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15894       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15895       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15896       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15897     }
15898   }
15899
15900   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15901     return SDValue();
15902
15903   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15904   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15905     std::swap(N0, N1);
15906   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15907     return SDValue();
15908   if (!N0.hasOneUse() || !N1.hasOneUse())
15909     return SDValue();
15910
15911   SDValue ShAmt0 = N0.getOperand(1);
15912   if (ShAmt0.getValueType() != MVT::i8)
15913     return SDValue();
15914   SDValue ShAmt1 = N1.getOperand(1);
15915   if (ShAmt1.getValueType() != MVT::i8)
15916     return SDValue();
15917   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15918     ShAmt0 = ShAmt0.getOperand(0);
15919   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15920     ShAmt1 = ShAmt1.getOperand(0);
15921
15922   DebugLoc DL = N->getDebugLoc();
15923   unsigned Opc = X86ISD::SHLD;
15924   SDValue Op0 = N0.getOperand(0);
15925   SDValue Op1 = N1.getOperand(0);
15926   if (ShAmt0.getOpcode() == ISD::SUB) {
15927     Opc = X86ISD::SHRD;
15928     std::swap(Op0, Op1);
15929     std::swap(ShAmt0, ShAmt1);
15930   }
15931
15932   unsigned Bits = VT.getSizeInBits();
15933   if (ShAmt1.getOpcode() == ISD::SUB) {
15934     SDValue Sum = ShAmt1.getOperand(0);
15935     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15936       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15937       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15938         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15939       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15940         return DAG.getNode(Opc, DL, VT,
15941                            Op0, Op1,
15942                            DAG.getNode(ISD::TRUNCATE, DL,
15943                                        MVT::i8, ShAmt0));
15944     }
15945   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15946     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15947     if (ShAmt0C &&
15948         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15949       return DAG.getNode(Opc, DL, VT,
15950                          N0.getOperand(0), N1.getOperand(0),
15951                          DAG.getNode(ISD::TRUNCATE, DL,
15952                                        MVT::i8, ShAmt0));
15953   }
15954
15955   return SDValue();
15956 }
15957
15958 // Generate NEG and CMOV for integer abs.
15959 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15960   EVT VT = N->getValueType(0);
15961
15962   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15963   // 8-bit integer abs to NEG and CMOV.
15964   if (VT.isInteger() && VT.getSizeInBits() == 8)
15965     return SDValue();
15966
15967   SDValue N0 = N->getOperand(0);
15968   SDValue N1 = N->getOperand(1);
15969   DebugLoc DL = N->getDebugLoc();
15970
15971   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15972   // and change it to SUB and CMOV.
15973   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15974       N0.getOpcode() == ISD::ADD &&
15975       N0.getOperand(1) == N1 &&
15976       N1.getOpcode() == ISD::SRA &&
15977       N1.getOperand(0) == N0.getOperand(0))
15978     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15979       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15980         // Generate SUB & CMOV.
15981         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15982                                   DAG.getConstant(0, VT), N0.getOperand(0));
15983
15984         SDValue Ops[] = { N0.getOperand(0), Neg,
15985                           DAG.getConstant(X86::COND_GE, MVT::i8),
15986                           SDValue(Neg.getNode(), 1) };
15987         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15988                            Ops, array_lengthof(Ops));
15989       }
15990   return SDValue();
15991 }
15992
15993 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15994 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15995                                  TargetLowering::DAGCombinerInfo &DCI,
15996                                  const X86Subtarget *Subtarget) {
15997   if (DCI.isBeforeLegalizeOps())
15998     return SDValue();
15999
16000   if (Subtarget->hasCMov()) {
16001     SDValue RV = performIntegerAbsCombine(N, DAG);
16002     if (RV.getNode())
16003       return RV;
16004   }
16005
16006   // Try forming BMI if it is available.
16007   if (!Subtarget->hasBMI())
16008     return SDValue();
16009
16010   EVT VT = N->getValueType(0);
16011
16012   if (VT != MVT::i32 && VT != MVT::i64)
16013     return SDValue();
16014
16015   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16016
16017   // Create BLSMSK instructions by finding X ^ (X-1)
16018   SDValue N0 = N->getOperand(0);
16019   SDValue N1 = N->getOperand(1);
16020   DebugLoc DL = N->getDebugLoc();
16021
16022   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16023       isAllOnes(N0.getOperand(1)))
16024     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16025
16026   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16027       isAllOnes(N1.getOperand(1)))
16028     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16029
16030   return SDValue();
16031 }
16032
16033 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16034 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16035                                   TargetLowering::DAGCombinerInfo &DCI,
16036                                   const X86Subtarget *Subtarget) {
16037   LoadSDNode *Ld = cast<LoadSDNode>(N);
16038   EVT RegVT = Ld->getValueType(0);
16039   EVT MemVT = Ld->getMemoryVT();
16040   DebugLoc dl = Ld->getDebugLoc();
16041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16042
16043   ISD::LoadExtType Ext = Ld->getExtensionType();
16044
16045   // If this is a vector EXT Load then attempt to optimize it using a
16046   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16047   // expansion is still better than scalar code.
16048   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16049   // emit a shuffle and a arithmetic shift.
16050   // TODO: It is possible to support ZExt by zeroing the undef values
16051   // during the shuffle phase or after the shuffle.
16052   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16053       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16054     assert(MemVT != RegVT && "Cannot extend to the same type");
16055     assert(MemVT.isVector() && "Must load a vector from memory");
16056
16057     unsigned NumElems = RegVT.getVectorNumElements();
16058     unsigned RegSz = RegVT.getSizeInBits();
16059     unsigned MemSz = MemVT.getSizeInBits();
16060     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16061
16062     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16063       return SDValue();
16064
16065     // All sizes must be a power of two.
16066     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16067       return SDValue();
16068
16069     // Attempt to load the original value using scalar loads.
16070     // Find the largest scalar type that divides the total loaded size.
16071     MVT SclrLoadTy = MVT::i8;
16072     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16073          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16074       MVT Tp = (MVT::SimpleValueType)tp;
16075       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16076         SclrLoadTy = Tp;
16077       }
16078     }
16079
16080     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16081     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16082         (64 <= MemSz))
16083       SclrLoadTy = MVT::f64;
16084
16085     // Calculate the number of scalar loads that we need to perform
16086     // in order to load our vector from memory.
16087     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16088     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16089       return SDValue();
16090
16091     unsigned loadRegZize = RegSz;
16092     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16093       loadRegZize /= 2;
16094
16095     // Represent our vector as a sequence of elements which are the
16096     // largest scalar that we can load.
16097     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16098       loadRegZize/SclrLoadTy.getSizeInBits());
16099
16100     // Represent the data using the same element type that is stored in
16101     // memory. In practice, we ''widen'' MemVT.
16102     EVT WideVecVT = 
16103           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16104                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16105
16106     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16107       "Invalid vector type");
16108
16109     // We can't shuffle using an illegal type.
16110     if (!TLI.isTypeLegal(WideVecVT))
16111       return SDValue();
16112
16113     SmallVector<SDValue, 8> Chains;
16114     SDValue Ptr = Ld->getBasePtr();
16115     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16116                                         TLI.getPointerTy());
16117     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16118
16119     for (unsigned i = 0; i < NumLoads; ++i) {
16120       // Perform a single load.
16121       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16122                                        Ptr, Ld->getPointerInfo(),
16123                                        Ld->isVolatile(), Ld->isNonTemporal(),
16124                                        Ld->isInvariant(), Ld->getAlignment());
16125       Chains.push_back(ScalarLoad.getValue(1));
16126       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16127       // another round of DAGCombining.
16128       if (i == 0)
16129         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16130       else
16131         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16132                           ScalarLoad, DAG.getIntPtrConstant(i));
16133
16134       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16135     }
16136
16137     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16138                                Chains.size());
16139
16140     // Bitcast the loaded value to a vector of the original element type, in
16141     // the size of the target vector type.
16142     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16143     unsigned SizeRatio = RegSz/MemSz;
16144
16145     if (Ext == ISD::SEXTLOAD) {
16146       // If we have SSE4.1 we can directly emit a VSEXT node.
16147       if (Subtarget->hasSSE41()) {
16148         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16149         return DCI.CombineTo(N, Sext, TF, true);
16150       }
16151
16152       // Otherwise we'll shuffle the small elements in the high bits of the
16153       // larger type and perform an arithmetic shift. If the shift is not legal
16154       // it's better to scalarize.
16155       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16156         return SDValue();
16157
16158       // Redistribute the loaded elements into the different locations.
16159       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16160       for (unsigned i = 0; i != NumElems; ++i)
16161         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16162
16163       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16164                                            DAG.getUNDEF(WideVecVT),
16165                                            &ShuffleVec[0]);
16166
16167       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16168
16169       // Build the arithmetic shift.
16170       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16171                      MemVT.getVectorElementType().getSizeInBits();
16172       SmallVector<SDValue, 8> C(NumElems,
16173                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16174       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16175       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16176
16177       return DCI.CombineTo(N, Shuff, TF, true);
16178     }
16179
16180     // Redistribute the loaded elements into the different locations.
16181     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16182     for (unsigned i = 0; i != NumElems; ++i)
16183       ShuffleVec[i*SizeRatio] = i;
16184
16185     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16186                                          DAG.getUNDEF(WideVecVT),
16187                                          &ShuffleVec[0]);
16188
16189     // Bitcast to the requested type.
16190     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16191     // Replace the original load with the new sequence
16192     // and return the new chain.
16193     return DCI.CombineTo(N, Shuff, TF, true);
16194   }
16195
16196   return SDValue();
16197 }
16198
16199 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16200 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16201                                    const X86Subtarget *Subtarget) {
16202   StoreSDNode *St = cast<StoreSDNode>(N);
16203   EVT VT = St->getValue().getValueType();
16204   EVT StVT = St->getMemoryVT();
16205   DebugLoc dl = St->getDebugLoc();
16206   SDValue StoredVal = St->getOperand(1);
16207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16208
16209   // If we are saving a concatenation of two XMM registers, perform two stores.
16210   // On Sandy Bridge, 256-bit memory operations are executed by two
16211   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16212   // memory  operation.
16213   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16214       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16215       StoredVal.getNumOperands() == 2) {
16216     SDValue Value0 = StoredVal.getOperand(0);
16217     SDValue Value1 = StoredVal.getOperand(1);
16218
16219     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16220     SDValue Ptr0 = St->getBasePtr();
16221     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16222
16223     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16224                                 St->getPointerInfo(), St->isVolatile(),
16225                                 St->isNonTemporal(), St->getAlignment());
16226     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16227                                 St->getPointerInfo(), St->isVolatile(),
16228                                 St->isNonTemporal(), St->getAlignment());
16229     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16230   }
16231
16232   // Optimize trunc store (of multiple scalars) to shuffle and store.
16233   // First, pack all of the elements in one place. Next, store to memory
16234   // in fewer chunks.
16235   if (St->isTruncatingStore() && VT.isVector()) {
16236     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16237     unsigned NumElems = VT.getVectorNumElements();
16238     assert(StVT != VT && "Cannot truncate to the same type");
16239     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16240     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16241
16242     // From, To sizes and ElemCount must be pow of two
16243     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16244     // We are going to use the original vector elt for storing.
16245     // Accumulated smaller vector elements must be a multiple of the store size.
16246     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16247
16248     unsigned SizeRatio  = FromSz / ToSz;
16249
16250     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16251
16252     // Create a type on which we perform the shuffle
16253     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16254             StVT.getScalarType(), NumElems*SizeRatio);
16255
16256     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16257
16258     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16259     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16260     for (unsigned i = 0; i != NumElems; ++i)
16261       ShuffleVec[i] = i * SizeRatio;
16262
16263     // Can't shuffle using an illegal type.
16264     if (!TLI.isTypeLegal(WideVecVT))
16265       return SDValue();
16266
16267     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16268                                          DAG.getUNDEF(WideVecVT),
16269                                          &ShuffleVec[0]);
16270     // At this point all of the data is stored at the bottom of the
16271     // register. We now need to save it to mem.
16272
16273     // Find the largest store unit
16274     MVT StoreType = MVT::i8;
16275     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16276          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16277       MVT Tp = (MVT::SimpleValueType)tp;
16278       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16279         StoreType = Tp;
16280     }
16281
16282     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16283     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16284         (64 <= NumElems * ToSz))
16285       StoreType = MVT::f64;
16286
16287     // Bitcast the original vector into a vector of store-size units
16288     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16289             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16290     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16291     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16292     SmallVector<SDValue, 8> Chains;
16293     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16294                                         TLI.getPointerTy());
16295     SDValue Ptr = St->getBasePtr();
16296
16297     // Perform one or more big stores into memory.
16298     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16299       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16300                                    StoreType, ShuffWide,
16301                                    DAG.getIntPtrConstant(i));
16302       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16303                                 St->getPointerInfo(), St->isVolatile(),
16304                                 St->isNonTemporal(), St->getAlignment());
16305       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16306       Chains.push_back(Ch);
16307     }
16308
16309     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16310                                Chains.size());
16311   }
16312
16313   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16314   // the FP state in cases where an emms may be missing.
16315   // A preferable solution to the general problem is to figure out the right
16316   // places to insert EMMS.  This qualifies as a quick hack.
16317
16318   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16319   if (VT.getSizeInBits() != 64)
16320     return SDValue();
16321
16322   const Function *F = DAG.getMachineFunction().getFunction();
16323   bool NoImplicitFloatOps = F->getFnAttributes().
16324     hasAttribute(Attribute::NoImplicitFloat);
16325   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16326                      && Subtarget->hasSSE2();
16327   if ((VT.isVector() ||
16328        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16329       isa<LoadSDNode>(St->getValue()) &&
16330       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16331       St->getChain().hasOneUse() && !St->isVolatile()) {
16332     SDNode* LdVal = St->getValue().getNode();
16333     LoadSDNode *Ld = 0;
16334     int TokenFactorIndex = -1;
16335     SmallVector<SDValue, 8> Ops;
16336     SDNode* ChainVal = St->getChain().getNode();
16337     // Must be a store of a load.  We currently handle two cases:  the load
16338     // is a direct child, and it's under an intervening TokenFactor.  It is
16339     // possible to dig deeper under nested TokenFactors.
16340     if (ChainVal == LdVal)
16341       Ld = cast<LoadSDNode>(St->getChain());
16342     else if (St->getValue().hasOneUse() &&
16343              ChainVal->getOpcode() == ISD::TokenFactor) {
16344       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16345         if (ChainVal->getOperand(i).getNode() == LdVal) {
16346           TokenFactorIndex = i;
16347           Ld = cast<LoadSDNode>(St->getValue());
16348         } else
16349           Ops.push_back(ChainVal->getOperand(i));
16350       }
16351     }
16352
16353     if (!Ld || !ISD::isNormalLoad(Ld))
16354       return SDValue();
16355
16356     // If this is not the MMX case, i.e. we are just turning i64 load/store
16357     // into f64 load/store, avoid the transformation if there are multiple
16358     // uses of the loaded value.
16359     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16360       return SDValue();
16361
16362     DebugLoc LdDL = Ld->getDebugLoc();
16363     DebugLoc StDL = N->getDebugLoc();
16364     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16365     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16366     // pair instead.
16367     if (Subtarget->is64Bit() || F64IsLegal) {
16368       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16369       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16370                                   Ld->getPointerInfo(), Ld->isVolatile(),
16371                                   Ld->isNonTemporal(), Ld->isInvariant(),
16372                                   Ld->getAlignment());
16373       SDValue NewChain = NewLd.getValue(1);
16374       if (TokenFactorIndex != -1) {
16375         Ops.push_back(NewChain);
16376         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16377                                Ops.size());
16378       }
16379       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16380                           St->getPointerInfo(),
16381                           St->isVolatile(), St->isNonTemporal(),
16382                           St->getAlignment());
16383     }
16384
16385     // Otherwise, lower to two pairs of 32-bit loads / stores.
16386     SDValue LoAddr = Ld->getBasePtr();
16387     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16388                                  DAG.getConstant(4, MVT::i32));
16389
16390     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16391                                Ld->getPointerInfo(),
16392                                Ld->isVolatile(), Ld->isNonTemporal(),
16393                                Ld->isInvariant(), Ld->getAlignment());
16394     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16395                                Ld->getPointerInfo().getWithOffset(4),
16396                                Ld->isVolatile(), Ld->isNonTemporal(),
16397                                Ld->isInvariant(),
16398                                MinAlign(Ld->getAlignment(), 4));
16399
16400     SDValue NewChain = LoLd.getValue(1);
16401     if (TokenFactorIndex != -1) {
16402       Ops.push_back(LoLd);
16403       Ops.push_back(HiLd);
16404       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16405                              Ops.size());
16406     }
16407
16408     LoAddr = St->getBasePtr();
16409     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16410                          DAG.getConstant(4, MVT::i32));
16411
16412     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16413                                 St->getPointerInfo(),
16414                                 St->isVolatile(), St->isNonTemporal(),
16415                                 St->getAlignment());
16416     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16417                                 St->getPointerInfo().getWithOffset(4),
16418                                 St->isVolatile(),
16419                                 St->isNonTemporal(),
16420                                 MinAlign(St->getAlignment(), 4));
16421     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16422   }
16423   return SDValue();
16424 }
16425
16426 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16427 /// and return the operands for the horizontal operation in LHS and RHS.  A
16428 /// horizontal operation performs the binary operation on successive elements
16429 /// of its first operand, then on successive elements of its second operand,
16430 /// returning the resulting values in a vector.  For example, if
16431 ///   A = < float a0, float a1, float a2, float a3 >
16432 /// and
16433 ///   B = < float b0, float b1, float b2, float b3 >
16434 /// then the result of doing a horizontal operation on A and B is
16435 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16436 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16437 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16438 /// set to A, RHS to B, and the routine returns 'true'.
16439 /// Note that the binary operation should have the property that if one of the
16440 /// operands is UNDEF then the result is UNDEF.
16441 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16442   // Look for the following pattern: if
16443   //   A = < float a0, float a1, float a2, float a3 >
16444   //   B = < float b0, float b1, float b2, float b3 >
16445   // and
16446   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16447   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16448   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16449   // which is A horizontal-op B.
16450
16451   // At least one of the operands should be a vector shuffle.
16452   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16453       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16454     return false;
16455
16456   EVT VT = LHS.getValueType();
16457
16458   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16459          "Unsupported vector type for horizontal add/sub");
16460
16461   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16462   // operate independently on 128-bit lanes.
16463   unsigned NumElts = VT.getVectorNumElements();
16464   unsigned NumLanes = VT.getSizeInBits()/128;
16465   unsigned NumLaneElts = NumElts / NumLanes;
16466   assert((NumLaneElts % 2 == 0) &&
16467          "Vector type should have an even number of elements in each lane");
16468   unsigned HalfLaneElts = NumLaneElts/2;
16469
16470   // View LHS in the form
16471   //   LHS = VECTOR_SHUFFLE A, B, LMask
16472   // If LHS is not a shuffle then pretend it is the shuffle
16473   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16474   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16475   // type VT.
16476   SDValue A, B;
16477   SmallVector<int, 16> LMask(NumElts);
16478   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16479     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16480       A = LHS.getOperand(0);
16481     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16482       B = LHS.getOperand(1);
16483     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16484     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16485   } else {
16486     if (LHS.getOpcode() != ISD::UNDEF)
16487       A = LHS;
16488     for (unsigned i = 0; i != NumElts; ++i)
16489       LMask[i] = i;
16490   }
16491
16492   // Likewise, view RHS in the form
16493   //   RHS = VECTOR_SHUFFLE C, D, RMask
16494   SDValue C, D;
16495   SmallVector<int, 16> RMask(NumElts);
16496   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16497     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16498       C = RHS.getOperand(0);
16499     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16500       D = RHS.getOperand(1);
16501     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16502     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16503   } else {
16504     if (RHS.getOpcode() != ISD::UNDEF)
16505       C = RHS;
16506     for (unsigned i = 0; i != NumElts; ++i)
16507       RMask[i] = i;
16508   }
16509
16510   // Check that the shuffles are both shuffling the same vectors.
16511   if (!(A == C && B == D) && !(A == D && B == C))
16512     return false;
16513
16514   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16515   if (!A.getNode() && !B.getNode())
16516     return false;
16517
16518   // If A and B occur in reverse order in RHS, then "swap" them (which means
16519   // rewriting the mask).
16520   if (A != C)
16521     CommuteVectorShuffleMask(RMask, NumElts);
16522
16523   // At this point LHS and RHS are equivalent to
16524   //   LHS = VECTOR_SHUFFLE A, B, LMask
16525   //   RHS = VECTOR_SHUFFLE A, B, RMask
16526   // Check that the masks correspond to performing a horizontal operation.
16527   for (unsigned i = 0; i != NumElts; ++i) {
16528     int LIdx = LMask[i], RIdx = RMask[i];
16529
16530     // Ignore any UNDEF components.
16531     if (LIdx < 0 || RIdx < 0 ||
16532         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16533         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16534       continue;
16535
16536     // Check that successive elements are being operated on.  If not, this is
16537     // not a horizontal operation.
16538     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16539     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16540     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16541     if (!(LIdx == Index && RIdx == Index + 1) &&
16542         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16543       return false;
16544   }
16545
16546   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16547   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16548   return true;
16549 }
16550
16551 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16552 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16553                                   const X86Subtarget *Subtarget) {
16554   EVT VT = N->getValueType(0);
16555   SDValue LHS = N->getOperand(0);
16556   SDValue RHS = N->getOperand(1);
16557
16558   // Try to synthesize horizontal adds from adds of shuffles.
16559   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16560        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16561       isHorizontalBinOp(LHS, RHS, true))
16562     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16563   return SDValue();
16564 }
16565
16566 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16567 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16568                                   const X86Subtarget *Subtarget) {
16569   EVT VT = N->getValueType(0);
16570   SDValue LHS = N->getOperand(0);
16571   SDValue RHS = N->getOperand(1);
16572
16573   // Try to synthesize horizontal subs from subs of shuffles.
16574   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16575        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16576       isHorizontalBinOp(LHS, RHS, false))
16577     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16578   return SDValue();
16579 }
16580
16581 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16582 /// X86ISD::FXOR nodes.
16583 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16584   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16585   // F[X]OR(0.0, x) -> x
16586   // F[X]OR(x, 0.0) -> x
16587   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16588     if (C->getValueAPF().isPosZero())
16589       return N->getOperand(1);
16590   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16591     if (C->getValueAPF().isPosZero())
16592       return N->getOperand(0);
16593   return SDValue();
16594 }
16595
16596 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16597 /// X86ISD::FMAX nodes.
16598 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16599   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16600
16601   // Only perform optimizations if UnsafeMath is used.
16602   if (!DAG.getTarget().Options.UnsafeFPMath)
16603     return SDValue();
16604
16605   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16606   // into FMINC and FMAXC, which are Commutative operations.
16607   unsigned NewOp = 0;
16608   switch (N->getOpcode()) {
16609     default: llvm_unreachable("unknown opcode");
16610     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16611     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16612   }
16613
16614   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16615                      N->getOperand(0), N->getOperand(1));
16616 }
16617
16618 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16619 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16620   // FAND(0.0, x) -> 0.0
16621   // FAND(x, 0.0) -> 0.0
16622   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16623     if (C->getValueAPF().isPosZero())
16624       return N->getOperand(0);
16625   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16626     if (C->getValueAPF().isPosZero())
16627       return N->getOperand(1);
16628   return SDValue();
16629 }
16630
16631 static SDValue PerformBTCombine(SDNode *N,
16632                                 SelectionDAG &DAG,
16633                                 TargetLowering::DAGCombinerInfo &DCI) {
16634   // BT ignores high bits in the bit index operand.
16635   SDValue Op1 = N->getOperand(1);
16636   if (Op1.hasOneUse()) {
16637     unsigned BitWidth = Op1.getValueSizeInBits();
16638     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16639     APInt KnownZero, KnownOne;
16640     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16641                                           !DCI.isBeforeLegalizeOps());
16642     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16643     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16644         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16645       DCI.CommitTargetLoweringOpt(TLO);
16646   }
16647   return SDValue();
16648 }
16649
16650 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16651   SDValue Op = N->getOperand(0);
16652   if (Op.getOpcode() == ISD::BITCAST)
16653     Op = Op.getOperand(0);
16654   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16655   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16656       VT.getVectorElementType().getSizeInBits() ==
16657       OpVT.getVectorElementType().getSizeInBits()) {
16658     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16659   }
16660   return SDValue();
16661 }
16662
16663 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16664                                   TargetLowering::DAGCombinerInfo &DCI,
16665                                   const X86Subtarget *Subtarget) {
16666   if (!DCI.isBeforeLegalizeOps())
16667     return SDValue();
16668
16669   if (!Subtarget->hasFp256())
16670     return SDValue();
16671
16672   EVT VT = N->getValueType(0);
16673   SDValue Op = N->getOperand(0);
16674   EVT OpVT = Op.getValueType();
16675   DebugLoc dl = N->getDebugLoc();
16676
16677   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16678       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16679
16680     if (Subtarget->hasInt256())
16681       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16682
16683     // Optimize vectors in AVX mode
16684     // Sign extend  v8i16 to v8i32 and
16685     //              v4i32 to v4i64
16686     //
16687     // Divide input vector into two parts
16688     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16689     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16690     // concat the vectors to original VT
16691
16692     unsigned NumElems = OpVT.getVectorNumElements();
16693     SDValue Undef = DAG.getUNDEF(OpVT);
16694
16695     SmallVector<int,8> ShufMask1(NumElems, -1);
16696     for (unsigned i = 0; i != NumElems/2; ++i)
16697       ShufMask1[i] = i;
16698
16699     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16700
16701     SmallVector<int,8> ShufMask2(NumElems, -1);
16702     for (unsigned i = 0; i != NumElems/2; ++i)
16703       ShufMask2[i] = i + NumElems/2;
16704
16705     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16706
16707     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16708                                   VT.getVectorNumElements()/2);
16709
16710     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16711     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16712
16713     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16714   }
16715   return SDValue();
16716 }
16717
16718 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16719                                  const X86Subtarget* Subtarget) {
16720   DebugLoc dl = N->getDebugLoc();
16721   EVT VT = N->getValueType(0);
16722
16723   // Let legalize expand this if it isn't a legal type yet.
16724   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16725     return SDValue();
16726
16727   EVT ScalarVT = VT.getScalarType();
16728   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16729       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16730     return SDValue();
16731
16732   SDValue A = N->getOperand(0);
16733   SDValue B = N->getOperand(1);
16734   SDValue C = N->getOperand(2);
16735
16736   bool NegA = (A.getOpcode() == ISD::FNEG);
16737   bool NegB = (B.getOpcode() == ISD::FNEG);
16738   bool NegC = (C.getOpcode() == ISD::FNEG);
16739
16740   // Negative multiplication when NegA xor NegB
16741   bool NegMul = (NegA != NegB);
16742   if (NegA)
16743     A = A.getOperand(0);
16744   if (NegB)
16745     B = B.getOperand(0);
16746   if (NegC)
16747     C = C.getOperand(0);
16748
16749   unsigned Opcode;
16750   if (!NegMul)
16751     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16752   else
16753     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16754
16755   return DAG.getNode(Opcode, dl, VT, A, B, C);
16756 }
16757
16758 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16759                                   TargetLowering::DAGCombinerInfo &DCI,
16760                                   const X86Subtarget *Subtarget) {
16761   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16762   //           (and (i32 x86isd::setcc_carry), 1)
16763   // This eliminates the zext. This transformation is necessary because
16764   // ISD::SETCC is always legalized to i8.
16765   DebugLoc dl = N->getDebugLoc();
16766   SDValue N0 = N->getOperand(0);
16767   EVT VT = N->getValueType(0);
16768   EVT OpVT = N0.getValueType();
16769
16770   if (N0.getOpcode() == ISD::AND &&
16771       N0.hasOneUse() &&
16772       N0.getOperand(0).hasOneUse()) {
16773     SDValue N00 = N0.getOperand(0);
16774     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16775       return SDValue();
16776     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16777     if (!C || C->getZExtValue() != 1)
16778       return SDValue();
16779     return DAG.getNode(ISD::AND, dl, VT,
16780                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16781                                    N00.getOperand(0), N00.getOperand(1)),
16782                        DAG.getConstant(1, VT));
16783   }
16784
16785   // Optimize vectors in AVX mode:
16786   //
16787   //   v8i16 -> v8i32
16788   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16789   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16790   //   Concat upper and lower parts.
16791   //
16792   //   v4i32 -> v4i64
16793   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16794   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16795   //   Concat upper and lower parts.
16796   //
16797   if (!DCI.isBeforeLegalizeOps())
16798     return SDValue();
16799
16800   if (!Subtarget->hasFp256())
16801     return SDValue();
16802
16803   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16804       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16805
16806     if (Subtarget->hasInt256())
16807       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16808
16809     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16810     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16811     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16812
16813     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16814                                VT.getVectorNumElements()/2);
16815
16816     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16817     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16818
16819     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16820   }
16821
16822   return SDValue();
16823 }
16824
16825 // Optimize x == -y --> x+y == 0
16826 //          x != -y --> x+y != 0
16827 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16828   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16829   SDValue LHS = N->getOperand(0);
16830   SDValue RHS = N->getOperand(1);
16831
16832   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16834       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16835         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16836                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16837         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16838                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16839       }
16840   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16841     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16842       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16843         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16844                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16845         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16846                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16847       }
16848   return SDValue();
16849 }
16850
16851 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
16852 // as "sbb reg,reg", since it can be extended without zext and produces 
16853 // an all-ones bit which is more useful than 0/1 in some cases.
16854 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16855   return DAG.getNode(ISD::AND, DL, MVT::i8,
16856                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16857                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16858                      DAG.getConstant(1, MVT::i8));
16859 }
16860
16861 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16862 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16863                                    TargetLowering::DAGCombinerInfo &DCI,
16864                                    const X86Subtarget *Subtarget) {
16865   DebugLoc DL = N->getDebugLoc();
16866   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16867   SDValue EFLAGS = N->getOperand(1);
16868
16869   if (CC == X86::COND_A) {
16870     // Try to convert COND_A into COND_B in an attempt to facilitate 
16871     // materializing "setb reg".
16872     //
16873     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16874     // cannot take an immediate as its first operand.
16875     //
16876     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
16877         EFLAGS.getValueType().isInteger() &&
16878         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
16879       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
16880                                    EFLAGS.getNode()->getVTList(),
16881                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
16882       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
16883       return MaterializeSETB(DL, NewEFLAGS, DAG);
16884     }
16885   }
16886
16887   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16888   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16889   // cases.
16890   if (CC == X86::COND_B)
16891     return MaterializeSETB(DL, EFLAGS, DAG);
16892
16893   SDValue Flags;
16894
16895   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16896   if (Flags.getNode()) {
16897     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16898     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16899   }
16900
16901   return SDValue();
16902 }
16903
16904 // Optimize branch condition evaluation.
16905 //
16906 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16907                                     TargetLowering::DAGCombinerInfo &DCI,
16908                                     const X86Subtarget *Subtarget) {
16909   DebugLoc DL = N->getDebugLoc();
16910   SDValue Chain = N->getOperand(0);
16911   SDValue Dest = N->getOperand(1);
16912   SDValue EFLAGS = N->getOperand(3);
16913   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16914
16915   SDValue Flags;
16916
16917   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16918   if (Flags.getNode()) {
16919     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16920     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16921                        Flags);
16922   }
16923
16924   return SDValue();
16925 }
16926
16927 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16928                                         const X86TargetLowering *XTLI) {
16929   SDValue Op0 = N->getOperand(0);
16930   EVT InVT = Op0->getValueType(0);
16931
16932   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16933   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16934     DebugLoc dl = N->getDebugLoc();
16935     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16936     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16937     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16938   }
16939
16940   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16941   // a 32-bit target where SSE doesn't support i64->FP operations.
16942   if (Op0.getOpcode() == ISD::LOAD) {
16943     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16944     EVT VT = Ld->getValueType(0);
16945     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16946         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16947         !XTLI->getSubtarget()->is64Bit() &&
16948         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16949       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16950                                           Ld->getChain(), Op0, DAG);
16951       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16952       return FILDChain;
16953     }
16954   }
16955   return SDValue();
16956 }
16957
16958 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16959 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16960                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16961   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16962   // the result is either zero or one (depending on the input carry bit).
16963   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16964   if (X86::isZeroNode(N->getOperand(0)) &&
16965       X86::isZeroNode(N->getOperand(1)) &&
16966       // We don't have a good way to replace an EFLAGS use, so only do this when
16967       // dead right now.
16968       SDValue(N, 1).use_empty()) {
16969     DebugLoc DL = N->getDebugLoc();
16970     EVT VT = N->getValueType(0);
16971     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16972     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16973                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16974                                            DAG.getConstant(X86::COND_B,MVT::i8),
16975                                            N->getOperand(2)),
16976                                DAG.getConstant(1, VT));
16977     return DCI.CombineTo(N, Res1, CarryOut);
16978   }
16979
16980   return SDValue();
16981 }
16982
16983 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16984 //      (add Y, (setne X, 0)) -> sbb -1, Y
16985 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16986 //      (sub (setne X, 0), Y) -> adc -1, Y
16987 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16988   DebugLoc DL = N->getDebugLoc();
16989
16990   // Look through ZExts.
16991   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16992   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16993     return SDValue();
16994
16995   SDValue SetCC = Ext.getOperand(0);
16996   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16997     return SDValue();
16998
16999   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17000   if (CC != X86::COND_E && CC != X86::COND_NE)
17001     return SDValue();
17002
17003   SDValue Cmp = SetCC.getOperand(1);
17004   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17005       !X86::isZeroNode(Cmp.getOperand(1)) ||
17006       !Cmp.getOperand(0).getValueType().isInteger())
17007     return SDValue();
17008
17009   SDValue CmpOp0 = Cmp.getOperand(0);
17010   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17011                                DAG.getConstant(1, CmpOp0.getValueType()));
17012
17013   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17014   if (CC == X86::COND_NE)
17015     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17016                        DL, OtherVal.getValueType(), OtherVal,
17017                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17018   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17019                      DL, OtherVal.getValueType(), OtherVal,
17020                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17021 }
17022
17023 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17024 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17025                                  const X86Subtarget *Subtarget) {
17026   EVT VT = N->getValueType(0);
17027   SDValue Op0 = N->getOperand(0);
17028   SDValue Op1 = N->getOperand(1);
17029
17030   // Try to synthesize horizontal adds from adds of shuffles.
17031   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17032        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17033       isHorizontalBinOp(Op0, Op1, true))
17034     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17035
17036   return OptimizeConditionalInDecrement(N, DAG);
17037 }
17038
17039 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17040                                  const X86Subtarget *Subtarget) {
17041   SDValue Op0 = N->getOperand(0);
17042   SDValue Op1 = N->getOperand(1);
17043
17044   // X86 can't encode an immediate LHS of a sub. See if we can push the
17045   // negation into a preceding instruction.
17046   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17047     // If the RHS of the sub is a XOR with one use and a constant, invert the
17048     // immediate. Then add one to the LHS of the sub so we can turn
17049     // X-Y -> X+~Y+1, saving one register.
17050     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17051         isa<ConstantSDNode>(Op1.getOperand(1))) {
17052       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17053       EVT VT = Op0.getValueType();
17054       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17055                                    Op1.getOperand(0),
17056                                    DAG.getConstant(~XorC, VT));
17057       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17058                          DAG.getConstant(C->getAPIntValue()+1, VT));
17059     }
17060   }
17061
17062   // Try to synthesize horizontal adds from adds of shuffles.
17063   EVT VT = N->getValueType(0);
17064   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17065        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17066       isHorizontalBinOp(Op0, Op1, true))
17067     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17068
17069   return OptimizeConditionalInDecrement(N, DAG);
17070 }
17071
17072 /// performVZEXTCombine - Performs build vector combines
17073 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17074                                         TargetLowering::DAGCombinerInfo &DCI,
17075                                         const X86Subtarget *Subtarget) {
17076   // (vzext (bitcast (vzext (x)) -> (vzext x)
17077   SDValue In = N->getOperand(0);
17078   while (In.getOpcode() == ISD::BITCAST)
17079     In = In.getOperand(0);
17080
17081   if (In.getOpcode() != X86ISD::VZEXT)
17082     return SDValue();
17083
17084   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17085 }
17086
17087 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17088                                              DAGCombinerInfo &DCI) const {
17089   SelectionDAG &DAG = DCI.DAG;
17090   switch (N->getOpcode()) {
17091   default: break;
17092   case ISD::EXTRACT_VECTOR_ELT:
17093     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17094   case ISD::VSELECT:
17095   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17096   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17097   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17098   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17099   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17100   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17101   case ISD::SHL:
17102   case ISD::SRA:
17103   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17104   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17105   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17106   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17107   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17108   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17109   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17110   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17111   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17112   case X86ISD::FXOR:
17113   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17114   case X86ISD::FMIN:
17115   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17116   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17117   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17118   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17119   case ISD::ANY_EXTEND:
17120   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17121   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17122   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17123   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17124   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17125   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17126   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17127   case X86ISD::SHUFP:       // Handle all target specific shuffles
17128   case X86ISD::PALIGN:
17129   case X86ISD::UNPCKH:
17130   case X86ISD::UNPCKL:
17131   case X86ISD::MOVHLPS:
17132   case X86ISD::MOVLHPS:
17133   case X86ISD::PSHUFD:
17134   case X86ISD::PSHUFHW:
17135   case X86ISD::PSHUFLW:
17136   case X86ISD::MOVSS:
17137   case X86ISD::MOVSD:
17138   case X86ISD::VPERMILP:
17139   case X86ISD::VPERM2X128:
17140   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17141   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17142   }
17143
17144   return SDValue();
17145 }
17146
17147 /// isTypeDesirableForOp - Return true if the target has native support for
17148 /// the specified value type and it is 'desirable' to use the type for the
17149 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17150 /// instruction encodings are longer and some i16 instructions are slow.
17151 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17152   if (!isTypeLegal(VT))
17153     return false;
17154   if (VT != MVT::i16)
17155     return true;
17156
17157   switch (Opc) {
17158   default:
17159     return true;
17160   case ISD::LOAD:
17161   case ISD::SIGN_EXTEND:
17162   case ISD::ZERO_EXTEND:
17163   case ISD::ANY_EXTEND:
17164   case ISD::SHL:
17165   case ISD::SRL:
17166   case ISD::SUB:
17167   case ISD::ADD:
17168   case ISD::MUL:
17169   case ISD::AND:
17170   case ISD::OR:
17171   case ISD::XOR:
17172     return false;
17173   }
17174 }
17175
17176 /// IsDesirableToPromoteOp - This method query the target whether it is
17177 /// beneficial for dag combiner to promote the specified node. If true, it
17178 /// should return the desired promotion type by reference.
17179 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17180   EVT VT = Op.getValueType();
17181   if (VT != MVT::i16)
17182     return false;
17183
17184   bool Promote = false;
17185   bool Commute = false;
17186   switch (Op.getOpcode()) {
17187   default: break;
17188   case ISD::LOAD: {
17189     LoadSDNode *LD = cast<LoadSDNode>(Op);
17190     // If the non-extending load has a single use and it's not live out, then it
17191     // might be folded.
17192     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17193                                                      Op.hasOneUse()*/) {
17194       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17195              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17196         // The only case where we'd want to promote LOAD (rather then it being
17197         // promoted as an operand is when it's only use is liveout.
17198         if (UI->getOpcode() != ISD::CopyToReg)
17199           return false;
17200       }
17201     }
17202     Promote = true;
17203     break;
17204   }
17205   case ISD::SIGN_EXTEND:
17206   case ISD::ZERO_EXTEND:
17207   case ISD::ANY_EXTEND:
17208     Promote = true;
17209     break;
17210   case ISD::SHL:
17211   case ISD::SRL: {
17212     SDValue N0 = Op.getOperand(0);
17213     // Look out for (store (shl (load), x)).
17214     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17215       return false;
17216     Promote = true;
17217     break;
17218   }
17219   case ISD::ADD:
17220   case ISD::MUL:
17221   case ISD::AND:
17222   case ISD::OR:
17223   case ISD::XOR:
17224     Commute = true;
17225     // fallthrough
17226   case ISD::SUB: {
17227     SDValue N0 = Op.getOperand(0);
17228     SDValue N1 = Op.getOperand(1);
17229     if (!Commute && MayFoldLoad(N1))
17230       return false;
17231     // Avoid disabling potential load folding opportunities.
17232     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17233       return false;
17234     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17235       return false;
17236     Promote = true;
17237   }
17238   }
17239
17240   PVT = MVT::i32;
17241   return Promote;
17242 }
17243
17244 //===----------------------------------------------------------------------===//
17245 //                           X86 Inline Assembly Support
17246 //===----------------------------------------------------------------------===//
17247
17248 namespace {
17249   // Helper to match a string separated by whitespace.
17250   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17251     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17252
17253     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17254       StringRef piece(*args[i]);
17255       if (!s.startswith(piece)) // Check if the piece matches.
17256         return false;
17257
17258       s = s.substr(piece.size());
17259       StringRef::size_type pos = s.find_first_not_of(" \t");
17260       if (pos == 0) // We matched a prefix.
17261         return false;
17262
17263       s = s.substr(pos);
17264     }
17265
17266     return s.empty();
17267   }
17268   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17269 }
17270
17271 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17272   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17273
17274   std::string AsmStr = IA->getAsmString();
17275
17276   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17277   if (!Ty || Ty->getBitWidth() % 16 != 0)
17278     return false;
17279
17280   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17281   SmallVector<StringRef, 4> AsmPieces;
17282   SplitString(AsmStr, AsmPieces, ";\n");
17283
17284   switch (AsmPieces.size()) {
17285   default: return false;
17286   case 1:
17287     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17288     // we will turn this bswap into something that will be lowered to logical
17289     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17290     // lower so don't worry about this.
17291     // bswap $0
17292     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17293         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17294         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17295         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17296         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17297         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17298       // No need to check constraints, nothing other than the equivalent of
17299       // "=r,0" would be valid here.
17300       return IntrinsicLowering::LowerToByteSwap(CI);
17301     }
17302
17303     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17304     if (CI->getType()->isIntegerTy(16) &&
17305         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17306         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17307          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17308       AsmPieces.clear();
17309       const std::string &ConstraintsStr = IA->getConstraintString();
17310       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17311       std::sort(AsmPieces.begin(), AsmPieces.end());
17312       if (AsmPieces.size() == 4 &&
17313           AsmPieces[0] == "~{cc}" &&
17314           AsmPieces[1] == "~{dirflag}" &&
17315           AsmPieces[2] == "~{flags}" &&
17316           AsmPieces[3] == "~{fpsr}")
17317       return IntrinsicLowering::LowerToByteSwap(CI);
17318     }
17319     break;
17320   case 3:
17321     if (CI->getType()->isIntegerTy(32) &&
17322         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17323         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17324         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17325         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17326       AsmPieces.clear();
17327       const std::string &ConstraintsStr = IA->getConstraintString();
17328       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17329       std::sort(AsmPieces.begin(), AsmPieces.end());
17330       if (AsmPieces.size() == 4 &&
17331           AsmPieces[0] == "~{cc}" &&
17332           AsmPieces[1] == "~{dirflag}" &&
17333           AsmPieces[2] == "~{flags}" &&
17334           AsmPieces[3] == "~{fpsr}")
17335         return IntrinsicLowering::LowerToByteSwap(CI);
17336     }
17337
17338     if (CI->getType()->isIntegerTy(64)) {
17339       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17340       if (Constraints.size() >= 2 &&
17341           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17342           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17343         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17344         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17345             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17346             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17347           return IntrinsicLowering::LowerToByteSwap(CI);
17348       }
17349     }
17350     break;
17351   }
17352   return false;
17353 }
17354
17355 /// getConstraintType - Given a constraint letter, return the type of
17356 /// constraint it is for this target.
17357 X86TargetLowering::ConstraintType
17358 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17359   if (Constraint.size() == 1) {
17360     switch (Constraint[0]) {
17361     case 'R':
17362     case 'q':
17363     case 'Q':
17364     case 'f':
17365     case 't':
17366     case 'u':
17367     case 'y':
17368     case 'x':
17369     case 'Y':
17370     case 'l':
17371       return C_RegisterClass;
17372     case 'a':
17373     case 'b':
17374     case 'c':
17375     case 'd':
17376     case 'S':
17377     case 'D':
17378     case 'A':
17379       return C_Register;
17380     case 'I':
17381     case 'J':
17382     case 'K':
17383     case 'L':
17384     case 'M':
17385     case 'N':
17386     case 'G':
17387     case 'C':
17388     case 'e':
17389     case 'Z':
17390       return C_Other;
17391     default:
17392       break;
17393     }
17394   }
17395   return TargetLowering::getConstraintType(Constraint);
17396 }
17397
17398 /// Examine constraint type and operand type and determine a weight value.
17399 /// This object must already have been set up with the operand type
17400 /// and the current alternative constraint selected.
17401 TargetLowering::ConstraintWeight
17402   X86TargetLowering::getSingleConstraintMatchWeight(
17403     AsmOperandInfo &info, const char *constraint) const {
17404   ConstraintWeight weight = CW_Invalid;
17405   Value *CallOperandVal = info.CallOperandVal;
17406     // If we don't have a value, we can't do a match,
17407     // but allow it at the lowest weight.
17408   if (CallOperandVal == NULL)
17409     return CW_Default;
17410   Type *type = CallOperandVal->getType();
17411   // Look at the constraint type.
17412   switch (*constraint) {
17413   default:
17414     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17415   case 'R':
17416   case 'q':
17417   case 'Q':
17418   case 'a':
17419   case 'b':
17420   case 'c':
17421   case 'd':
17422   case 'S':
17423   case 'D':
17424   case 'A':
17425     if (CallOperandVal->getType()->isIntegerTy())
17426       weight = CW_SpecificReg;
17427     break;
17428   case 'f':
17429   case 't':
17430   case 'u':
17431       if (type->isFloatingPointTy())
17432         weight = CW_SpecificReg;
17433       break;
17434   case 'y':
17435       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17436         weight = CW_SpecificReg;
17437       break;
17438   case 'x':
17439   case 'Y':
17440     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17441         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17442       weight = CW_Register;
17443     break;
17444   case 'I':
17445     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17446       if (C->getZExtValue() <= 31)
17447         weight = CW_Constant;
17448     }
17449     break;
17450   case 'J':
17451     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17452       if (C->getZExtValue() <= 63)
17453         weight = CW_Constant;
17454     }
17455     break;
17456   case 'K':
17457     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17458       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17459         weight = CW_Constant;
17460     }
17461     break;
17462   case 'L':
17463     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17464       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17465         weight = CW_Constant;
17466     }
17467     break;
17468   case 'M':
17469     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17470       if (C->getZExtValue() <= 3)
17471         weight = CW_Constant;
17472     }
17473     break;
17474   case 'N':
17475     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17476       if (C->getZExtValue() <= 0xff)
17477         weight = CW_Constant;
17478     }
17479     break;
17480   case 'G':
17481   case 'C':
17482     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17483       weight = CW_Constant;
17484     }
17485     break;
17486   case 'e':
17487     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17488       if ((C->getSExtValue() >= -0x80000000LL) &&
17489           (C->getSExtValue() <= 0x7fffffffLL))
17490         weight = CW_Constant;
17491     }
17492     break;
17493   case 'Z':
17494     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17495       if (C->getZExtValue() <= 0xffffffff)
17496         weight = CW_Constant;
17497     }
17498     break;
17499   }
17500   return weight;
17501 }
17502
17503 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17504 /// with another that has more specific requirements based on the type of the
17505 /// corresponding operand.
17506 const char *X86TargetLowering::
17507 LowerXConstraint(EVT ConstraintVT) const {
17508   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17509   // 'f' like normal targets.
17510   if (ConstraintVT.isFloatingPoint()) {
17511     if (Subtarget->hasSSE2())
17512       return "Y";
17513     if (Subtarget->hasSSE1())
17514       return "x";
17515   }
17516
17517   return TargetLowering::LowerXConstraint(ConstraintVT);
17518 }
17519
17520 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17521 /// vector.  If it is invalid, don't add anything to Ops.
17522 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17523                                                      std::string &Constraint,
17524                                                      std::vector<SDValue>&Ops,
17525                                                      SelectionDAG &DAG) const {
17526   SDValue Result(0, 0);
17527
17528   // Only support length 1 constraints for now.
17529   if (Constraint.length() > 1) return;
17530
17531   char ConstraintLetter = Constraint[0];
17532   switch (ConstraintLetter) {
17533   default: break;
17534   case 'I':
17535     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17536       if (C->getZExtValue() <= 31) {
17537         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17538         break;
17539       }
17540     }
17541     return;
17542   case 'J':
17543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17544       if (C->getZExtValue() <= 63) {
17545         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17546         break;
17547       }
17548     }
17549     return;
17550   case 'K':
17551     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17552       if (isInt<8>(C->getSExtValue())) {
17553         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17554         break;
17555       }
17556     }
17557     return;
17558   case 'N':
17559     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17560       if (C->getZExtValue() <= 255) {
17561         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17562         break;
17563       }
17564     }
17565     return;
17566   case 'e': {
17567     // 32-bit signed value
17568     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17569       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17570                                            C->getSExtValue())) {
17571         // Widen to 64 bits here to get it sign extended.
17572         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17573         break;
17574       }
17575     // FIXME gcc accepts some relocatable values here too, but only in certain
17576     // memory models; it's complicated.
17577     }
17578     return;
17579   }
17580   case 'Z': {
17581     // 32-bit unsigned value
17582     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17583       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17584                                            C->getZExtValue())) {
17585         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17586         break;
17587       }
17588     }
17589     // FIXME gcc accepts some relocatable values here too, but only in certain
17590     // memory models; it's complicated.
17591     return;
17592   }
17593   case 'i': {
17594     // Literal immediates are always ok.
17595     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17596       // Widen to 64 bits here to get it sign extended.
17597       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17598       break;
17599     }
17600
17601     // In any sort of PIC mode addresses need to be computed at runtime by
17602     // adding in a register or some sort of table lookup.  These can't
17603     // be used as immediates.
17604     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17605       return;
17606
17607     // If we are in non-pic codegen mode, we allow the address of a global (with
17608     // an optional displacement) to be used with 'i'.
17609     GlobalAddressSDNode *GA = 0;
17610     int64_t Offset = 0;
17611
17612     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17613     while (1) {
17614       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17615         Offset += GA->getOffset();
17616         break;
17617       } else if (Op.getOpcode() == ISD::ADD) {
17618         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17619           Offset += C->getZExtValue();
17620           Op = Op.getOperand(0);
17621           continue;
17622         }
17623       } else if (Op.getOpcode() == ISD::SUB) {
17624         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17625           Offset += -C->getZExtValue();
17626           Op = Op.getOperand(0);
17627           continue;
17628         }
17629       }
17630
17631       // Otherwise, this isn't something we can handle, reject it.
17632       return;
17633     }
17634
17635     const GlobalValue *GV = GA->getGlobal();
17636     // If we require an extra load to get this address, as in PIC mode, we
17637     // can't accept it.
17638     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17639                                                         getTargetMachine())))
17640       return;
17641
17642     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17643                                         GA->getValueType(0), Offset);
17644     break;
17645   }
17646   }
17647
17648   if (Result.getNode()) {
17649     Ops.push_back(Result);
17650     return;
17651   }
17652   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17653 }
17654
17655 std::pair<unsigned, const TargetRegisterClass*>
17656 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17657                                                 EVT VT) const {
17658   // First, see if this is a constraint that directly corresponds to an LLVM
17659   // register class.
17660   if (Constraint.size() == 1) {
17661     // GCC Constraint Letters
17662     switch (Constraint[0]) {
17663     default: break;
17664       // TODO: Slight differences here in allocation order and leaving
17665       // RIP in the class. Do they matter any more here than they do
17666       // in the normal allocation?
17667     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17668       if (Subtarget->is64Bit()) {
17669         if (VT == MVT::i32 || VT == MVT::f32)
17670           return std::make_pair(0U, &X86::GR32RegClass);
17671         if (VT == MVT::i16)
17672           return std::make_pair(0U, &X86::GR16RegClass);
17673         if (VT == MVT::i8 || VT == MVT::i1)
17674           return std::make_pair(0U, &X86::GR8RegClass);
17675         if (VT == MVT::i64 || VT == MVT::f64)
17676           return std::make_pair(0U, &X86::GR64RegClass);
17677         break;
17678       }
17679       // 32-bit fallthrough
17680     case 'Q':   // Q_REGS
17681       if (VT == MVT::i32 || VT == MVT::f32)
17682         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17683       if (VT == MVT::i16)
17684         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17685       if (VT == MVT::i8 || VT == MVT::i1)
17686         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17687       if (VT == MVT::i64)
17688         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17689       break;
17690     case 'r':   // GENERAL_REGS
17691     case 'l':   // INDEX_REGS
17692       if (VT == MVT::i8 || VT == MVT::i1)
17693         return std::make_pair(0U, &X86::GR8RegClass);
17694       if (VT == MVT::i16)
17695         return std::make_pair(0U, &X86::GR16RegClass);
17696       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17697         return std::make_pair(0U, &X86::GR32RegClass);
17698       return std::make_pair(0U, &X86::GR64RegClass);
17699     case 'R':   // LEGACY_REGS
17700       if (VT == MVT::i8 || VT == MVT::i1)
17701         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17702       if (VT == MVT::i16)
17703         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17704       if (VT == MVT::i32 || !Subtarget->is64Bit())
17705         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17706       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17707     case 'f':  // FP Stack registers.
17708       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17709       // value to the correct fpstack register class.
17710       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17711         return std::make_pair(0U, &X86::RFP32RegClass);
17712       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17713         return std::make_pair(0U, &X86::RFP64RegClass);
17714       return std::make_pair(0U, &X86::RFP80RegClass);
17715     case 'y':   // MMX_REGS if MMX allowed.
17716       if (!Subtarget->hasMMX()) break;
17717       return std::make_pair(0U, &X86::VR64RegClass);
17718     case 'Y':   // SSE_REGS if SSE2 allowed
17719       if (!Subtarget->hasSSE2()) break;
17720       // FALL THROUGH.
17721     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17722       if (!Subtarget->hasSSE1()) break;
17723
17724       switch (VT.getSimpleVT().SimpleTy) {
17725       default: break;
17726       // Scalar SSE types.
17727       case MVT::f32:
17728       case MVT::i32:
17729         return std::make_pair(0U, &X86::FR32RegClass);
17730       case MVT::f64:
17731       case MVT::i64:
17732         return std::make_pair(0U, &X86::FR64RegClass);
17733       // Vector types.
17734       case MVT::v16i8:
17735       case MVT::v8i16:
17736       case MVT::v4i32:
17737       case MVT::v2i64:
17738       case MVT::v4f32:
17739       case MVT::v2f64:
17740         return std::make_pair(0U, &X86::VR128RegClass);
17741       // AVX types.
17742       case MVT::v32i8:
17743       case MVT::v16i16:
17744       case MVT::v8i32:
17745       case MVT::v4i64:
17746       case MVT::v8f32:
17747       case MVT::v4f64:
17748         return std::make_pair(0U, &X86::VR256RegClass);
17749       }
17750       break;
17751     }
17752   }
17753
17754   // Use the default implementation in TargetLowering to convert the register
17755   // constraint into a member of a register class.
17756   std::pair<unsigned, const TargetRegisterClass*> Res;
17757   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17758
17759   // Not found as a standard register?
17760   if (Res.second == 0) {
17761     // Map st(0) -> st(7) -> ST0
17762     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17763         tolower(Constraint[1]) == 's' &&
17764         tolower(Constraint[2]) == 't' &&
17765         Constraint[3] == '(' &&
17766         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17767         Constraint[5] == ')' &&
17768         Constraint[6] == '}') {
17769
17770       Res.first = X86::ST0+Constraint[4]-'0';
17771       Res.second = &X86::RFP80RegClass;
17772       return Res;
17773     }
17774
17775     // GCC allows "st(0)" to be called just plain "st".
17776     if (StringRef("{st}").equals_lower(Constraint)) {
17777       Res.first = X86::ST0;
17778       Res.second = &X86::RFP80RegClass;
17779       return Res;
17780     }
17781
17782     // flags -> EFLAGS
17783     if (StringRef("{flags}").equals_lower(Constraint)) {
17784       Res.first = X86::EFLAGS;
17785       Res.second = &X86::CCRRegClass;
17786       return Res;
17787     }
17788
17789     // 'A' means EAX + EDX.
17790     if (Constraint == "A") {
17791       Res.first = X86::EAX;
17792       Res.second = &X86::GR32_ADRegClass;
17793       return Res;
17794     }
17795     return Res;
17796   }
17797
17798   // Otherwise, check to see if this is a register class of the wrong value
17799   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17800   // turn into {ax},{dx}.
17801   if (Res.second->hasType(VT))
17802     return Res;   // Correct type already, nothing to do.
17803
17804   // All of the single-register GCC register classes map their values onto
17805   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17806   // really want an 8-bit or 32-bit register, map to the appropriate register
17807   // class and return the appropriate register.
17808   if (Res.second == &X86::GR16RegClass) {
17809     if (VT == MVT::i8) {
17810       unsigned DestReg = 0;
17811       switch (Res.first) {
17812       default: break;
17813       case X86::AX: DestReg = X86::AL; break;
17814       case X86::DX: DestReg = X86::DL; break;
17815       case X86::CX: DestReg = X86::CL; break;
17816       case X86::BX: DestReg = X86::BL; break;
17817       }
17818       if (DestReg) {
17819         Res.first = DestReg;
17820         Res.second = &X86::GR8RegClass;
17821       }
17822     } else if (VT == MVT::i32) {
17823       unsigned DestReg = 0;
17824       switch (Res.first) {
17825       default: break;
17826       case X86::AX: DestReg = X86::EAX; break;
17827       case X86::DX: DestReg = X86::EDX; break;
17828       case X86::CX: DestReg = X86::ECX; break;
17829       case X86::BX: DestReg = X86::EBX; break;
17830       case X86::SI: DestReg = X86::ESI; break;
17831       case X86::DI: DestReg = X86::EDI; break;
17832       case X86::BP: DestReg = X86::EBP; break;
17833       case X86::SP: DestReg = X86::ESP; break;
17834       }
17835       if (DestReg) {
17836         Res.first = DestReg;
17837         Res.second = &X86::GR32RegClass;
17838       }
17839     } else if (VT == MVT::i64) {
17840       unsigned DestReg = 0;
17841       switch (Res.first) {
17842       default: break;
17843       case X86::AX: DestReg = X86::RAX; break;
17844       case X86::DX: DestReg = X86::RDX; break;
17845       case X86::CX: DestReg = X86::RCX; break;
17846       case X86::BX: DestReg = X86::RBX; break;
17847       case X86::SI: DestReg = X86::RSI; break;
17848       case X86::DI: DestReg = X86::RDI; break;
17849       case X86::BP: DestReg = X86::RBP; break;
17850       case X86::SP: DestReg = X86::RSP; break;
17851       }
17852       if (DestReg) {
17853         Res.first = DestReg;
17854         Res.second = &X86::GR64RegClass;
17855       }
17856     }
17857   } else if (Res.second == &X86::FR32RegClass ||
17858              Res.second == &X86::FR64RegClass ||
17859              Res.second == &X86::VR128RegClass) {
17860     // Handle references to XMM physical registers that got mapped into the
17861     // wrong class.  This can happen with constraints like {xmm0} where the
17862     // target independent register mapper will just pick the first match it can
17863     // find, ignoring the required type.
17864
17865     if (VT == MVT::f32 || VT == MVT::i32)
17866       Res.second = &X86::FR32RegClass;
17867     else if (VT == MVT::f64 || VT == MVT::i64)
17868       Res.second = &X86::FR64RegClass;
17869     else if (X86::VR128RegClass.hasType(VT))
17870       Res.second = &X86::VR128RegClass;
17871     else if (X86::VR256RegClass.hasType(VT))
17872       Res.second = &X86::VR256RegClass;
17873   }
17874
17875   return Res;
17876 }
17877
17878 //===----------------------------------------------------------------------===//
17879 //
17880 // X86 cost model.
17881 //
17882 //===----------------------------------------------------------------------===//
17883
17884 struct X86CostTblEntry {
17885   int ISD;
17886   MVT Type;
17887   unsigned Cost;
17888 };
17889
17890 static int
17891 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
17892   for (unsigned int i = 0; i < len; ++i)
17893     if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
17894       return i;
17895
17896   // Could not find an entry.
17897   return -1;
17898 }
17899
17900 struct X86TypeConversionCostTblEntry {
17901   int ISD;
17902   MVT Dst;
17903   MVT Src;
17904   unsigned Cost;
17905 };
17906
17907 static int
17908 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
17909                    int ISD, MVT Dst, MVT Src) {
17910   for (unsigned int i = 0; i < len; ++i)
17911     if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
17912       return i;
17913
17914   // Could not find an entry.
17915   return -1;
17916 }
17917
17918 ScalarTargetTransformInfo::PopcntHwSupport
17919 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
17920   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
17921   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17922
17923   // TODO: Currently the __builtin_popcount() implementation using SSE3
17924   //   instructions is inefficient. Once the problem is fixed, we should
17925   //   call ST.hasSSE3() instead of ST.hasSSE4().
17926   return ST.hasSSE41() ? Fast : None;
17927 }
17928
17929 unsigned
17930 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
17931                                                      Type *Ty) const {
17932   // Legalize the type.
17933   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
17934
17935   int ISD = InstructionOpcodeToISD(Opcode);
17936   assert(ISD && "Invalid opcode");
17937
17938   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17939
17940   static const X86CostTblEntry AVX1CostTable[] = {
17941     // We don't have to scalarize unsupported ops. We can issue two half-sized
17942     // operations and we only need to extract the upper YMM half.
17943     // Two ops + 1 extract + 1 insert = 4.
17944     { ISD::MUL,     MVT::v8i32,    4 },
17945     { ISD::SUB,     MVT::v8i32,    4 },
17946     { ISD::ADD,     MVT::v8i32,    4 },
17947     { ISD::MUL,     MVT::v4i64,    4 },
17948     { ISD::SUB,     MVT::v4i64,    4 },
17949     { ISD::ADD,     MVT::v4i64,    4 },
17950     };
17951
17952   // Look for AVX1 lowering tricks.
17953   if (ST.hasAVX()) {
17954     int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
17955                           LT.second);
17956     if (Idx != -1)
17957       return LT.first * AVX1CostTable[Idx].Cost;
17958   }
17959   // Fallback to the default implementation.
17960   return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
17961 }
17962
17963 unsigned
17964 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
17965                                               unsigned Alignment,
17966                                               unsigned AddressSpace) const {
17967   // Legalize the type.
17968   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
17969   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
17970          "Invalid Opcode");
17971
17972   const X86Subtarget &ST =
17973   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17974
17975   // Each load/store unit costs 1.
17976   unsigned Cost = LT.first * 1;
17977
17978   // On Sandybridge 256bit load/stores are double pumped
17979   // (but not on Haswell).
17980   if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
17981     Cost*=2;
17982
17983   return Cost;
17984 }
17985
17986 unsigned
17987 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
17988                                                  unsigned Index) const {
17989   assert(Val->isVectorTy() && "This must be a vector type");
17990
17991   if (Index != -1U) {
17992     // Legalize the type.
17993     std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
17994
17995     // This type is legalized to a scalar type.
17996     if (!LT.second.isVector())
17997       return 0;
17998
17999     // The type may be split. Normalize the index to the new type.
18000     unsigned Width = LT.second.getVectorNumElements();
18001     Index = Index % Width;
18002
18003     // Floating point scalars are already located in index #0.
18004     if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18005       return 0;
18006   }
18007
18008   return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18009 }
18010
18011 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18012                                                           Type *ValTy,
18013                                                           Type *CondTy) const {
18014   // Legalize the type.
18015   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18016
18017   MVT MTy = LT.second;
18018
18019   int ISD = InstructionOpcodeToISD(Opcode);
18020   assert(ISD && "Invalid opcode");
18021
18022   const X86Subtarget &ST =
18023   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18024
18025   static const X86CostTblEntry SSE42CostTbl[] = {
18026     { ISD::SETCC,   MVT::v2f64,   1 },
18027     { ISD::SETCC,   MVT::v4f32,   1 },
18028     { ISD::SETCC,   MVT::v2i64,   1 },
18029     { ISD::SETCC,   MVT::v4i32,   1 },
18030     { ISD::SETCC,   MVT::v8i16,   1 },
18031     { ISD::SETCC,   MVT::v16i8,   1 },
18032   };
18033
18034   static const X86CostTblEntry AVX1CostTbl[] = {
18035     { ISD::SETCC,   MVT::v4f64,   1 },
18036     { ISD::SETCC,   MVT::v8f32,   1 },
18037     // AVX1 does not support 8-wide integer compare.
18038     { ISD::SETCC,   MVT::v4i64,   4 },
18039     { ISD::SETCC,   MVT::v8i32,   4 },
18040     { ISD::SETCC,   MVT::v16i16,  4 },
18041     { ISD::SETCC,   MVT::v32i8,   4 },
18042   };
18043
18044   static const X86CostTblEntry AVX2CostTbl[] = {
18045     { ISD::SETCC,   MVT::v4i64,   1 },
18046     { ISD::SETCC,   MVT::v8i32,   1 },
18047     { ISD::SETCC,   MVT::v16i16,  1 },
18048     { ISD::SETCC,   MVT::v32i8,   1 },
18049   };
18050
18051   if (ST.hasAVX2()) {
18052     int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18053     if (Idx != -1)
18054       return LT.first * AVX2CostTbl[Idx].Cost;
18055   }
18056
18057   if (ST.hasAVX()) {
18058     int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18059     if (Idx != -1)
18060       return LT.first * AVX1CostTbl[Idx].Cost;
18061   }
18062
18063   if (ST.hasSSE42()) {
18064     int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18065     if (Idx != -1)
18066       return LT.first * SSE42CostTbl[Idx].Cost;
18067   }
18068
18069   return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18070 }
18071
18072 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18073                                                         Type *Dst,
18074                                                         Type *Src) const {
18075   int ISD = InstructionOpcodeToISD(Opcode);
18076   assert(ISD && "Invalid opcode");
18077
18078   EVT SrcTy = TLI->getValueType(Src);
18079   EVT DstTy = TLI->getValueType(Dst);
18080
18081   if (!SrcTy.isSimple() || !DstTy.isSimple())
18082     return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18083
18084   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18085
18086   static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18087     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18088     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18089     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18090     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18091     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 1 },
18092     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32, 1 },
18093     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18094     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18095     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18096     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18097     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 1 },
18098     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
18099     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1,  6 },
18100     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1,  9 },
18101     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64, 3 },
18102   };
18103
18104   if (ST.hasAVX()) {
18105     int Idx = FindInConvertTable(AVXConversionTbl,
18106                                  array_lengthof(AVXConversionTbl),
18107                                  ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18108     if (Idx != -1)
18109       return AVXConversionTbl[Idx].Cost;
18110   }
18111
18112   return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18113 }
18114